";
@@ -2979,12 +2648,12 @@ public static function getContactActivitySelector(&$params) {
$activity['links'] = CRM_Core_Action::formLink($actionLinks,
$actionMask,
- array(
+ [
'id' => $values['activity_id'],
'cid' => $params['contact_id'],
'cxt' => $context,
'caseid' => CRM_Utils_Array::value('case_id', $values),
- ),
+ ],
ts('more'),
FALSE,
'activity.tab.row',
@@ -3000,7 +2669,7 @@ public static function getContactActivitySelector(&$params) {
}
}
- $activitiesDT = array();
+ $activitiesDT = [];
$activitiesDT['data'] = $contactActivities;
$activitiesDT['recordsTotal'] = $params['total'];
$activitiesDT['recordsFiltered'] = $params['total'];
@@ -3017,7 +2686,7 @@ public static function getContactActivitySelector(&$params) {
*/
public static function copyExtendedActivityData($params) {
// attach custom data to the new activity
- $customParams = $htmlType = array();
+ $customParams = $htmlType = [];
$customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($params['activityID'], 'Activity');
if (!empty($customValues)) {
@@ -3034,10 +2703,10 @@ public static function copyExtendedActivityData($params) {
// CRM-10542
if (in_array($key, $htmlType)) {
$fileValues = CRM_Core_BAO_File::path($value, $params['activityID']);
- $customParams["custom_{$key}_-1"] = array(
+ $customParams["custom_{$key}_-1"] = [
'name' => $fileValues[0],
- 'path' => $fileValues[1],
- );
+ 'type' => $fileValues[1],
+ ];
}
else {
$customParams["custom_{$key}_-1"] = $value;
@@ -3120,7 +2789,7 @@ public function setApiFilter(&$params) {
*
* @return bool
*/
- public static function sendToAssignee($activity, $mailToContacts, $params = array()) {
+ public static function sendToAssignee($activity, $mailToContacts, $params = []) {
if (!CRM_Utils_Array::crmIsEmptyArray($mailToContacts)) {
$clientID = CRM_Utils_Array::value('client_id', $params);
$caseID = CRM_Utils_Array::value('case_id', $params);
@@ -3136,4 +2805,14 @@ public static function sendToAssignee($activity, $mailToContacts, $params = arra
return FALSE;
}
+ /**
+ * @return array
+ */
+ public static function getEntityRefFilters() {
+ return [
+ ['key' => 'activity_type_id', 'value' => ts('Activity Type')],
+ ['key' => 'status_id', 'value' => ts('Activity Status')],
+ ];
+ }
+
}
diff --git a/CRM/Activity/BAO/ActivityAssignment.php b/CRM/Activity/BAO/ActivityAssignment.php
index 3f19f83cac1f..87420a3dc79f 100644
--- a/CRM/Activity/BAO/ActivityAssignment.php
+++ b/CRM/Activity/BAO/ActivityAssignment.php
@@ -1,9 +1,9 @@
array($activity_id, 'Integer')));
+ $assignment = CRM_Core_DAO::executeQuery($sql, [
+ 1 => [
+ $activity_id,
+ 'Integer',
+ ],
+ ]);
while ($assignment->fetch()) {
$assigneeArray[] = $assignment->contact_id;
}
@@ -108,7 +113,7 @@ public static function retrieveAssigneeIdsByActivityId($activity_id) {
* @return array
*/
public static function getAssigneeNames($activityIDs, $isDisplayName = FALSE, $skipDetails = TRUE) {
- $assigneeNames = array();
+ $assigneeNames = [];
if (empty($activityIDs)) {
return $assigneeNames;
}
diff --git a/CRM/Activity/BAO/ActivityContact.php b/CRM/Activity/BAO/ActivityContact.php
index ee63f83e7482..7039fba2f164 100644
--- a/CRM/Activity/BAO/ActivityContact.php
+++ b/CRM/Activity/BAO/ActivityContact.php
@@ -1,9 +1,9 @@
array($activityID, 'Integer'),
- 2 => array($recordTypeID, 'Integer'),
- );
+ $params = [
+ 1 => [$activityID, 'Integer'],
+ 2 => [$recordTypeID, 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
@@ -98,7 +98,7 @@ public static function getNames($activityID, $recordTypeID, $alsoIDs = FALSE) {
$ids[] = $dao->id;
}
- return $alsoIDs ? array($names, $ids) : $names;
+ return $alsoIDs ? [$names, $ids] : $names;
}
/**
@@ -110,7 +110,7 @@ public static function getNames($activityID, $recordTypeID, $alsoIDs = FALSE) {
* @return mixed
*/
public static function retrieveContactIdsByActivityId($activityID, $recordTypeID) {
- $activityContact = array();
+ $activityContact = [];
if (!CRM_Utils_Rule::positiveInteger($activityID) ||
!CRM_Utils_Rule::positiveInteger($recordTypeID)
) {
@@ -124,10 +124,10 @@ public static function retrieveContactIdsByActivityId($activityID, $recordTypeID
AND record_type_id = %2
AND civicrm_contact.is_deleted = 0
";
- $params = array(
- 1 => array($activityID, 'Integer'),
- 2 => array($recordTypeID, 'Integer'),
- );
+ $params = [
+ 1 => [$activityID, 'Integer'],
+ 2 => [$recordTypeID, 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
@@ -147,12 +147,12 @@ public static function retrieveContactIdsByActivityId($activityID, $recordTypeID
* @see DB_DataObject::getLink()
*
* @return array|null
- * array = if there are links defined for this table.
- * empty array - if there is a links.ini file, but no links on this table
- * null - if no links.ini exists for this database (hence try auto_links).
+ * array if there are links defined for this table.
+ * empty array - if there is a links.ini file, but no links on this table
+ * null - if no links.ini exists for this database (hence try auto_links).
*/
public function links() {
- $link = array('activity_id' => 'civicrm_activity:id');
+ $link = ['activity_id' => 'civicrm_activity:id'];
return $link;
}
diff --git a/CRM/Activity/BAO/ActivityTarget.php b/CRM/Activity/BAO/ActivityTarget.php
index 2c548156ac49..167857d1c33d 100644
--- a/CRM/Activity/BAO/ActivityTarget.php
+++ b/CRM/Activity/BAO/ActivityTarget.php
@@ -1,9 +1,9 @@
array($activity_id, 'Integer')));
+ $target = CRM_Core_DAO::executeQuery($sql, [
+ 1 => [
+ $activity_id,
+ 'Integer',
+ ],
+ ]);
while ($target->fetch()) {
$targetArray[] = $target->contact_id;
}
@@ -100,7 +105,7 @@ public static function retrieveTargetIdsByActivityId($activity_id) {
* @return array
*/
public static function getTargetNames($activityID) {
- $targetNames = array();
+ $targetNames = [];
if (empty($activityID)) {
return $targetNames;
@@ -116,7 +121,7 @@ public static function getTargetNames($activityID) {
AND civicrm_activity_contact.record_type_id = $targetID
AND contact_a.is_deleted = 0
";
- $queryParam = array(1 => array($activityID, 'Integer'));
+ $queryParam = [1 => [$activityID, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $queryParam);
while ($dao->fetch()) {
diff --git a/CRM/Activity/BAO/ICalendar.php b/CRM/Activity/BAO/ICalendar.php
index a94cd18e2438..cb2cb014eff7 100644
--- a/CRM/Activity/BAO/ICalendar.php
+++ b/CRM/Activity/BAO/ICalendar.php
@@ -1,9 +1,9 @@
get('activity_assignee_notification_ics')) {
- $config = &CRM_Core_Config::singleton();
- $this->icsfile = tempnam($config->customFileUploadDir, 'ics');
+ $this->icsfile = tempnam(CRM_Core_Config::singleton()->customFileUploadDir, 'ics');
if ($this->icsfile !== FALSE) {
rename($this->icsfile, $this->icsfile . '.ics');
$this->icsfile .= '.ics';
@@ -86,14 +85,14 @@ public function addAttachment(&$attachments, $contacts) {
$calendar = $template->fetch('CRM/Activity/Calendar/ICal.tpl');
if (file_put_contents($this->icsfile, $calendar) !== FALSE) {
if (empty($attachments)) {
- $attachments = array();
+ $attachments = [];
}
- $attachments['activity_ics'] = array(
+ $attachments['activity_ics'] = [
'mime_type' => 'text/calendar',
'fileName' => $icsFileName,
'cleanName' => $icsFileName,
'fullPath' => $this->icsfile,
- );
+ ];
return 'activity_ics';
}
}
@@ -105,7 +104,7 @@ public function addAttachment(&$attachments, $contacts) {
* Remove temp file.
*/
public function cleanup() {
- if (!empty ($this->icsfile)) {
+ if (!empty($this->icsfile)) {
@unlink($this->icsfile);
}
}
diff --git a/CRM/Activity/BAO/Query.php b/CRM/Activity/BAO/Query.php
index 2287312afa1f..8f7cd076b8f5 100644
--- a/CRM/Activity/BAO/Query.php
+++ b/CRM/Activity/BAO/Query.php
@@ -1,9 +1,9 @@
_returnProperties['source_contact'])) {
$query->_select['source_contact'] = 'source_contact.sort_name as source_contact';
$query->_element['source_contact'] = 1;
- $query->_tables['source_contact'] = $query->_whereTables['source_contact'] = 1;
+ $query->_tables['civicrm_activity'] = $query->_tables['source_contact'] = $query->_whereTables['source_contact'] = 1;
+ }
+
+ if (!empty($query->_returnProperties['source_contact_id'])) {
+ $query->_select['source_contact_id'] = 'source_contact.id as source_contact_id';
+ $query->_element['source_contact_id'] = 1;
+ $query->_tables['civicrm_activity'] = $query->_tables['source_contact'] = $query->_whereTables['source_contact'] = 1;
}
if (!empty($query->_returnProperties['activity_result'])) {
@@ -205,22 +211,30 @@ public static function whereClauseSingle(&$values, &$query) {
case 'activity_subject':
$qillName = $name;
- if (in_array($name, array('activity_engagement_level', 'activity_id'))) {
+ if (in_array($name, ['activity_engagement_level', 'activity_id'])) {
$name = $qillName = str_replace('activity_', '', $name);
}
- if (in_array($name, array('activity_status_id', 'activity_subject', 'activity_priority_id'))) {
+ if (in_array($name, [
+ 'activity_status_id',
+ 'activity_subject',
+ 'activity_priority_id',
+ ])) {
$name = str_replace('activity_', '', $name);
$qillName = str_replace('_id', '', $qillName);
}
if ($name == 'activity_campaign_id') {
- $name = 'campaign_id';
+ $name = 'campaign_id';
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_activity.$name", $op, $value, $dataType);
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Activity_DAO_Activity', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [
+ 1 => $fields[$qillName]['title'],
+ 2 => $op,
+ 3 => $value,
+ ]);
break;
case 'activity_text':
@@ -232,7 +246,11 @@ public static function whereClauseSingle(&$values, &$query) {
case 'activity_priority':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$name.label", $op, $value, 'String');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Activity_DAO_Activity', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$name]['title'], 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [
+ 1 => $fields[$name]['title'],
+ 2 => $op,
+ 3 => $value,
+ ]);
$query->_tables[$name] = $query->_whereTables[$name] = 1;
break;
@@ -282,14 +300,19 @@ public static function whereClauseSingle(&$values, &$query) {
case 'activity_date':
case 'activity_date_low':
case 'activity_date_high':
+ case 'activity_date_time_low':
+ case 'activity_date_time_high':
$query->dateQueryBuilder($values,
- 'civicrm_activity', 'activity_date', 'activity_date_time', ts('Activity Date')
+ 'civicrm_activity', str_replace([
+ '_high',
+ '_low',
+ ], '', $name), 'activity_date_time', ts('Activity Date')
);
break;
case 'activity_taglist':
$taglist = $value;
- $value = array();
+ $value = [];
foreach ($taglist as $val) {
if ($val) {
$val = explode(',', $val);
@@ -303,37 +326,37 @@ public static function whereClauseSingle(&$values, &$query) {
case 'activity_tags':
$value = array_keys($value);
- $activityTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
+ $activityTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
- $names = array();
+ $names = [];
if (is_array($value)) {
foreach ($value as $k => $v) {
$names[] = $activityTags[$v];
}
}
$query->_where[$grouping][] = "civicrm_activity_tag.tag_id IN (" . implode(",", $value) . ")";
- $query->_qill[$grouping][] = ts('Activity Tag %1', array(1 => $op)) . ' ' . implode(' ' . ts('OR') . ' ', $names);
+ $query->_qill[$grouping][] = ts('Activity Tag %1', [1 => $op]) . ' ' . implode(' ' . ts('OR') . ' ', $names);
$query->_tables['civicrm_activity_tag'] = $query->_whereTables['civicrm_activity_tag'] = 1;
break;
case 'activity_result':
if (is_array($value)) {
- $safe = NULL;
- while (list(, $k) = each($value)) {
+ $safe = [];
+ foreach ($value as $id => $k) {
$safe[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
}
$query->_where[$grouping][] = "civicrm_activity.result IN (" . implode(',', $safe) . ")";
- $query->_qill[$grouping][] = ts("Activity Result - %1", array(1 => implode(' or ', $safe)));
+ $query->_qill[$grouping][] = ts("Activity Result - %1", [1 => implode(' or ', $safe)]);
}
break;
case 'parent_id':
if ($value == 1) {
- $query->_where[$grouping][] = "parent_id.parent_id IS NOT NULL";
+ $query->_where[$grouping][] = "civicrm_activity.parent_id IS NOT NULL";
$query->_qill[$grouping][] = ts('Activities which have Followup Activities');
}
elseif ($value == 2) {
- $query->_where[$grouping][] = "parent_id.parent_id IS NULL";
+ $query->_where[$grouping][] = "civicrm_activity.parent_id IS NULL";
$query->_qill[$grouping][] = ts('Activities without Followup Activities');
}
break;
@@ -348,6 +371,18 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_qill[$grouping][] = ts('Activities which are not Followup Activities');
}
break;
+
+ case 'source_contact':
+ case 'source_contact_id':
+ $columnName = strstr($name, '_id') ? 'id' : 'sort_name';
+ $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("source_contact.{$columnName}", $op, $value, CRM_Utils_Type::typeToString($fields[$name]['type']));
+ list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Contact', $columnName, $value, $op);
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [
+ 1 => $fields[$name]['title'],
+ 2 => $op,
+ 3 => $value,
+ ]);
+ break;
}
}
@@ -399,12 +434,16 @@ public static function from($name, $mode, $side) {
break;
case 'source_contact':
- $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
- $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
+ $sourceID = CRM_Core_PseudoConstant::getKey(
+ 'CRM_Activity_BAO_ActivityContact',
+ 'record_type_id',
+ 'Activity Source'
+ );
$from = "
- LEFT JOIN civicrm_activity_contact ac
- ON ( ac.activity_id = civicrm_activity_contact.activity_id AND ac.record_type_id = {$sourceID})
- INNER JOIN civicrm_contact source_contact ON (ac.contact_id = source_contact.id)";
+ LEFT JOIN civicrm_activity_contact source_activity
+ ON (source_activity.activity_id = civicrm_activity_contact.activity_id
+ AND source_activity.record_type_id = {$sourceID})
+ LEFT JOIN civicrm_contact source_contact ON (source_activity.contact_id = source_contact.id)";
break;
case 'parent_id':
@@ -415,53 +454,74 @@ public static function from($name, $mode, $side) {
return $from;
}
+ /**
+ * Get the metadata for fields to be included on the activity search form.
+ *
+ * @todo ideally this would be a trait included on the activity search & advanced search
+ * rather than a static function.
+ */
+ public static function getSearchFieldMetadata() {
+ $fields = ['activity_type_id', 'activity_date_time'];
+ $metadata = civicrm_api3('Activity', 'getfields', [])['values'];
+ return array_intersect_key($metadata, array_flip($fields));
+ }
+
/**
* Add all the elements shared between case activity search and advanced search.
*
- * @param CRM_Core_Form $form
+ * @param CRM_Core_Form_Search $form
*/
public static function buildSearchForm(&$form) {
- $form->addSelect('activity_type_id',
- array('entity' => 'activity', 'label' => ts('Activity Type(s)'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
- );
+ $form->addSearchFieldMetadata(['Activity' => self::getSearchFieldMetadata()]);
+ $form->addFormFieldsFromMetadata();
- CRM_Core_Form_Date::buildDateRange($form, 'activity_date', 1, '_low', '_high', ts('From'), FALSE, FALSE);
- $form->addElement('hidden', 'activity_date_range_error');
- $form->addFormRule(array('CRM_Activity_BAO_Query', 'formRule'), $form);
-
- $followUpActivity = array(
+ $followUpActivity = [
1 => ts('Yes'),
2 => ts('No'),
- );
- $form->addRadio('parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
- $form->addRadio('followup_parent_id', NULL, $followUpActivity, array('allowClear' => TRUE));
- $activityRoles = array(
+ ];
+ $form->addRadio('parent_id', NULL, $followUpActivity, ['allowClear' => TRUE]);
+ $form->addRadio('followup_parent_id', NULL, $followUpActivity, ['allowClear' => TRUE]);
+ $activityRoles = [
3 => ts('With'),
2 => ts('Assigned to'),
1 => ts('Added by'),
- );
- $form->addRadio('activity_role', NULL, $activityRoles, array('allowClear' => TRUE));
- $form->setDefaults(array('activity_role' => 3));
- $activityStatus = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'status_id', array('flip' => 1, 'labelColumn' => 'name'));
+ ];
+ $form->addRadio('activity_role', NULL, $activityRoles, ['allowClear' => TRUE]);
+ $form->setDefaults(['activity_role' => 3]);
+ $activityStatus = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'status_id', [
+ 'flip' => 1,
+ 'labelColumn' => 'name',
+ ]);
$form->addSelect('status_id',
- array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
+ [
+ 'entity' => 'activity',
+ 'multiple' => 'multiple',
+ 'option_url' => NULL,
+ 'placeholder' => ts('- any -'),
+ ]
);
$ssID = $form->get('ssID');
- $status = array($activityStatus['Completed'], $activityStatus['Scheduled']);
+ $status = [$activityStatus['Completed'], $activityStatus['Scheduled']];
//If status is saved in smart group.
if (!empty($ssID) && !empty($form->_formValues['activity_status_id'])) {
$status = $form->_formValues['activity_status_id'];
}
- $form->setDefaults(array('status_id' => $status));
+ $form->setDefaults(['status_id' => $status]);
$form->addElement('text', 'activity_text', ts('Activity Text'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
$form->addRadio('activity_option', '', CRM_Core_SelectValues::activityTextOptions());
- $form->setDefaults(array('activity_option' => 'both'));
+ $form->setDefaults(['activity_option' => 'both']);
$priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
$form->addSelect('priority_id',
- array('entity' => 'activity', 'label' => ts('Priority'), 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
+ [
+ 'entity' => 'activity',
+ 'label' => ts('Priority'),
+ 'multiple' => 'multiple',
+ 'option_url' => NULL,
+ 'placeholder' => ts('- any -'),
+ ]
);
$form->addYesNo('activity_test', ts('Activity is a Test?'));
@@ -480,12 +540,12 @@ public static function buildSearchForm(&$form) {
$surveys = CRM_Campaign_BAO_Survey::getSurveys(TRUE, FALSE, FALSE, TRUE);
if ($surveys) {
$form->add('select', 'activity_survey_id', ts('Survey / Petition'),
- array('' => ts('- none -')) + $surveys, FALSE,
- array('class' => 'crm-select2')
- );
+ ['' => ts('- none -')] + $surveys, FALSE,
+ ['class' => 'crm-select2']
+ );
}
- CRM_Core_BAO_Query::addCustomFormFields($form, array('Activity'));
+ CRM_Core_BAO_Query::addCustomFormFields($form, ['Activity']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'activity_campaign_id');
@@ -496,16 +556,19 @@ public static function buildSearchForm(&$form) {
CRM_Campaign_BAO_Campaign::accessCampaign()
) {
$buildEngagementLevel = TRUE;
- $form->addSelect('activity_engagement_level', array('entity' => 'activity', 'context' => 'search'));
+ $form->addSelect('activity_engagement_level', [
+ 'entity' => 'activity',
+ 'context' => 'search',
+ ]);
// Add survey result field.
$optionGroups = CRM_Campaign_BAO_Survey::getResultSets('name');
- $resultOptions = array();
+ $resultOptions = [];
foreach ($optionGroups as $gid => $name) {
if ($name) {
$value = CRM_Core_OptionGroup::values($name);
if (!empty($value)) {
- while (list($k, $v) = each($value)) {
+ foreach ($value as $k => $v) {
$resultOptions[$v] = $v;
}
}
@@ -518,14 +581,18 @@ public static function buildSearchForm(&$form) {
asort($resultOptions);
$form->add('select', 'activity_result', ts("Survey Result"),
$resultOptions, FALSE,
- array('id' => 'activity_result', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ [
+ 'id' => 'activity_result',
+ 'multiple' => 'multiple',
+ 'class' => 'crm-select2',
+ ]
);
}
}
$form->assign('buildEngagementLevel', $buildEngagementLevel);
$form->assign('buildSurveyResult', $buildSurveyResult);
- $form->setDefaults(array('activity_test' => 0));
+ $form->setDefaults(['activity_test' => 0]);
}
/**
@@ -537,7 +604,7 @@ public static function buildSearchForm(&$form) {
public static function defaultReturnProperties($mode, $includeCustomFields = TRUE) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
- $properties = array(
+ $properties = [
'activity_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
@@ -559,7 +626,7 @@ public static function defaultReturnProperties($mode, $includeCustomFields = TRU
'result' => 1,
'activity_engagement_level' => 1,
'parent_id' => 1,
- );
+ ];
if ($includeCustomFields) {
// also get all the custom activity properties
@@ -582,7 +649,7 @@ public static function defaultReturnProperties($mode, $includeCustomFields = TRU
* kills a small kitten so add carefully.
*/
public static function selectorReturnProperties() {
- $properties = array(
+ $properties = [
'activity_id' => 1,
'contact_type' => 1,
'contact_sub_type' => 1,
@@ -597,36 +664,16 @@ public static function selectorReturnProperties() {
'activity_is_test' => 1,
'activity_campaign_id' => 1,
'activity_engagement_level' => 1,
- );
+ ];
return $properties;
}
- /**
- * Custom form rules.
- *
- * @param array $fields
- * @param array $files
- * @param CRM_Core_Form $form
- *
- * @return bool|array
- */
- public static function formRule($fields, $files, $form) {
- $errors = array();
-
- if (empty($fields['activity_date_low']) || empty($fields['activity_date_high'])) {
- return TRUE;
- }
-
- CRM_Utils_Rule::validDateRange($fields, 'activity_date', $errors, ts('Activity Date'));
-
- return empty($errors) ? TRUE : $errors;
- }
-
/**
* Where/qill clause for notes
*
* @param array $values
+ * @param object $query
*/
public static function whereClauseSingleActivityText(&$values, &$query) {
list($name, $op, $value, $grouping, $wildcard) = $values;
@@ -635,8 +682,8 @@ public static function whereClauseSingleActivityText(&$values, &$query) {
$query->_useDistinct = TRUE;
- $label = ts('Activity Text (%1)', array(1 => CRM_Utils_Array::value($activityOption, CRM_Core_SelectValues::activityTextOptions())));
- $clauses = array();
+ $label = ts('Activity Text (%1)', [1 => CRM_Utils_Array::value($activityOption, CRM_Core_SelectValues::activityTextOptions())]);
+ $clauses = [];
if ($activityOption % 2 == 0) {
$clauses[] = $query->buildClause('civicrm_activity.details', $op, $value, 'String');
}
@@ -646,7 +693,11 @@ public static function whereClauseSingleActivityText(&$values, &$query) {
$query->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
list($qillOp, $qillVal) = $query->buildQillForFieldValue(NULL, $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,
+ ]);
}
}
diff --git a/CRM/Activity/Controller/Search.php b/CRM/Activity/Controller/Search.php
index 1395d13f62ad..67f358a50d86 100644
--- a/CRM/Activity/Controller/Search.php
+++ b/CRM/Activity/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_activity';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'phone_id', 'civicrm_phone', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_activity', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'relationship_id', 'civicrm_relationship', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'original_id', 'civicrm_activity', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'phone_id', 'civicrm_phone', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_id', 'civicrm_activity', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'relationship_id', 'civicrm_relationship', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'original_id', 'civicrm_activity', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'activity_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'activity_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Activity ID') ,
- 'description' => 'Unique Other Activity ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Activity ID'),
+ 'description' => ts('Unique Other Activity ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_activity.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- ) ,
- 'source_record_id' => array(
+ ],
+ 'source_record_id' => [
'name' => 'source_record_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Source Record') ,
- 'description' => 'Artificial FK to original transaction (e.g. contribution) IF it is not an Activity. Table can be figured out through activity_type_id, and further through component registry.',
+ 'title' => ts('Source Record'),
+ 'description' => ts('Artificial FK to original transaction (e.g. contribution) IF it is not an Activity. Table can be figured out through activity_type_id, and further through component registry.'),
+ 'where' => 'civicrm_activity.source_record_id',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- ) ,
- 'activity_type_id' => array(
+ ],
+ 'activity_type_id' => [
'name' => 'activity_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Activity Type ID') ,
- 'description' => 'FK to civicrm_option_value.id, that has to be valid, registered activity type.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Activity Type ID'),
+ 'description' => ts('FK to civicrm_option_value.id, that has to be valid, registered activity type.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_activity.activity_type_id',
'headerPattern' => '/(activity.)?type(.id$)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'activity_type',
'optionEditPath' => 'civicrm/admin/options/activity_type',
- )
- ) ,
- 'activity_subject' => array(
+ ]
+ ],
+ 'activity_subject' => [
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Subject') ,
- 'description' => 'The subject/purpose/short description of the activity.',
+ 'title' => ts('Subject'),
+ 'description' => ts('The subject/purpose/short description of the activity.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_activity.subject',
'headerPattern' => '/(activity.)?subject/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'activity_date_time' => array(
+ ],
+ ],
+ 'activity_date_time' => [
'name' => 'activity_date_time',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Activity Date') ,
- 'description' => 'Date and time this activity is scheduled to occur. Formerly named scheduled_date_time.',
- 'import' => true,
+ 'title' => ts('Activity Date'),
+ 'description' => ts('Date and time this activity is scheduled to occur. Formerly named scheduled_date_time.'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.activity_date_time',
'headerPattern' => '/(activity.)?date(.time$)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'activity_duration' => array(
+ ],
+ ],
+ 'activity_duration' => [
'name' => 'duration',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Duration') ,
- 'description' => 'Planned or actual duration of activity expressed in minutes. Conglomerate of former duration_hours and duration_minutes.',
- 'import' => true,
+ 'title' => ts('Duration'),
+ 'description' => ts('Planned or actual duration of activity expressed in minutes. Conglomerate of former duration_hours and duration_minutes.'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.duration',
'headerPattern' => '/(activity.)?duration(s)?$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'activity_location' => array(
+ ],
+ ],
+ 'activity_location' => [
'name' => 'location',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Location') ,
- 'description' => 'Location of the activity (optional, open text).',
+ 'title' => ts('Location'),
+ 'description' => ts('Location of the activity (optional, open text).'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_activity.location',
'headerPattern' => '/(activity.)?location$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'phone_id' => array(
+ ],
+ ],
+ 'phone_id' => [
'name' => 'phone_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Phone (called) ID') ,
- 'description' => 'Phone ID of the number called (optional - used if an existing phone number is selected).',
+ 'title' => ts('Phone (called) ID'),
+ 'description' => ts('Phone ID of the number called (optional - used if an existing phone number is selected).'),
+ 'where' => 'civicrm_activity.phone_id',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Phone',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'phone_number' => array(
+ ],
+ ],
+ 'phone_number' => [
'name' => 'phone_number',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Phone (called) Number') ,
- 'description' => 'Phone number in case the number does not exist in the civicrm_phone table.',
+ 'title' => ts('Phone (called) Number'),
+ 'description' => ts('Phone number in case the number does not exist in the civicrm_phone table.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_activity.phone_number',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'activity_details' => array(
+ ],
+ ],
+ 'activity_details' => [
'name' => 'details',
'type' => CRM_Utils_Type::T_LONGTEXT,
- 'title' => ts('Details') ,
- 'description' => 'Details about the activity (agenda, notes, etc).',
- 'import' => true,
+ 'title' => ts('Details'),
+ 'description' => ts('Details about the activity (agenda, notes, etc).'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.details',
'headerPattern' => '/(activity.)?detail(s)?$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'RichTextEditor',
- ) ,
- ) ,
- 'activity_status_id' => array(
+ ],
+ ],
+ 'activity_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Activity Status') ,
- 'description' => 'ID of the status this activity is currently in. Foreign key to civicrm_option_value.',
- 'import' => true,
+ 'title' => ts('Activity Status'),
+ 'description' => ts('ID of the status this activity is currently in. Foreign key to civicrm_option_value.'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.status_id',
'headerPattern' => '/(activity.)?status(.label$)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'activity_status',
'optionEditPath' => 'civicrm/admin/options/activity_status',
- )
- ) ,
- 'priority_id' => array(
+ ]
+ ],
+ 'priority_id' => [
'name' => 'priority_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Priority') ,
- 'description' => 'ID of the priority given to this activity. Foreign key to civicrm_option_value.',
+ 'title' => ts('Priority'),
+ 'description' => ts('ID of the priority given to this activity. Foreign key to civicrm_option_value.'),
+ 'where' => 'civicrm_activity.priority_id',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'priority',
'optionEditPath' => 'civicrm/admin/options/priority',
- )
- ) ,
- 'parent_id' => array(
+ ]
+ ],
+ 'parent_id' => [
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Parent Activity Id') ,
- 'description' => 'Parent meeting ID (if this is a follow-up item). This is not currently implemented',
+ 'title' => ts('Parent Activity Id'),
+ 'description' => ts('Parent meeting ID (if this is a follow-up item). This is not currently implemented'),
+ 'where' => 'civicrm_activity.parent_id',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
- ) ,
- 'activity_is_test' => array(
+ ],
+ 'activity_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.is_test',
'headerPattern' => '/(is.)?test(.activity)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'activity_medium_id' => array(
+ ],
+ ],
+ 'activity_medium_id' => [
'name' => 'medium_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Activity Medium') ,
- 'description' => 'Activity Medium, Implicit FK to civicrm_option_value where option_group = encounter_medium.',
+ 'title' => ts('Activity Medium'),
+ 'description' => ts('Activity Medium, Implicit FK to civicrm_option_value where option_group = encounter_medium.'),
+ 'where' => 'civicrm_activity.medium_id',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'encounter_medium',
'optionEditPath' => 'civicrm/admin/options/encounter_medium',
- )
- ) ,
- 'is_auto' => array(
+ ]
+ ],
+ 'is_auto' => [
'name' => 'is_auto',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Auto') ,
+ 'title' => ts('Auto'),
+ 'where' => 'civicrm_activity.is_auto',
+ 'default' => '0',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- ) ,
- 'relationship_id' => array(
+ ],
+ 'relationship_id' => [
'name' => 'relationship_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Relationship Id') ,
- 'description' => 'FK to Relationship ID',
+ 'title' => ts('Relationship Id'),
+ 'description' => ts('FK to Relationship ID'),
+ 'where' => 'civicrm_activity.relationship_id',
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Relationship',
- ) ,
- 'is_current_revision' => array(
+ ],
+ 'is_current_revision' => [
'name' => 'is_current_revision',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is this activity a current revision in versioning chain?') ,
- 'import' => true,
+ 'title' => ts('Is this activity a current revision in versioning chain?'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.is_current_revision',
'headerPattern' => '/(is.)?(current.)?(revision|version(ing)?)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'original_id' => array(
+ ],
+ ],
+ 'original_id' => [
'name' => 'original_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Original Activity ID ') ,
- 'description' => 'Activity ID of the first activity record in versioning chain.',
+ 'title' => ts('Original Activity ID '),
+ 'description' => ts('Activity ID of the first activity record in versioning chain.'),
+ 'where' => 'civicrm_activity.original_id',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
- ) ,
- 'activity_result' => array(
+ ],
+ 'activity_result' => [
'name' => 'result',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Result') ,
- 'description' => 'Currently being used to store result id for survey activity, FK to option value.',
+ 'title' => ts('Result'),
+ 'description' => ts('Currently being used to store result id for survey activity, FK to option value.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_activity.result',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'activity_is_deleted' => array(
+ ],
+ ],
+ 'activity_is_deleted' => [
'name' => 'is_deleted',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Activity is in the Trash') ,
- 'import' => true,
+ 'title' => ts('Activity is in the Trash'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.is_deleted',
'headerPattern' => '/(activity.)?(trash|deleted)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'activity_campaign_id' => array(
+ ],
+ ],
+ 'activity_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this activity has been triggered.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this activity has been triggered.'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'activity_engagement_level' => array(
+ ]
+ ],
+ 'activity_engagement_level' => [
'name' => 'engagement_level',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Engagement Index') ,
- 'description' => 'Assign a specific level of engagement to this activity. Used for tracking constituents in ladder of engagement.',
- 'import' => true,
+ 'title' => ts('Engagement Index'),
+ 'description' => ts('Assign a specific level of engagement to this activity. Used for tracking constituents in ladder of engagement.'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.engagement_level',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'engagement_index',
'optionEditPath' => 'civicrm/admin/options/engagement_index',
- )
- ) ,
- 'weight' => array(
+ ]
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
+ 'title' => ts('Order'),
+ 'where' => 'civicrm_activity.weight',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_star' => array(
+ ],
+ ],
+ 'is_star' => [
'name' => 'is_star',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Starred') ,
- 'description' => 'Activity marked as favorite.',
- 'import' => true,
+ 'title' => ts('Is Starred'),
+ 'description' => ts('Activity marked as favorite.'),
+ 'import' => TRUE,
'where' => 'civicrm_activity.is_star',
'headerPattern' => '/(activity.)?(star|favorite)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- ) ,
- 'activity_created_date' => array(
+ ],
+ 'activity_created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Created Date') ,
- 'description' => 'When was the activity was created.',
- 'required' => false,
- 'export' => true,
+ 'title' => ts('Created Date'),
+ 'description' => ts('When was the activity was created.'),
+ 'required' => FALSE,
'where' => 'civicrm_activity.created_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- ) ,
- 'activity_modified_date' => array(
+ ],
+ 'activity_modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Modified Date') ,
- 'description' => 'When was the activity (or closely related entity) was created or modified or deleted.',
- 'required' => false,
- 'export' => true,
+ 'title' => ts('Modified Date'),
+ 'description' => ts('When was the activity (or closely related entity) was created or modified or deleted.'),
+ 'required' => FALSE,
'where' => 'civicrm_activity.modified_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'table_name' => 'civicrm_activity',
'entity' => 'Activity',
'bao' => 'CRM_Activity_BAO_Activity',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -726,10 +726,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -737,72 +738,78 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_source_record_id' => array(
+ $indices = [
+ 'UI_source_record_id' => [
'name' => 'UI_source_record_id',
- 'field' => array(
+ 'field' => [
0 => 'source_record_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::source_record_id',
- ) ,
- 'UI_activity_type_id' => array(
+ ],
+ 'UI_activity_type_id' => [
'name' => 'UI_activity_type_id',
- 'field' => array(
+ 'field' => [
0 => 'activity_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::activity_type_id',
- ) ,
- 'index_activity_date_time' => array(
+ ],
+ 'index_activity_date_time' => [
'name' => 'index_activity_date_time',
- 'field' => array(
+ 'field' => [
0 => 'activity_date_time',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::activity_date_time',
- ) ,
- 'index_status_id' => array(
+ ],
+ 'index_status_id' => [
'name' => 'index_status_id',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::status_id',
- ) ,
- 'index_medium_id' => array(
+ ],
+ 'index_medium_id' => [
'name' => 'index_medium_id',
- 'field' => array(
+ 'field' => [
0 => 'medium_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::medium_id',
- ) ,
- 'index_is_current_revision' => array(
+ ],
+ 'index_is_current_revision' => [
'name' => 'index_is_current_revision',
- 'field' => array(
+ 'field' => [
0 => 'is_current_revision',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::is_current_revision',
- ) ,
- 'index_is_deleted' => array(
+ ],
+ 'index_is_deleted' => [
'name' => 'index_is_deleted',
- 'field' => array(
+ 'field' => [
0 => 'is_deleted',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity::0::is_deleted',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Activity/DAO/ActivityContact.php b/CRM/Activity/DAO/ActivityContact.php
index bb95eb6fddbc..1eaa7ca8256d 100644
--- a/CRM/Activity/DAO/ActivityContact.php
+++ b/CRM/Activity/DAO/ActivityContact.php
@@ -1,199 +1,188 @@
__table = 'civicrm_activity_contact';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'activity_id', 'civicrm_activity', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'activity_id', 'civicrm_activity', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Activity Contact ID') ,
- 'description' => 'Activity contact id',
- 'required' => true,
+ 'title' => ts('Activity Contact ID'),
+ 'description' => ts('Activity contact id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_activity_contact.id',
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
- ) ,
- 'activity_id' => array(
+ ],
+ 'activity_id' => [
'name' => 'activity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Activity ID') ,
- 'description' => 'Foreign key to the activity for this record.',
- 'required' => true,
+ 'title' => ts('Activity ID'),
+ 'description' => ts('Foreign key to the activity for this record.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_activity_contact.activity_id',
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'FKClassName' => 'CRM_Activity_DAO_Activity',
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID (match to contact)') ,
- 'description' => 'Foreign key to the contact for this record.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID (match to contact)'),
+ 'description' => ts('Foreign key to the contact for this record.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_activity_contact.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'record_type_id' => array(
+ ],
+ 'record_type_id' => [
'name' => 'record_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Record Type ID') ,
- 'description' => 'Nature of this contact\'s role in the activity: 1 assignee, 2 creator, 3 focus or target.',
+ 'title' => ts('Record Type ID'),
+ 'description' => ts('Nature of this contact\'s role in the activity: 1 assignee, 2 creator, 3 focus or target.'),
+ 'where' => 'civicrm_activity_contact.record_type_id',
'table_name' => 'civicrm_activity_contact',
'entity' => 'ActivityContact',
'bao' => 'CRM_Activity_BAO_ActivityContact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'activity_contacts',
'optionEditPath' => 'civicrm/admin/options/activity_contacts',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -201,10 +190,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity_contact', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'activity_contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -212,36 +202,42 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity_contact', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'activity_contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_activity_contact' => array(
+ $indices = [
+ 'UI_activity_contact' => [
'name' => 'UI_activity_contact',
- 'field' => array(
+ 'field' => [
0 => 'contact_id',
1 => 'activity_id',
2 => 'record_type_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_activity_contact::1::contact_id::activity_id::record_type_id',
- ) ,
- 'index_record_type' => array(
+ ],
+ 'index_record_type' => [
'name' => 'index_record_type',
- 'field' => array(
+ 'field' => [
0 => 'activity_id',
1 => 'record_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_activity_contact::0::activity_id::record_type_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Activity/Form/Activity.php b/CRM/Activity/Form/Activity.php
index 7187c523d3a9..a3fef8d7d8f0 100644
--- a/CRM/Activity/Form/Activity.php
+++ b/CRM/Activity/Form/Activity.php
@@ -1,9 +1,9 @@
_fields = array(
- 'subject' => array(
+ $this->_fields = [
+ 'subject' => [
'type' => 'text',
'label' => ts('Subject'),
- 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
- 'subject'
- ),
- ),
- 'duration' => array(
- 'type' => 'text',
+ 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'activity_subject'),
+ ],
+ 'duration' => [
+ 'type' => 'number',
'label' => ts('Duration'),
- 'attributes' => array('size' => 4, 'maxlength' => 8),
+ 'attributes' => ['class' => 'four', 'min' => 1],
'required' => FALSE,
- ),
- 'location' => array(
+ ],
+ 'location' => [
'type' => 'text',
'label' => ts('Location'),
'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'location'),
'required' => FALSE,
- ),
- 'details' => array(
+ ],
+ 'details' => [
'type' => 'wysiwyg',
'label' => ts('Details'),
- 'attributes' => array('class' => 'huge'),
+ 'attributes' => ['class' => 'huge'],
'required' => FALSE,
- ),
- 'status_id' => array(
+ ],
+ 'status_id' => [
'type' => 'select',
'required' => TRUE,
- ),
- 'priority_id' => array(
+ ],
+ 'priority_id' => [
'type' => 'select',
'required' => TRUE,
- ),
- 'source_contact_id' => array(
+ ],
+ 'source_contact_id' => [
'type' => 'entityRef',
'label' => ts('Added By'),
'required' => FALSE,
- ),
- 'target_contact_id' => array(
+ ],
+ 'target_contact_id' => [
'type' => 'entityRef',
'label' => ts('With Contact'),
- 'attributes' => array('multiple' => TRUE, 'create' => TRUE),
- ),
- 'assignee_contact_id' => array(
+ 'attributes' => ['multiple' => TRUE, 'create' => TRUE],
+ ],
+ 'assignee_contact_id' => [
'type' => 'entityRef',
'label' => ts('Assigned to'),
- 'attributes' => array(
+ 'attributes' => [
'multiple' => TRUE,
'create' => TRUE,
- 'api' => array('params' => array('is_deceased' => 0)),
- ),
- ),
- 'followup_assignee_contact_id' => array(
+ 'api' => ['params' => ['is_deceased' => 0]],
+ ],
+ ],
+ 'activity_date_time' => [
+ 'type' => 'datepicker',
+ 'label' => ts('Date'),
+ 'required' => TRUE,
+ ],
+ 'followup_assignee_contact_id' => [
'type' => 'entityRef',
'label' => ts('Assigned to'),
- 'attributes' => array(
+ 'attributes' => [
'multiple' => TRUE,
'create' => TRUE,
- 'api' => array('params' => array('is_deceased' => 0)),
- ),
- ),
- 'followup_activity_type_id' => array(
+ 'api' => ['params' => ['is_deceased' => 0]],
+ ],
+ ],
+ 'followup_activity_type_id' => [
'type' => 'select',
'label' => ts('Followup Activity'),
- 'attributes' => array('' => '- ' . ts('select activity') . ' -') + $activityTypes,
- 'extra' => array('class' => 'crm-select2'),
- ),
+ 'attributes' => ['' => '- ' . ts('select activity') . ' -'] + $activityTypes,
+ 'extra' => ['class' => 'crm-select2'],
+ ],
// Add optional 'Subject' field for the Follow-up Activiity, CRM-4491
- 'followup_activity_subject' => array(
+ 'followup_activity_subject' => [
'type' => 'text',
'label' => ts('Subject'),
- 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
- 'subject'
- ),
- ),
- );
+ 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity', 'subject'),
+ ],
+ ];
}
/**
@@ -238,11 +259,11 @@ public function preProcess() {
// Give the context.
if (!isset($this->_context)) {
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
if (CRM_Contact_Form_Search::isSearchContext($this->_context)) {
$this->_context = 'search';
}
- elseif (!in_array($this->_context, array('dashlet', 'dashletFullscreen'))
+ elseif (!in_array($this->_context, ['dashlet', 'case', 'dashletFullscreen'])
&& $this->_currentlyViewedContactId
) {
$this->_context = 'activity';
@@ -279,10 +300,10 @@ public function preProcess() {
// Check for required permissions, CRM-6264.
if ($this->_activityId &&
- in_array($this->_action, array(
+ in_array($this->_action, [
CRM_Core_Action::UPDATE,
CRM_Core_Action::VIEW,
- )) &&
+ ]) &&
!CRM_Activity_BAO_Activity::checkPermission($this->_activityId, $this->_action)
) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
@@ -291,6 +312,7 @@ public function preProcess() {
CRM_Activity_BAO_Activity::checkPermission($this->_activityId, CRM_Core_Action::UPDATE)
) {
$this->assign('permission', 'edit');
+ $this->assign('allow_edit_inbound_emails', CRM_Activity_BAO_Activity::checkEditInboundEmailsPermissions());
}
if (!$this->_activityTypeId && $this->_activityId) {
@@ -312,7 +334,6 @@ public function preProcess() {
// Set title.
if (isset($activityTName)) {
$activityName = CRM_Utils_Array::value($this->_activityTypeId, $activityTName);
- $this->assign('pageTitle', ts('%1 Activity', array(1 => $activityName)));
if ($this->_currentlyViewedContactId) {
$displayName = CRM_Contact_BAO_Contact::displayName($this->_currentlyViewedContactId);
@@ -323,7 +344,7 @@ public function preProcess() {
CRM_Utils_System::setTitle($displayName . ' - ' . $activityName);
}
else {
- CRM_Utils_System::setTitle(ts('%1 Activity', array(1 => $activityName)));
+ CRM_Utils_System::setTitle(ts('%1 Activity', [1 => $activityName]));
}
}
@@ -415,12 +436,12 @@ public function preProcess() {
}
$this->assign('searchKey', $qfKey);
}
- elseif (in_array($this->_context, array(
+ elseif (in_array($this->_context, [
'standalone',
'home',
'dashlet',
'dashletFullscreen',
- ))
+ ])
) {
$urlParams = 'reset=1';
$urlString = 'civicrm/dashboard';
@@ -494,17 +515,40 @@ public function preProcess() {
$this->_values = $this->get('values');
if (!is_array($this->_values)) {
- $this->_values = array();
+ $this->_values = [];
if (isset($this->_activityId) && $this->_activityId) {
- $params = array('id' => $this->_activityId);
+ $params = ['id' => $this->_activityId];
CRM_Activity_BAO_Activity::retrieve($params, $this->_values);
}
+
$this->set('values', $this->_values);
}
if ($this->_action & CRM_Core_Action::UPDATE) {
+ // We filter out alternatives, in case this is a stored e-mail, before sending to front-end
+ if (isset($this->_values['details'])) {
+ $this->_values['details'] = CRM_Utils_String::stripAlternatives($this->_values['details']) ?: '';
+ }
+
+ if ($this->_activityTypeName === 'Inbound Email' &&
+ !CRM_Core_Permission::check('edit inbound email basic information and content')
+ ) {
+ $this->_fields['details']['type'] = 'static';
+ }
+
CRM_Core_Form_RecurringEntity::preProcess('civicrm_activity');
}
+
+ if ($this->_action & CRM_Core_Action::VIEW) {
+ $url = CRM_Utils_System::url(implode("/", $this->urlPath), "reset=1&id={$this->_activityId}&action=view&cid={$this->_values['source_contact_id']}");
+ CRM_Utils_Recent::add(CRM_Utils_Array::value('subject', $this->_values, ts('(no subject)')),
+ $url,
+ $this->_values['id'],
+ 'Activity',
+ $this->_values['source_contact_id'],
+ $this->_values['source_contact']
+ );
+ }
}
/**
@@ -519,16 +563,6 @@ public function setDefaultValues() {
$defaults = $this->_values + CRM_Core_Form_RecurringEntity::setDefaultValues();
// if we're editing...
if (isset($this->_activityId)) {
- if (empty($defaults['activity_date_time'])) {
- list($defaults['activity_date_time'], $defaults['activity_date_time_time']) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
- }
- elseif ($this->_action & CRM_Core_Action::UPDATE) {
- $this->assign('current_activity_date_time', $defaults['activity_date_time']);
- list($defaults['activity_date_time'],
- $defaults['activity_date_time_time']
- ) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
- list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['activity_date_time'], 'activityDateTime');
- }
if ($this->_context != 'standalone') {
$this->assign('target_contact_value',
@@ -553,9 +587,10 @@ public function setDefaultValues() {
$defaults['source_contact_id'] = $this->_sourceContactId;
$defaults['target_contact_id'] = $this->_targetContactId;
+ }
- list($defaults['activity_date_time'], $defaults['activity_date_time_time'])
- = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
+ if (empty($defaults['activity_date_time'])) {
+ $defaults['activity_date_time'] = date('Y-m-d H:i:s');
}
if ($this->_activityTypeId) {
@@ -567,10 +602,10 @@ public function setDefaultValues() {
}
// CRM-15472 - 50 is around the practical limit of how many items a select2 entityRef can handle
- if ($this->_action == 2 && !empty($defaults['target_contact_id'])) {
+ if ($this->_action == CRM_Core_Action::UPDATE && !empty($defaults['target_contact_id'])) {
$count = count(is_array($defaults['target_contact_id']) ? $defaults['target_contact_id'] : explode(',', $defaults['target_contact_id']));
if ($count > 50) {
- $this->freeze(array('target_contact_id'));
+ $this->freeze(['target_contact_id']);
}
}
@@ -601,18 +636,18 @@ public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::RENEW) {
$button = ts('Restore');
}
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => $button,
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
return;
}
@@ -623,11 +658,11 @@ public function buildQuickForm() {
$this->assign('suppressForm', FALSE);
$element = &$this->add('select', 'activity_type_id', ts('Activity Type'),
- array('' => '- ' . ts('select') . ' -') + $this->_fields['followup_activity_type_id']['attributes'],
- FALSE, array(
+ ['' => '- ' . ts('select') . ' -'] + $this->_fields['followup_activity_type_id']['attributes'],
+ FALSE, [
'onchange' => "CRM.buildCustomData( 'Activity', this.value );",
'class' => 'crm-select2 required',
- )
+ ]
);
// Freeze for update mode.
@@ -646,7 +681,7 @@ public function buildQuickForm() {
$required = !empty($values['required']);
if ($values['type'] == 'select' && empty($attribute)) {
- $this->addSelect($field, array('entity' => 'activity'), $required);
+ $this->addSelect($field, ['entity' => 'activity'], $required);
}
elseif ($values['type'] == 'entityRef') {
$this->addEntityRef($field, $values['label'], $attribute, $required);
@@ -666,7 +701,7 @@ public function buildQuickForm() {
CRM_Campaign_BAO_Campaign::accessCampaign()
) {
$buildEngagementLevel = TRUE;
- $this->addSelect('engagement_level', array('entity' => 'activity'));
+ $this->addSelect('engagement_level', ['entity' => 'activity']);
$this->addRule('engagement_level',
ts('Please enter the engagement index as a number (integers only).'),
'positiveInteger'
@@ -690,7 +725,7 @@ public function buildQuickForm() {
$responseOptions = CRM_Campaign_BAO_Survey::getResponsesOptions($surveyId);
if ($responseOptions) {
$this->add('select', 'result', ts('Result'),
- array('' => ts('- select -')) + array_combine($responseOptions, $responseOptions)
+ ['' => ts('- select -')] + array_combine($responseOptions, $responseOptions)
);
}
$surveyTitle = NULL;
@@ -702,18 +737,26 @@ public function buildQuickForm() {
}
$this->assign('surveyActivity', $this->_isSurveyActivity);
- // this option should be available only during add mode
- if ($this->_action != CRM_Core_Action::UPDATE) {
- $this->add('advcheckbox', 'is_multi_activity', ts('Create a separate activity for each contact.'));
+ // Add the "Activity Separation" field
+ $actionIsAdd = $this->_action != CRM_Core_Action::UPDATE;
+ $separationIsPossible = $this->supportsActivitySeparation;
+ if ($actionIsAdd && $separationIsPossible) {
+ $this->addRadio(
+ 'separation',
+ ts('Activity Separation'),
+ [
+ 'separate' => ts('Create separate activities for each contact'),
+ 'combined' => ts('Create one activity with all contacts together'),
+ ]
+ );
}
$this->addRule('duration',
ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger'
);
- $this->addDateTime('activity_date_time', ts('Date'), TRUE, array('formatType' => 'activityDateTime'));
// Add followup date.
- $this->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'followup_date', ts('in'));
// Only admins and case-workers can change the activity source
if (!CRM_Core_Permission::check('administer CiviCRM') && $this->_context != 'caseActivity') {
@@ -728,11 +771,15 @@ public function buildQuickForm() {
$tags = CRM_Core_BAO_Tag::getColorTags('civicrm_activity');
if (!empty($tags)) {
- $this->add('select2', 'tag', ts('Tags'), $tags, FALSE, array('class' => 'huge', 'placeholder' => ts('- select -'), 'multiple' => TRUE));
+ $this->add('select2', 'tag', ts('Tags'), $tags, FALSE, [
+ 'class' => 'huge',
+ 'placeholder' => ts('- select -'),
+ 'multiple' => TRUE,
+ ]);
}
// we need to hide activity tagset for special activities
- $specialActivities = array('Open Case');
+ $specialActivities = ['Open Case'];
if (!in_array($this->_activityTypeName, $specialActivities)) {
// build tag widget
@@ -748,48 +795,47 @@ public function buildQuickForm() {
// form should be frozen for view mode
$this->freeze();
- $buttons = array();
- $buttons[] = array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- );
- $this->addButtons($buttons);
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
else {
- $message = array(
- 'completed' => ts('Are you sure? This is a COMPLETED activity with the DATE in the FUTURE. Click Cancel to change the date / status. Otherwise, click OK to save.'),
- 'scheduled' => ts('Are you sure? This is a SCHEDULED activity with the DATE in the PAST. Click Cancel to change the date / status. Otherwise, click OK to save.'),
- );
- $js = array('onclick' => "return activityStatus(" . json_encode($message) . ");");
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
- 'js' => $js,
'isDefault' => TRUE,
- ),
- array(
+ 'submitOnce' => TRUE,
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
if ($this->_activityTypeFile) {
$className = "CRM_{$this->_crmDir}_Form_Activity_{$this->_activityTypeFile}";
$className::buildQuickForm($this);
- $this->addFormRule(array($className, 'formRule'), $this);
+ $this->addFormRule([$className, 'formRule'], $this);
}
- $this->addFormRule(array('CRM_Activity_Form_Activity', 'formRule'), $this);
+ $this->addFormRule(['CRM_Activity_Form_Activity', 'formRule'], $this);
- if (Civi::settings()->get('activity_assignee_notification')) {
- $this->assign('activityAssigneeNotification', TRUE);
+ $doNotNotifyAssigneeFor = (array) Civi::settings()
+ ->get('do_not_notify_assignees_for');
+ if (($this->_activityTypeId && in_array($this->_activityTypeId, $doNotNotifyAssigneeFor)) || !Civi::settings()
+ ->get('activity_assignee_notification')) {
+ $this->assign('activityAssigneeNotification', FALSE);
}
else {
- $this->assign('activityAssigneeNotification', FALSE);
+ $this->assign('activityAssigneeNotification', TRUE);
}
+ $this->assign('doNotNotifyAssigneeFor', $doNotNotifyAssigneeFor);
}
/**
@@ -809,29 +855,37 @@ public static function formRule($fields, $files, $self) {
if (CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Delete') {
return TRUE;
}
- $errors = array();
+ $errors = [];
if ((array_key_exists('activity_type_id', $fields) || !$self->_single) && empty($fields['activity_type_id'])) {
$errors['activity_type_id'] = ts('Activity Type is a required field');
}
- if (CRM_Utils_Array::value('activity_type_id', $fields) == 3 &&
- CRM_Utils_Array::value('status_id', $fields) == 1
- ) {
+ if (CRM_Utils_Array::value('activity_type_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email')
+ && CRM_Utils_Array::value('status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled')) {
$errors['status_id'] = ts('You cannot record scheduled email activity.');
}
- elseif (CRM_Utils_Array::value('activity_type_id', $fields) == 4 &&
- CRM_Utils_Array::value('status_id', $fields) == 1
- ) {
+ elseif (CRM_Utils_Array::value('activity_type_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS')
+ && CRM_Utils_Array::value('status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled')) {
$errors['status_id'] = ts('You cannot record scheduled SMS activity.');
}
if (!empty($fields['followup_activity_type_id']) && empty($fields['followup_date'])) {
- $errors['followup_date_time'] = ts('Followup date is a required field.');
+ $errors['followup_date'] = ts('Followup date is a required field.');
}
// Activity type is mandatory if subject or follow-up date is specified for an Follow-up activity, CRM-4515.
if ((!empty($fields['followup_activity_subject']) || !empty($fields['followup_date'])) && empty($fields['followup_activity_type_id'])) {
$errors['followup_activity_subject'] = ts('Follow-up Activity type is a required field.');
}
+
+ // Check that a value has been set for the "activity separation" field if needed
+ $separationIsPossible = $self->supportsActivitySeparation;
+ $actionIsAdd = $self->_action == CRM_Core_Action::ADD;
+ $hasMultipleTargetContacts = !empty($fields['target_contact_id']) && strpos($fields['target_contact_id'], ',') !== FALSE;
+ $separationFieldIsEmpty = empty($fields['separation']);
+ if ($separationIsPossible && $actionIsAdd && $hasMultipleTargetContacts && $separationFieldIsEmpty) {
+ $errors['separation'] = ts('Activity Separation is a required field.');
+ }
+
return $errors;
}
@@ -840,19 +894,21 @@ public static function formRule($fields, $files, $self) {
*
*
* @param array $params
+
* @return array|null
+ * @throws \CiviCRM_API3_Exception
*/
public function postProcess($params = NULL) {
if ($this->_action & CRM_Core_Action::DELETE) {
- $deleteParams = array('id' => $this->_activityId);
+ $deleteParams = ['id' => $this->_activityId];
$moveToTrash = CRM_Case_BAO_Case::isCaseActivity($this->_activityId);
CRM_Activity_BAO_Activity::deleteActivity($deleteParams, $moveToTrash);
// delete tags for the entity
- $tagParams = array(
+ $tagParams = [
'entity_table' => 'civicrm_activity',
'entity_id' => $this->_activityId,
- );
+ ];
CRM_Core_BAO_EntityTag::del($tagParams);
@@ -887,16 +943,13 @@ public function postProcess($params = NULL) {
);
}
- // store the date with proper format
- $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
-
// format params as arrays
- foreach (array('target', 'assignee', 'followup_assignee') as $name) {
+ foreach (['target', 'assignee', 'followup_assignee'] as $name) {
if (!empty($params["{$name}_contact_id"])) {
$params["{$name}_contact_id"] = explode(',', $params["{$name}_contact_id"]);
}
else {
- $params["{$name}_contact_id"] = array();
+ $params["{$name}_contact_id"] = [];
}
}
@@ -916,13 +969,15 @@ public function postProcess($params = NULL) {
$this->_activityId
);
- $activity = array();
+ $params['is_multi_activity'] = CRM_Utils_Array::value('separation', $params) == 'separate';
+
+ $activity = [];
if (!empty($params['is_multi_activity']) &&
!CRM_Utils_Array::crmIsEmptyArray($params['target_contact_id'])
) {
$targetContacts = $params['target_contact_id'];
foreach ($targetContacts as $targetContactId) {
- $params['target_contact_id'] = array($targetContactId);
+ $params['target_contact_id'] = [$targetContactId];
// save activity
$activity[] = $this->processActivity($params);
}
@@ -932,7 +987,7 @@ public function postProcess($params = NULL) {
$activity = $this->processActivity($params);
}
- $activityIds = empty($this->_activityIds) ? array($this->_activityId) : $this->_activityIds;
+ $activityIds = empty($this->_activityIds) ? [$this->_activityId] : $this->_activityIds;
foreach ($activityIds as $activityId) {
// set params for repeat configuration in create mode
$params['entity_id'] = $activityId;
@@ -951,7 +1006,7 @@ public function postProcess($params = NULL) {
$params['schedule_reminder_id'] = $scheduleReminderDetails->id;
}
}
- $params['dateColumns'] = array('activity_date_time');
+ $params['dateColumns'] = ['activity_date_time'];
// Set default repetition start if it was not provided.
if (empty($params['repetition_start_date'])) {
@@ -960,20 +1015,20 @@ public function postProcess($params = NULL) {
// unset activity id
unset($params['id']);
- $linkedEntities = array(
- array(
+ $linkedEntities = [
+ [
'table' => 'civicrm_activity_contact',
- 'findCriteria' => array(
+ 'findCriteria' => [
'activity_id' => $activityId,
- ),
- 'linkedColumns' => array('activity_id'),
+ ],
+ 'linkedColumns' => ['activity_id'],
'isRecurringEntityRecord' => FALSE,
- ),
- );
+ ],
+ ];
CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_activity', $linkedEntities);
}
- return array('activity' => $activity);
+ return ['activity' => $activity];
}
/**
@@ -985,7 +1040,7 @@ public function postProcess($params = NULL) {
* @return self|null|object
*/
protected function processActivity(&$params) {
- $activityAssigned = array();
+ $activityAssigned = [];
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
// format assignee params
@@ -1006,14 +1061,13 @@ protected function processActivity(&$params) {
$activity = CRM_Activity_BAO_Activity::create($params);
// add tags if exists
- $tagParams = array();
+ $tagParams = [];
if (!empty($params['tag'])) {
if (!is_array($params['tag'])) {
$params['tag'] = explode(',', $params['tag']);
}
- foreach ($params['tag'] as $tag) {
- $tagParams[$tag] = 1;
- }
+
+ $tagParams = array_fill_keys($params['tag'], 1);
}
// Save static tags.
@@ -1047,15 +1101,17 @@ protected function processActivity(&$params) {
// send copy to assignee contacts.CRM-4509
$mailStatus = '';
- if (Civi::settings()->get('activity_assignee_notification')) {
- $activityIDs = array($activity->id);
+ if (Civi::settings()->get('activity_assignee_notification')
+ && !in_array($activity->activity_type_id, Civi::settings()
+ ->get('do_not_notify_assignees_for'))) {
+ $activityIDs = [$activity->id];
if ($followupActivity) {
- $activityIDs = array_merge($activityIDs, array($followupActivity->id));
+ $activityIDs = array_merge($activityIDs, [$followupActivity->id]);
}
$assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityIDs, TRUE, FALSE);
if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
- $mailToContacts = array();
+ $mailToContacts = [];
// Build an associative array with unique email addresses.
foreach ($activityAssigned as $id => $dnc) {
@@ -1072,7 +1128,7 @@ protected function processActivity(&$params) {
// Also send email to follow-up activity assignees if set
if ($followupActivity) {
- $mailToFollowupContacts = array();
+ $mailToFollowupContacts = [];
foreach ($assigneeContacts as $values) {
if ($values['activity_id'] == $followupActivity->id) {
$mailToFollowupContacts[$values['email']] = $values;
@@ -1093,11 +1149,11 @@ protected function processActivity(&$params) {
}
CRM_Core_Session::setStatus(ts('Activity %1 has been saved. %2 %3',
- array(
+ [
1 => $subject,
2 => $followupStatus,
3 => $mailStatus,
- )
+ ]
), ts('Saved'), 'success');
return $activity;
diff --git a/CRM/Activity/Form/ActivityFilter.php b/CRM/Activity/Form/ActivityFilter.php
index b843dc2a0e7a..472c5b542c60 100644
--- a/CRM/Activity/Form/ActivityFilter.php
+++ b/CRM/Activity/Form/ActivityFilter.php
@@ -1,9 +1,9 @@
add('select', 'activity_type_filter_id', ts('Include'), array('' => ts('- all activity type(s) -')) + $activityOptions);
- $this->add('select', 'activity_type_exclude_filter_id', ts('Exclude'), array('' => ts('- select activity type -')) + $activityOptions);
- CRM_Core_Form_Date::buildDateRange(
- $this, 'activity_date', 1,
- '_low', '_high', ts('From:'),
- FALSE, array(), 'searchDate',
- FALSE, array('class' => 'crm-select2 medium')
- );
+ $this->add('select', 'activity_type_filter_id', ts('Include'), $activityOptions, FALSE, ['class' => 'crm-select2', 'multiple' => TRUE, 'placeholder' => ts('- all activity type(s) -')]);
+ $this->add('select', 'activity_type_exclude_filter_id', ts('Exclude'), $activityOptions, FALSE, ['class' => 'crm-select2', 'multiple' => TRUE, 'placeholder' => ts('- no types excluded -')]);
+ $this->addDatePickerRange('activity_date_time', ts('Date'));
$this->addSelect('status_id',
- array('entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -'))
+ ['entity' => 'activity', 'multiple' => 'multiple', 'option_url' => NULL, 'placeholder' => ts('- any -')]
);
$this->assign('suppressForm', TRUE);
@@ -66,11 +62,13 @@ public function buildQuickForm() {
*/
public function setDefaultValues() {
// CRM-11761 retrieve user's activity filter preferences
- $defaults = array();
- if (Civi::settings()->get('preserve_activity_tab_filter') && ($userID = CRM_Core_Session::getLoggedInContactID())) {
- $defaults = Civi::service('settings_manager')
- ->getBagByContact(NULL, $userID)
- ->get('activity_tab_filter');
+ $defaults = [];
+ if (Civi::settings()->get('preserve_activity_tab_filter') && (CRM_Core_Session::getLoggedInContactID())) {
+ $defaults = Civi::contactSettings()->get('activity_tab_filter');
+ }
+ // set Activity status 'Scheduled' by default only for dashlet
+ elseif (strstr(CRM_Utils_Array::value('q', $_GET), 'dashlet')) {
+ $defaults['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Scheduled');
}
return $defaults;
}
diff --git a/CRM/Activity/Form/ActivityLinks.php b/CRM/Activity/Form/ActivityLinks.php
index d06ba2db6373..36a27d14b39c 100644
--- a/CRM/Activity/Form/ActivityLinks.php
+++ b/CRM/Activity/Form/ActivityLinks.php
@@ -1,9 +1,9 @@
'activity_type',
'is_active' => 1,
- 'options' => array('limit' => 0, 'sort' => 'weight'),
- )));
+ 'options' => ['limit' => 0, 'sort' => 'weight'],
+ ]));
- $activityTypes = array();
+ $activityTypes = [];
foreach ($allTypes as $act) {
$url = 'civicrm/activity/add';
@@ -73,13 +74,26 @@ public static function commonBuildQuickForm($self) {
}
}
elseif ($act['name'] == 'SMS') {
- if (!$contactId || !CRM_SMS_BAO_Provider::activeProviderCount()) {
+ if (!$contactId || !CRM_SMS_BAO_Provider::activeProviderCount() || !CRM_Core_Permission::check('send SMS')) {
continue;
}
// Check for existence of a mobile phone and ! do not SMS privacy setting
- $mobileTypeID = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile');
- list($name, $phone, $doNotSMS) = CRM_Contact_BAO_Contact_Location::getPhoneDetails($contactId, $mobileTypeID);
- if (!$doNotSMS && $phone) {
+ try {
+ $phone = civicrm_api3('Phone', 'getsingle', [
+ 'contact_id' => $contactId,
+ 'phone_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Phone', 'phone_type_id', 'Mobile'),
+ 'return' => ['phone', 'contact_id'],
+ 'options' => ['limit' => 1, 'sort' => "is_primary DESC"],
+ 'api.Contact.getsingle' => [
+ 'id' => '$value.contact_id',
+ 'return' => 'do_not_sms',
+ ],
+ ]);
+ }
+ catch (CiviCRM_API3_Exception $e) {
+ continue;
+ }
+ if (!$phone['api.Contact.getsingle']['do_not_sms'] && $phone['phone']) {
$url = 'civicrm/activity/sms/add';
}
else {
@@ -95,7 +109,7 @@ public static function commonBuildQuickForm($self) {
$act['url'] = CRM_Utils_System::url($url,
"{$urlParams}{$act['value']}", FALSE, NULL, FALSE
);
- $act += array('icon' => 'fa-plus-square-o');
+ $act += ['icon' => 'fa-plus-square-o'];
$activityTypes[$act['value']] = $act;
}
diff --git a/CRM/Activity/Form/ActivityView.php b/CRM/Activity/Form/ActivityView.php
index 254e5daf687a..d0e884397168 100644
--- a/CRM/Activity/Form/ActivityView.php
+++ b/CRM/Activity/Form/ActivityView.php
@@ -1,9 +1,9 @@
pushUserContext($url);
- $defaults = array();
- $params = array('id' => $activityId);
+ $defaults = [];
+ $params = ['id' => $activityId];
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
// Set activity type name and description to template.
@@ -108,20 +108,29 @@ public function preProcess() {
$values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId);
$this->assign('values', $values);
+
+ $url = CRM_Utils_System::url(implode("/", $this->urlPath), "reset=1&id={$activityId}&action=view&cid={$values['source_contact_id']}");
+ CRM_Utils_Recent::add($this->_values['subject'],
+ $url,
+ $values['id'],
+ 'Activity',
+ $values['source_contact_id'],
+ $values['source_contact']
+ );
}
/**
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
}
diff --git a/CRM/Activity/Form/Search.php b/CRM/Activity/Form/Search.php
index 8f275c62aad9..4aa16252d5d6 100644
--- a/CRM/Activity/Form/Search.php
+++ b/CRM/Activity/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
-
- // we allow the controller to set force/reset externally, useful when we are being
- // driven by the wizard framework
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
- $this->assign("context", $this->_context);
+ $this->loadStandardSearchOptionsFromUrl();
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
@@ -102,6 +102,8 @@ public function preProcess() {
if ($this->_force) {
// If we force the search then merge form values with url values
// and set submit values to form values.
+ // @todo this is not good security practice. Instead define the fields in metadata & use
+ // getEntityDefaults.
$this->_formValues = array_merge((array) $this->_formValues, CRM_Utils_Request::exportValues());
$this->_submitValues = $this->_formValues;
}
@@ -170,9 +172,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Activity_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Activity_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -199,20 +199,19 @@ public function postProcess() {
if (!empty($_POST)) {
$this->_formValues = $this->controller->exportValues($this->_name);
- $specialParams = array(
+ $specialParams = [
'activity_type_id',
'status_id',
'priority_id',
'activity_text',
- );
- $changeNames = array(
+ ];
+ $changeNames = [
'status_id' => 'activity_status_id',
'priority_id' => 'activity_priority_id',
- );
+ ];
CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, $specialParams, $changeNames);
}
-
$this->fixFormValues();
if (isset($this->_ssID) && empty($_POST)) {
@@ -324,60 +323,9 @@ public function fixFormValues() {
}
}
- // Added for membership search
-
- $signupType = CRM_Utils_Request::retrieve('signupType', 'Positive');
-
- if ($signupType) {
- $this->_formValues['activity_role'] = 1;
- $this->_defaults['activity_role'] = 1;
- $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
-
- $renew = CRM_Utils_Array::key('Membership Renewal', $activityTypes);
- $signup = CRM_Utils_Array::key('Membership Signup', $activityTypes);
-
- switch ($signupType) {
- case 3: // signups and renewals
- $this->_formValues['activity_type_id'][$renew] = 1;
- $this->_defaults['activity_type_id'][$renew] = 1;
- case 1: // signups only
- $this->_formValues['activity_type_id'][$signup] = 1;
- $this->_defaults['activity_type_id'][$signup] = 1;
- break;
-
- case 2: // renewals only
- $this->_formValues['activity_type_id'][$renew] = 1;
- $this->_defaults['activity_type_id'][$renew] = 1;
- break;
- }
- }
-
- $dateLow = CRM_Utils_Request::retrieve('dateLow', 'String');
-
- if ($dateLow) {
- $dateLow = date('m/d/Y', strtotime($dateLow));
- $this->_formValues['activity_date_relative'] = 0;
- $this->_defaults['activity_date_relative'] = 0;
- $this->_formValues['activity_date_low'] = $dateLow;
- $this->_defaults['activity_date_low'] = $dateLow;
- }
-
- $dateHigh = CRM_Utils_Request::retrieve('dateHigh', 'String');
-
- if ($dateHigh) {
- // Activity date time assumes midnight at the beginning of the date
- // This sets it to almost midnight at the end of the date
- /* if ($dateHigh <= 99999999) {
- $dateHigh = 1000000 * $dateHigh + 235959;
- } */
- $dateHigh = date('m/d/Y', strtotime($dateHigh));
- $this->_formValues['activity_date_relative'] = 0;
- $this->_defaults['activity_date_relative'] = 0;
- $this->_formValues['activity_date_high'] = $dateHigh;
- $this->_defaults['activity_date_high'] = $dateHigh;
- }
-
// Enable search activity by custom value
+ // @todo this is not good security practice. Instead define entity fields in metadata &
+ // use getEntity Defaults
$requestParams = CRM_Utils_Request::exportValues();
foreach (array_keys($requestParams) as $key) {
if (substr($key, 0, 7) != 'custom_') {
@@ -405,6 +353,16 @@ public function getFormValues() {
return NULL;
}
+ /**
+ * This virtual function is used to set the default values of various form elements.
+ *
+ * @return array|NULL
+ * reference to the array of default values
+ */
+ public function setDefaultValues() {
+ return array_merge($this->getEntityDefaults($this->getDefaultEntity()), (array) $this->_formValues);
+ }
+
/**
* Return a descriptive name for the page, used in wizard header
*
@@ -414,4 +372,8 @@ public function getTitle() {
return ts('Find Activities');
}
+ protected function getEntityMetadata() {
+ return CRM_Activity_BAO_Query::getSearchFieldMetadata();
+ }
+
}
diff --git a/CRM/Activity/Form/Task.php b/CRM/Activity/Form/Task.php
index 90131945fde6..d64c173297b1 100644
--- a/CRM/Activity/Form/Task.php
+++ b/CRM/Activity/Form/Task.php
@@ -1,9 +1,9 @@
_activityHolderIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_activityHolderIds = [];
$values = $form->controller->exportValues($form->get('searchFormName'));
@@ -93,7 +65,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$activityTasks = CRM_Activity_Task::tasks();
$form->assign('taskName', $activityTasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -113,7 +85,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$activityClause = NULL;
$components = CRM_Core_Component::getNames();
- $componentClause = array();
+ $componentClause = [];
foreach ($components as $componentID => $componentName) {
if ($componentName != 'CiviCase' && !CRM_Core_Permission::check("access $componentName")) {
$componentClause[] = " (activity_type.component_id IS NULL OR activity_type.component_id <> {$componentID}) ";
@@ -191,17 +163,17 @@ public function setContactIDs() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => $backType,
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Activity/Form/Task/AddToTag.php b/CRM/Activity/Form/Task/AddToTag.php
index 3b32d612a45f..f712d449246d 100644
--- a/CRM/Activity/Form/Task/AddToTag.php
+++ b/CRM/Activity/Form/Task/AddToTag.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Activity_Form_Task_AddToTag', 'formRule'));
+ $this->addFormRule(['CRM_Activity_Form_Task_AddToTag', 'formRule']);
}
/**
@@ -81,7 +81,7 @@ public function addRules() {
* @return array
*/
public static function formRule($form, $rule) {
- $errors = array();
+ $errors = [];
if (empty($form['tag']) && empty($form['activity_taglist'])) {
$errors['_qf_default'] = ts("Please select at least one tag.");
}
@@ -94,7 +94,7 @@ public static function formRule($form, $rule) {
public function postProcess() {
// Get the submitted values in an array.
$params = $this->controller->exportValues($this->_name);
- $activityTags = $tagList = array();
+ $activityTags = $tagList = [];
// check if contact tags exists
if (!empty($params['tag'])) {
@@ -131,22 +131,22 @@ public function postProcess() {
// merge activity and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($activityTags, $tagList);
- $this->_name = array();
+ $this->_name = [];
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addEntitiesToTag($this->_activityHolderIds, $key,
'civicrm_activity', FALSE);
- $status = array(ts('Activity tagged', array('count' => $added, 'plural' => '%count activities tagged')));
+ $status = [ts('Activity tagged', ['count' => $added, 'plural' => '%count activities tagged'])];
if ($notAdded) {
- $status[] = ts('1 activity already had this tag', array(
+ $status[] = ts('1 activity already had this tag', [
'count' => $notAdded,
'plural' => '%count activities already had this tag',
- ));
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts("Added Tag %1", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts("Added Tag %1", [1 => $this->_tags[$key]]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Activity/Form/Task/Batch.php b/CRM/Activity/Form/Task/Batch.php
index 72a72febc180..9bdb768b8b50 100644
--- a/CRM/Activity/Form/Task/Batch.php
+++ b/CRM/Activity/Form/Task/Batch.php
@@ -1,9 +1,9 @@
ts('Added By'), 'target_sort_name' => ts('With Contact')),
+ $readOnlyFields = array_merge(['sort_name' => ts('Added By'), 'target_sort_name' => ts('With Contact')],
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
@@ -101,12 +103,12 @@ public function buildQuickForm() {
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
- $this->_fields = array();
+ $this->_fields = [];
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
// remove file type field and then limit fields
$suppressFields = FALSE;
- $removehtmlTypes = array('File', 'Autocomplete-Select');
+ $removehtmlTypes = ['File'];
foreach ($this->_fields as $name => $field) {
if (CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -124,24 +126,24 @@ public function buildQuickForm() {
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'submit',
'name' => ts('Update Activities'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_activityHolderIds);
// Load all campaigns.
if (array_key_exists('activity_campaign_id', $this->_fields)) {
- $this->_componentCampaigns = array();
+ $this->_componentCampaigns = [];
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Activity_DAO_Activity',
TRUE, 'campaign_id', 'id',
@@ -153,7 +155,7 @@ public function buildQuickForm() {
// It is possible to have fields that are required in CiviCRM not be required in the
// profile. Overriding that here. Perhaps a better approach would be to
// make them required in the schema & read that up through getFields functionality.
- $requiredFields = array('activity_date_time');
+ $requiredFields = ['activity_date_time'];
foreach ($this->_activityHolderIds as $activityId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id');
@@ -187,7 +189,7 @@ public function buildQuickForm() {
// $buttonName = $this->controller->getButtonName('submit');
if ($suppressFields) {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple activities."), ts('Some Fields Excluded'), 'info');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple activities."), ts('Some Fields Excluded'), 'info');
}
$this->addDefaultButtons(ts('Update Activities'));
@@ -201,7 +203,7 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_activityHolderIds as $activityId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $activityId, 'Activity');
}
@@ -242,6 +244,9 @@ public function postProcess() {
$activityId = civicrm_api3('activity', 'create', $value);
// @todo this would be done by the api call above if the parames were passed through.
+ // @todo extract submit functions &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test
+ // handling of custom data, specifically checkbox fields.
if (!empty($value['custom']) &&
is_array($value['custom'])
) {
diff --git a/CRM/Activity/Form/Task/Delete.php b/CRM/Activity/Form/Task/Delete.php
index 6fee99f7dc4e..7fa2bef6ca80 100644
--- a/CRM/Activity/Form/Task/Delete.php
+++ b/CRM/Activity/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count activities deleted.', 'count' => $deleted));
+ $msg = ts('%count activity deleted.', ['plural' => '%count activities deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Activity/Form/Task/Email.php b/CRM/Activity/Form/Task/Email.php
index ad693bf5bb8a..4f6db5136b1a 100644
--- a/CRM/Activity/Form/Task/Email.php
+++ b/CRM/Activity/Form/Task/Email.php
@@ -1,9 +1,9 @@
addEntityRef('unclosed_case_id', ts('Select Case'), array('entity' => 'Case'), TRUE);
+ $this->addEntityRef('unclosed_case_id', ts('Select Case'), ['entity' => 'Case'], TRUE);
$this->addDefaultButtons(ts('Save'));
}
@@ -80,8 +82,8 @@ public function postProcess() {
$caseId = $formparams['unclosed_case_id'];
$filedActivities = 0;
foreach ($this->_activityHolderIds as $key => $id) {
- $targetContactValues = $defaults = array();
- $params = array('id' => $id);
+ $targetContactValues = $defaults = [];
+ $params = ['id' => $id];
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
if (CRM_Case_BAO_Case::checkPermission($id, 'File On Case', $defaults['activity_type_id'])) {
@@ -92,13 +94,13 @@ public function postProcess() {
$targetContactValues = implode(',', array_keys($targetContactValues));
}
- $params = array(
+ $params = [
'caseID' => $caseId,
'activityID' => $id,
'newSubject' => empty($defaults['subject']) ? '' : $defaults['subject'],
'targetContactIds' => $targetContactValues,
'mode' => 'file',
- );
+ ];
$error_msg = CRM_Activity_Page_AJAX::_convertToCaseActivity($params);
if (empty($error_msg['error_msg'])) {
@@ -109,16 +111,17 @@ public function postProcess() {
}
}
else {
- CRM_Core_Session::setStatus(ts('Not permitted to file activity %1 %2.', array(
+ CRM_Core_Session::setStatus(
+ ts('Not permitted to file activity %1 %2.', [
1 => empty($defaults['subject']) ? '' : $defaults['subject'],
2 => $defaults['activity_date_time'],
- )),
+ ]),
ts("Error"), "error");
}
}
CRM_Core_Session::setStatus($filedActivities, ts("Filed Activities"), "success");
- CRM_Core_Session::setStatus("", ts('Total Selected Activities: %1', array(1 => count($this->_activityHolderIds))), "info");
+ CRM_Core_Session::setStatus("", ts('Total Selected Activities: %1', [1 => count($this->_activityHolderIds)]), "info");
}
}
diff --git a/CRM/Activity/Form/Task/PickOption.php b/CRM/Activity/Form/Task/PickOption.php
index 7914eb9eb6fd..bef28a6b3b4a 100644
--- a/CRM/Activity/Form/Task/PickOption.php
+++ b/CRM/Activity/Form/Task/PickOption.php
@@ -1,9 +1,9 @@
_activityHolderIds) > $this->_maxActivities) {
- CRM_Core_Session::setStatus(ts("The maximum number of Activities you can select to send an email is %1. You have selected %2. Please select fewer Activities from your search results and try again.", array(
+ CRM_Core_Session::setStatus(ts("The maximum number of Activities you can select to send an email is %1. You have selected %2. Please select fewer Activities from your search results and try again.", [
1 => $this->_maxActivities,
2 => count($this->_activityHolderIds),
- )), ts("Maximum Exceeded"), "error");
+ ]), ts("Maximum Exceeded"), "error");
$validate = TRUE;
}
// then redirect
@@ -92,7 +95,7 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'with_contact', ts('With Contact'));
$this->addElement('checkbox', 'assigned_to', ts('Assigned to Contact'));
$this->addElement('checkbox', 'created_by', ts('Created by'));
- $this->setDefaults(array('with_contact' => 1));
+ $this->setDefaults(['with_contact' => 1]);
$this->addDefaultButtons(ts('Continue'));
}
@@ -100,7 +103,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Activity_Form_Task_PickOption', 'formRule'));
+ $this->addFormRule(['CRM_Activity_Form_Task_PickOption', 'formRule']);
}
/**
@@ -117,7 +120,7 @@ public static function formRule($fields) {
!isset($fields['assigned_to']) &&
!isset($fields['created_by'])
) {
- return array('with_contact' => ts('You must select at least one email recipient type.'));
+ return ['with_contact' => ts('You must select at least one email recipient type.')];
}
return TRUE;
}
@@ -129,7 +132,7 @@ public function postProcess() {
// Clear any formRule errors from Email form in case they came back here via Cancel button
$this->controller->resetPage('Email');
$params = $this->exportValues();
- $this->_contacts = array();
+ $this->_contacts = [];
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
diff --git a/CRM/Activity/Form/Task/PickProfile.php b/CRM/Activity/Form/Task/PickProfile.php
index 13ad599e32be..1221a21c4abd 100644
--- a/CRM/Activity/Form/Task/PickProfile.php
+++ b/CRM/Activity/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
_activityHolderIds) > $this->_maxActivities) {
- CRM_Core_Session::setStatus(ts("The maximum number of activities you can select for Update multiple activities is %1. You have selected %2. Please select fewer Activities from your search results and try again.", array(
+ CRM_Core_Session::setStatus(ts("The maximum number of activities you can select for Update multiple activities is %1. You have selected %2. Please select fewer Activities from your search results and try again.", [
1 => $this->_maxActivities,
2 => count($this->_activityHolderIds),
- )), ts('Maximum Exceeded'), 'error');
+ ]), ts('Maximum Exceeded'), 'error');
$validate = TRUE;
}
@@ -85,11 +87,11 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $types = array('Activity');
+ $types = ['Activity'];
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
$activityTypeIds = array_flip(CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'));
- $nonEditableActivityTypeIds = array(
+ $nonEditableActivityTypeIds = [
$activityTypeIds['Email'],
$activityTypeIds['Bulk Email'],
$activityTypeIds['Contribution'],
@@ -99,7 +101,7 @@ public function buildQuickForm() {
$activityTypeIds['Membership Renewal'],
$activityTypeIds['Event Registration'],
$activityTypeIds['Pledge Acknowledgment'],
- );
+ ];
$notEditable = FALSE;
foreach ($this->_activityHolderIds as $activityId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id');
@@ -110,7 +112,7 @@ public function buildQuickForm() {
}
if (empty($profiles)) {
- CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple activities. Navigate to Administer > Customize Data and Screens > Profiles to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts("No Profile Configured"), "alert");
+ CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple activities. Navigate to Administer > Customize Data and Screens > Profiles to configure a Profile. Consult the online Administrator documentation for more information.", [1 => $types[0]]), ts("No Profile Configured"), "alert");
CRM_Utils_System::redirect($this->_userContext);
}
elseif ($notEditable) {
@@ -119,9 +121,9 @@ public function buildQuickForm() {
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
- array(
+ [
'' => ts('- select profile -'),
- ) + $profiles, TRUE
+ ] + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
@@ -130,7 +132,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Activity_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Activity_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Activity/Form/Task/Print.php b/CRM/Activity/Form/Task/Print.php
index b61214a8c4d1..69f822bd74b7 100644
--- a/CRM/Activity/Form/Task/Print.php
+++ b/CRM/Activity/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Print Activities'),
- 'js' => array('onclick' => 'window.print()'),
+ 'js' => ['onclick' => 'window.print()'],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'back',
'name' => ts('Done'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Activity/Form/Task/RemoveFromTag.php b/CRM/Activity/Form/Task/RemoveFromTag.php
index e1fecc0a3609..2590ba073d73 100644
--- a/CRM/Activity/Form/Task/RemoveFromTag.php
+++ b/CRM/Activity/Form/Task/RemoveFromTag.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Activity_Form_Task_RemoveFromTag', 'formRule'));
+ $this->addFormRule(['CRM_Activity_Form_Task_RemoveFromTag', 'formRule']);
}
/**
@@ -77,7 +77,7 @@ public function addRules() {
* @return array
*/
public static function formRule($form, $rule) {
- $errors = array();
+ $errors = [];
if (empty($form['tag']) && empty($form['activity_taglist'])) {
$errors['_qf_default'] = "Please select atleast one tag.";
}
@@ -91,7 +91,7 @@ public function postProcess() {
//get the submitted values in an array
$params = $this->controller->exportValues($this->_name);
- $activityTags = $tagList = array();
+ $activityTags = $tagList = [];
// check if contact tags exists
if (!empty($params['tag'])) {
@@ -120,27 +120,27 @@ public function postProcess() {
// merge contact and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($activityTags, $tagList);
- $this->_name = array();
+ $this->_name = [];
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $removed, $notRemoved) = CRM_Core_BAO_EntityTag::removeEntitiesFromTag($this->_activityHolderIds,
$key, 'civicrm_activity', FALSE);
- $status = array(
- ts('%count activity un-tagged', array(
+ $status = [
+ ts('%count activity un-tagged', [
'count' => $removed,
'plural' => '%count activities un-tagged',
- )),
- );
+ ]),
+ ];
if ($notRemoved) {
- $status[] = ts('1 activity already did not have this tag', array(
+ $status[] = ts('1 activity already did not have this tag', [
'count' => $notRemoved,
'plural' => '%count activities already did not have this tag',
- ));
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts("Removed Tag %1", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts("Removed Tag %1", [1 => $this->_tags[$key]]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Activity/Form/Task/SMS.php b/CRM/Activity/Form/Task/SMS.php
index b44723d4aea0..42d9f6aa3f23 100644
--- a/CRM/Activity/Form/Task/SMS.php
+++ b/CRM/Activity/Form/Task/SMS.php
@@ -1,9 +1,9 @@
_activityHolderIds);
@@ -63,12 +63,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'subject' => $dao->subject,
'activity_type' => $dao->activity_type,
'activity_date' => $dao->activity_date,
'display_name' => $dao->display_name,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -77,13 +77,13 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Activity/Import/Controller.php b/CRM/Activity/Import/Controller.php
index 9ad060e9ad21..9edc8e66b4e3 100644
--- a/CRM/Activity/Import/Controller.php
+++ b/CRM/Activity/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Activity/Import/Field.php b/CRM/Activity/Import/Field.php
index 029f7fd23b40..b19a6002de94 100644
--- a/CRM/Activity/Import/Field.php
+++ b/CRM/Activity/Import/Field.php
@@ -1,9 +1,9 @@
createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -67,11 +67,11 @@ public function buildQuickForm() {
* Process the uploaded file.
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'onDuplicate',
'dateFormats',
'savedMapping',
- ));
+ ]);
$this->submitFileForMapping('CRM_Activity_Import_Parser_Activity');
}
diff --git a/CRM/Activity/Import/Form/MapField.php b/CRM/Activity/Import/Form/MapField.php
index 752e4a96078e..2b2e78053b6f 100644
--- a/CRM/Activity/Import/Form/MapField.php
+++ b/CRM/Activity/Import/Form/MapField.php
@@ -1,9 +1,9 @@
assign('rowDisplayCount', 2);
}
- $highlightedFields = array();
- $requiredFields = array(
+ $highlightedFields = [];
+ $requiredFields = [
'activity_date_time',
'activity_type_id',
'activity_label',
'target_contact_id',
'activity_subject',
- );
+ ];
foreach ($requiredFields as $val) {
$highlightedFields[] = $val;
}
@@ -103,8 +102,8 @@ public function buildQuickForm() {
$this->assign('loadedMapping', $savedMapping);
$this->set('loadedMapping', $savedMapping);
- $params = array('id' => $savedMapping);
- $temp = array();
+ $params = ['id' => $savedMapping];
+ $temp = [];
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$this->assign('savedName', $mappingDetails->name);
@@ -117,13 +116,13 @@ public function buildQuickForm() {
$this->add('text', 'saveMappingDesc', ts('Description'));
}
- $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
+ $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
- $this->addFormRule(array('CRM_Activity_Import_Form_MapField', 'formRule'));
+ $this->addFormRule(['CRM_Activity_Import_Form_MapField', 'formRule']);
//-------- end of saved mapping stuff ---------
- $defaults = array();
+ $defaults = [];
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
@@ -148,7 +147,7 @@ public function buildQuickForm() {
$warning = 0;
for ($i = 0; $i < $this->_columnCount; $i++) {
- $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
+ $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
$jsSet = FALSE;
if ($this->get('savedMapping')) {
if (isset($mappingName[$i])) {
@@ -165,15 +164,15 @@ public function buildQuickForm() {
}
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
- $defaults["mapper[$i]"] = array(
+ $defaults["mapper[$i]"] = [
$mappingHeader[0],
(isset($locationId)) ? $locationId : "",
(isset($phoneType)) ? $phoneType : "",
- );
+ ];
$jsSet = TRUE;
}
else {
- $defaults["mapper[$i]"] = array();
+ $defaults["mapper[$i]"] = [];
}
if (!$jsSet) {
for ($k = 1; $k < 4; $k++) {
@@ -186,14 +185,10 @@ public function buildQuickForm() {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
- $defaults["mapper[$i]"] = array(
- $this->defaultFromHeader($this->_columnHeaders[$i],
- $headerPatterns
- ),
- );
+ $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns)];
}
else {
- $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
+ $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
}
}
// End of load mapping.
@@ -202,23 +197,23 @@ public function buildQuickForm() {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
// Infer the default from the skipped headers if we have them
- $defaults["mapper[$i]"] = array(
- $this->defaultFromHeader($this->_columnHeaders[$i],
- $headerPatterns
- ),
+ $defaults["mapper[$i]"] = [
+ $this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns),
0,
- );
+ ];
}
else {
// Otherwise guess the default from the form of the data
- $defaults["mapper[$i]"] = array(
- $this->defaultFromData($dataPatterns, $i),
- 0,
- );
+ $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i), 0];
}
}
- $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
+ $sel->setOptions([
+ $sel1,
+ $sel2,
+ (isset($sel3)) ? $sel3 : "",
+ (isset($sel4)) ? $sel4 : "",
+ ]);
}
$js .= "\n";
$this->assign('initHideBoxes', $js);
@@ -240,22 +235,22 @@ public function buildQuickForm() {
$this->setDefaults($defaults);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'back',
'name' => ts('Previous'),
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
}
@@ -269,28 +264,28 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
// define so we avoid notices below
$errors['_qf_default'] = '';
$fieldMessage = NULL;
if (!array_key_exists('savedMapping', $fields)) {
- $importKeys = array();
+ $importKeys = [];
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
// FIXME: should use the schema titles, not redeclare them
- $requiredFields = array(
+ $requiredFields = [
'target_contact_id' => ts('Contact ID'),
'activity_date_time' => ts('Activity Date'),
'activity_subject' => ts('Activity Subject'),
'activity_type_id' => ts('Activity Type ID'),
- );
+ ];
- $params = array(
+ $params = [
'used' => 'Unsupervised',
'contact_type' => 'Individual',
- );
+ ];
list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
$weightSum = 0;
foreach ($importKeys as $key => $val) {
@@ -310,7 +305,7 @@ public static function formRule($fields) {
else {
$errors['_qf_default'] .= ts('Missing required contact matching fields.')
. $fieldMessage . ' '
- . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(1 => $threshold))
+ . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [1 => $threshold])
. ' ';
}
}
@@ -320,14 +315,14 @@ public static function formRule($fields) {
}
else {
$errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
- array(
+ [
1 => $title,
2 => 'Activity Type Label',
- )) . ' ';
+ ]) . ' ';
}
}
else {
- $errors['_qf_default'] .= ts('Missing required field: %1', array(1 => $title)) . ' ';
+ $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . ' ';
}
}
}
@@ -339,8 +334,7 @@ public static function formRule($fields) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Activity', 'name');
- if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
+ if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'))) {
$errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
}
}
@@ -379,12 +373,12 @@ public function postProcess() {
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
- $mapperKeys = array();
- $mapper = array();
+ $mapperKeys = [];
+ $mapper = [];
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
- $mapperKeysMain = array();
- $mapperLocType = array();
- $mapperPhoneType = array();
+ $mapperKeysMain = [];
+ $mapperLocType = [];
+ $mapperPhoneType = [];
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
@@ -418,7 +412,7 @@ public function postProcess() {
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
- $mappingFieldsId = array();
+ $mappingFieldsId = [];
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
@@ -438,14 +432,11 @@ public function postProcess() {
// Saving Mapping Details and Records.
if (!empty($params['saveMapping'])) {
- $mappingParams = array(
+ $mappingParams = [
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import Activity',
- 'name'
- ),
- );
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'),
+ ];
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
diff --git a/CRM/Activity/Import/Form/Preview.php b/CRM/Activity/Import/Form/Preview.php
index b74b0d6f133d..6a2352d06213 100644
--- a/CRM/Activity/Import/Form/Preview.php
+++ b/CRM/Activity/Import/Form/Preview.php
@@ -1,9 +1,9 @@
set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'dataValues',
'columnCount',
@@ -93,7 +93,8 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
+ $this->setStatusUrl();
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -114,9 +115,9 @@ public function postProcess() {
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
- $mapperLocType = array();
- $mapperPhoneType = array();
+ $mapperKeys = [];
+ $mapperLocType = [];
+ $mapperPhoneType = [];
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
@@ -141,7 +142,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -151,7 +152,9 @@ public function postProcess() {
$mapperFields,
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
- $onDuplicate
+ $onDuplicate,
+ $this->get('statusID'),
+ $this->get('totalRowCount')
);
// add all the necessary variables to the form
@@ -161,7 +164,7 @@ public function postProcess() {
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Activity/Import/Form/Summary.php b/CRM/Activity/Import/Form/Summary.php
index 83f360a7a05e..5e263c5edbc7 100644
--- a/CRM/Activity/Import/Form/Summary.php
+++ b/CRM/Activity/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -101,7 +101,7 @@ public function preProcess() {
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Activity/Import/Parser.php b/CRM/Activity/Import/Parser.php
index 0c0d35161d63..fc4aca0c20dc 100644
--- a/CRM/Activity/Import/Parser.php
+++ b/CRM/Activity/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
+ if ($statusID) {
+ $this->progressImport($statusID);
+ $startTimestamp = $currTimestamp = $prevTimestamp = time();
+ }
while (!feof($fd)) {
$this->_lineCount++;
@@ -148,6 +159,9 @@ public function run(
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
+ if ($statusID && (($this->_lineCount % 50) == 0)) {
+ $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
+ }
}
else {
$returnCode = self::ERROR;
@@ -171,14 +185,12 @@ public function run(
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode & self::CONFLICT) {
@@ -233,30 +245,24 @@ public function run(
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
+ $headers = array_merge(
+ [ts('Line Number'), ts('Reason')],
$customHeaders
);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
+ $headers = array_merge(
+ [ts('Line Number'), ts('Reason')],
$customHeaders
);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('View Activity History URL'),
- ),
+ $headers = array_merge(
+ [ts('Line Number'), ts('View Activity History URL')],
$customHeaders
);
@@ -291,7 +297,7 @@ public function setActiveFields($fieldKeys) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -376,7 +382,7 @@ public function set($store, $mode = self::MODE_SUMMARY) {
* @param array $data
*/
public static function exportCSV($fileName, $header, $data) {
- $output = array();
+ $output = [];
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
diff --git a/CRM/Activity/Import/Parser/Activity.php b/CRM/Activity/Import/Parser/Activity.php
index 4e41cf675b20..de829240c3d7 100644
--- a/CRM/Activity/Import/Parser/Activity.php
+++ b/CRM/Activity/Import/Parser/Activity.php
@@ -1,9 +1,9 @@
array(
+ $fields = array_merge($fields, [
+ 'source_contact_id' => [
'title' => ts('Source Contact'),
'headerPattern' => '/Source.Contact?/i',
- ),
- 'activity_label' => array(
+ ],
+ 'activity_label' => [
'title' => ts('Activity Type Label'),
'headerPattern' => '/(activity.)?type label?/i',
- ),
- ));
+ ],
+ ]);
foreach ($fields as $name => $field) {
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
@@ -96,7 +96,7 @@ public function init() {
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newActivity = array();
+ $this->_newActivity = [];
$this->setActiveFields($this->_mapperKeys);
@@ -258,7 +258,7 @@ public function import($onDuplicate, &$values) {
$params = &$this->getActiveFieldParams();
$activityLabel = array_search('activity_label', $this->_mapperKeys);
if ($activityLabel) {
- $params = array_merge($params, array('activity_label' => $values[$activityLabel]));
+ $params = array_merge($params, ['activity_label' => $values[$activityLabel]]);
}
// For date-Formats.
$session = CRM_Core_Session::singleton();
@@ -332,10 +332,10 @@ public function import($onDuplicate, &$values) {
}
else {
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => 'Individual',
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = NULL;
diff --git a/CRM/Activity/Page/AJAX.php b/CRM/Activity/Page/AJAX.php
index 321c73e6179f..1da789c2734a 100644
--- a/CRM/Activity/Page/AJAX.php
+++ b/CRM/Activity/Page/AJAX.php
@@ -1,9 +1,9 @@
'Integer',
'status_id' => 'Integer',
'activity_deleted' => 'Boolean',
'activity_type_id' => 'Integer',
- 'activity_date_low' => 'Date',
- 'activity_date_high' => 'Date',
- );
+ // "Date" validation fails because it expects only numbers with no hyphens
+ 'activity_date_low' => 'Alphanumeric',
+ 'activity_date_high' => 'Alphanumeric',
+ ];
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
- $params += CRM_Core_Page_AJAX::validateParams(array(), $optionalParameters);
+ $params += CRM_Core_Page_AJAX::validateParams([], $optionalParameters);
// get the activities related to given case
$activities = CRM_Case_BAO_Case::getCaseActivity($caseID, $params, $contactID, $context, $userID);
@@ -65,17 +67,17 @@ public static function getCaseGlobalRelationships() {
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
// get the activities related to given case
- $globalGroupInfo = array();
+ $globalGroupInfo = [];
// get the total row count
CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, NULL, FALSE, TRUE, NULL, NULL);
// limit the rows
$relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, $params['sortBy'], $showLinks = TRUE, FALSE, $params['offset'], $params['rp']);
- $relationships = array();
+ $relationships = [];
// after sort we can update username fields to be a url
foreach ($relGlobal as $key => $value) {
- $relationship = array();
+ $relationship = [];
$relationship['sort_name'] = $value['sort_name'];
$relationship['phone'] = $value['phone'];
$relationship['email'] = $value['email'];
@@ -83,7 +85,7 @@ public static function getCaseGlobalRelationships() {
array_push($relationships, $relationship);
}
- $globalRelationshipsDT = array();
+ $globalRelationshipsDT = [];
$globalRelationshipsDT['data'] = $relationships;
$globalRelationshipsDT['recordsTotal'] = count($relationships);
$globalRelationshipsDT['recordsFiltered'] = count($relationships);
@@ -107,7 +109,7 @@ public static function getCaseClientRelationships() {
// Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles
// so they don't show up twice.
- $clientRelationships = array();
+ $clientRelationships = [];
foreach ($relClient as $r) {
if (!array_key_exists($r['id'], $caseRelationships)) {
$clientRelationships[] = $r;
@@ -121,10 +123,10 @@ public static function getCaseClientRelationships() {
$sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
array_multisort($sortArray, constant($sort_type), $clientRelationships);
- $relationships = array();
+ $relationships = [];
// after sort we can update username fields to be a url
foreach ($clientRelationships as $key => $value) {
- $relationship = array();
+ $relationship = [];
$relationship['relation'] = $value['relation'];
$relationship['name'] = '' . $clientRelationships[$key]['name'] . '';
@@ -134,7 +136,7 @@ public static function getCaseClientRelationships() {
array_push($relationships, $relationship);
}
- $clientRelationshipsDT = array();
+ $clientRelationshipsDT = [];
$clientRelationshipsDT['data'] = $relationships;
$clientRelationshipsDT['recordsTotal'] = count($relationships);
$clientRelationshipsDT['recordsFiltered'] = count($relationships);
@@ -142,7 +144,6 @@ public static function getCaseClientRelationships() {
CRM_Utils_JSON::output($clientRelationshipsDT);
}
-
public static function getCaseRoles() {
$caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
$contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
@@ -172,7 +173,7 @@ public static function getCaseRoles() {
// CRM-14466 added cid to the non-client array to avoid php notice
foreach ($caseRoles as $id => $value) {
if ($id != "client") {
- $rel = array();
+ $rel = [];
$rel['relation'] = $value;
$rel['relation_type'] = $id;
$rel['name'] = '(not assigned)';
@@ -183,7 +184,7 @@ public static function getCaseRoles() {
}
else {
foreach ($value as $clientRole) {
- $relClient = array();
+ $relClient = [];
$relClient['relation'] = 'Client';
$relClient['name'] = $clientRole['sort_name'];
$relClient['phone'] = $clientRole['phone'];
@@ -202,13 +203,13 @@ public static function getCaseRoles() {
$sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
array_multisort($sortArray, constant($sort_type), $caseRelationships);
- $relationships = array();
+ $relationships = [];
// set user name, email and edit columns links
foreach ($caseRelationships as $key => &$row) {
$typeLabel = $row['relation'];
// Add " (Case Manager)" to label
- if ($row['relation_type'] == $managerRoleId) {
+ if (!empty($row['relation_type']) && $row['relation_type'] == $managerRoleId) {
$row['relation'] .= ' ' . '(' . ts('Case Manager') . ')';
}
// view user links
@@ -227,16 +228,16 @@ public static function getCaseRoles() {
$contactType = $contactType == 'Contact' ? '' : $contactType;
switch ($row['source']) {
case 'caseRel':
- $row['actions'] = '' .
+ $row['actions'] = '' .
'' .
'' .
- '' .
+ '' .
'' .
'';
break;
case 'caseRoles':
- $row['actions'] = '' .
+ $row['actions'] = '' .
'' .
'';
break;
@@ -251,7 +252,7 @@ public static function getCaseRoles() {
}
$params['total'] = count($relationships);
- $caseRelationshipsDT = array();
+ $caseRelationshipsDT = [];
$caseRelationshipsDT['data'] = $relationships;
$caseRelationshipsDT['recordsTotal'] = $params['total'];
$caseRelationshipsDT['recordsFiltered'] = $params['total'];
@@ -261,8 +262,8 @@ public static function getCaseRoles() {
}
public static function convertToCaseActivity() {
- $params = array('caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode');
- $vals = array();
+ $params = ['caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode'];
+ $vals = [];
foreach ($params as $param) {
$vals[$param] = CRM_Utils_Array::value($param, $_POST);
}
@@ -277,19 +278,19 @@ public static function convertToCaseActivity() {
*/
public static function _convertToCaseActivity($params) {
if (!$params['activityID'] || !$params['caseID']) {
- return (array('error_msg' => 'required params missing.'));
+ return (['error_msg' => 'required params missing.']);
}
$otherActivity = new CRM_Activity_DAO_Activity();
$otherActivity->id = $params['activityID'];
if (!$otherActivity->find(TRUE)) {
- return (array('error_msg' => 'activity record is missing.'));
+ return (['error_msg' => 'activity record is missing.']);
}
$actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
// Create new activity record.
$mainActivity = new CRM_Activity_DAO_Activity();
- $mainActVals = array();
+ $mainActVals = [];
CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
// Get new activity subject.
@@ -302,20 +303,19 @@ public static function _convertToCaseActivity($params) {
$mainActivity->activity_date_time = $actDateTime;
// Make sure this is current revision.
$mainActivity->is_current_revision = TRUE;
- // Drop all relations.
- $mainActivity->parent_id = $mainActivity->original_id = NULL;
+ $mainActivity->original_id = $otherActivity->id;
+ $otherActivity->is_current_revision = FALSE;
$mainActivity->save();
$mainActivityId = $mainActivity->id;
CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
- $mainActivity->free();
// Mark previous activity as deleted. If it was a non-case activity
// then just change the subject.
- if (in_array($params['mode'], array(
+ if (in_array($params['mode'], [
'move',
'file',
- ))) {
+ ])) {
$caseActivity = new CRM_Case_DAO_CaseActivity();
$caseActivity->case_id = $params['caseID'];
$caseActivity->activity_id = $otherActivity->id;
@@ -323,18 +323,15 @@ public static function _convertToCaseActivity($params) {
$otherActivity->is_deleted = 1;
}
else {
- $otherActivity->subject = ts('(Filed on case %1)', array(
+ $otherActivity->subject = ts('(Filed on case %1)', [
1 => $params['caseID'],
- )) . ' ' . $otherActivity->subject;
+ ]) . ' ' . $otherActivity->subject;
}
- $otherActivity->activity_date_time = $actDateTime;
$otherActivity->save();
- $caseActivity->free();
}
- $otherActivity->free();
- $targetContacts = array();
+ $targetContacts = [];
if (!empty($params['targetContactIds'])) {
$targetContacts = array_unique(explode(',', $params['targetContactIds']));
}
@@ -345,19 +342,19 @@ public static function _convertToCaseActivity($params) {
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
$sourceContactID = CRM_Activity_BAO_Activity::getSourceContactID($params['activityID']);
- $src_params = array(
+ $src_params = [
'activity_id' => $mainActivityId,
'contact_id' => $sourceContactID,
'record_type_id' => $sourceID,
- );
+ ];
CRM_Activity_BAO_ActivityContact::create($src_params);
foreach ($targetContacts as $key => $value) {
- $targ_params = array(
+ $targ_params = [
'activity_id' => $mainActivityId,
'contact_id' => $value,
'record_type_id' => $targetID,
- );
+ ];
CRM_Activity_BAO_ActivityContact::create($targ_params);
}
@@ -367,11 +364,11 @@ public static function _convertToCaseActivity($params) {
$assigneeContacts = array_unique(explode(',', $params['assigneeContactIds']));
}
foreach ($assigneeContacts as $key => $value) {
- $assigneeParams = array(
+ $assigneeParams = [
'activity_id' => $mainActivityId,
'contact_id' => $value,
'record_type_id' => $assigneeID,
- );
+ ];
CRM_Activity_BAO_ActivityContact::create($assigneeParams);
}
@@ -381,12 +378,12 @@ public static function _convertToCaseActivity($params) {
$caseActivity->activity_id = $mainActivityId;
$caseActivity->save();
$error_msg = $caseActivity->_lastError;
- $caseActivity->free();
$params['mainActivityId'] = $mainActivityId;
CRM_Activity_BAO_Activity::copyExtendedActivityData($params);
+ CRM_Utils_Hook::post('create', 'CaseActivity', $caseActivity->id, $caseActivity);
- return (array('error_msg' => $error_msg, 'newId' => $mainActivity->id));
+ return (['error_msg' => $error_msg, 'newId' => $mainActivity->id]);
}
/**
@@ -395,19 +392,19 @@ public static function _convertToCaseActivity($params) {
* @return array
*/
public static function getContactActivity() {
- $requiredParameters = array(
+ $requiredParameters = [
'cid' => 'Integer',
- );
+ ];
- $optionalParameters = array(
+ $optionalParameters = [
'context' => 'String',
'activity_type_id' => 'Integer',
'activity_type_exclude_id' => 'Integer',
'activity_status_id' => 'String',
- 'activity_date_relative' => 'String',
- 'activity_date_low' => 'String',
- 'activity_date_high' => 'String',
- );
+ 'activity_date_time_relative' => 'String',
+ 'activity_date_time_low' => 'String',
+ 'activity_date_time_high' => 'String',
+ ];
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
@@ -424,7 +421,7 @@ public static function getContactActivity() {
// Check if recurring activity.
if (!empty($value['is_recurring_activity'])) {
$repeat = $value['is_recurring_activity'];
- $activities['data'][$key]['activity_type'] .= ' ' . ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])) . '';
+ $activities['data'][$key]['activity_type'] .= ' ' . ts('Repeating (%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]) . '';
}
}
@@ -440,27 +437,20 @@ public static function getContactActivity() {
$formSearchField = 'activity_type_exclude_filter_id';
}
if (!empty($params[$searchField])) {
- $activityFilter[$formSearchField] = CRM_Utils_Type::escape($params[$searchField], $dataType);
- if (in_array($searchField, array('activity_date_low', 'activity_date_high'))) {
- $activityFilter['activity_date_relative'] = 0;
+ $activityFilter[$formSearchField] = $params[$searchField];
+ if (in_array($searchField, ['activity_date_time_low', 'activity_date_time_high'])) {
+ $activityFilter['activity_date_time_relative'] = 0;
}
elseif ($searchField == 'activity_status_id') {
$activityFilter['status_id'] = explode(',', $activityFilter[$searchField]);
}
}
- elseif (in_array($searchField, array('activity_type_id', 'activity_type_exclude_id'))) {
- $activityFilter[$formSearchField] = '';
- }
}
- /**
- * @var \Civi\Core\SettingsBag $cSettings
- */
- $cSettings = Civi::service('settings_manager')->getBagByContact(CRM_Core_Config::domainID(), $userID);
- $cSettings->set('activity_tab_filter', $activityFilter);
+ Civi::contactSettings()->set('activity_tab_filter', $activityFilter);
}
if (!empty($_GET['is_unit_test'])) {
- return array($activities, $activityFilter);
+ return [$activities, $activityFilter];
}
CRM_Utils_JSON::output($activities);
diff --git a/CRM/Activity/Page/Tab.php b/CRM/Activity/Page/Tab.php
index de6a0f35d252..4415618a7e2f 100644
--- a/CRM/Activity/Page/Tab.php
+++ b/CRM/Activity/Page/Tab.php
@@ -1,9 +1,9 @@
assign('context', $context);
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this);
@@ -86,12 +86,12 @@ public function edit() {
switch ($activityTypeId) {
case $emailTypeValue:
$wrapper = new CRM_Utils_Wrapper();
- $arguments = array('attachUpload' => 1);
+ $arguments = ['attachUpload' => 1];
return $wrapper->run('CRM_Contact_Form_Task_Email', ts('Email a Contact'), $arguments);
case $letterTypeValue:
$wrapper = new CRM_Utils_Wrapper();
- $arguments = array('attachUpload' => 1);
+ $arguments = ['attachUpload' => 1];
return $wrapper->run('CRM_Contact_Form_Task_PDF', ts('Create PDF Letter'), $arguments);
default:
@@ -131,6 +131,7 @@ public function preProcess() {
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->assign('action', $this->_action);
+ $this->assign('allow_edit_inbound_emails', CRM_Activity_BAO_Activity::checkEditInboundEmailsPermissions());
// also create the form element for the activity links box
$controller = new CRM_Core_Controller_Simple(
@@ -159,14 +160,14 @@ public function delete() {
* Perform actions and display for activities.
*/
public function run() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$action = CRM_Utils_Request::retrieve('action', 'String', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
// Do check for view/edit operation.
if ($this->_id &&
- in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))
+ in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW])
) {
if (!CRM_Activity_BAO_Activity::checkPermission($this->_id, $action)) {
CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
@@ -199,10 +200,10 @@ public function run() {
'Print PDF Letter'
);
- if (in_array($activityTypeId, array(
+ if (in_array($activityTypeId, [
$emailTypeValue,
$letterTypeValue,
- ))) {
+ ])) {
return;
}
}
diff --git a/CRM/Activity/Page/UserDashboard.php b/CRM/Activity/Page/UserDashboard.php
index ad32029a42df..d16a23d32ef2 100644
--- a/CRM/Activity/Page/UserDashboard.php
+++ b/CRM/Activity/Page/UserDashboard.php
@@ -1,9 +1,9 @@
set('context', 'user');
$controller->set('cid', $this->_contactId);
// Limit to status "Scheduled" and "Available"
- $controller->set('status', array('IN' => array(1, 7)));
+ $controller->set('status', ['IN' => [1, 7]]);
$controller->set('activity_role', 2);
$controller->set('force', 1);
$controller->process();
diff --git a/CRM/Activity/Selector/Activity.php b/CRM/Activity/Selector/Activity.php
index 69972ea1102c..6fef52aaff35 100644
--- a/CRM/Activity/Selector/Activity.php
+++ b/CRM/Activity/Selector/Activity.php
@@ -1,9 +1,9 @@
array(
+ VIEW => [
'name' => ts('View'),
'url' => $url,
'qs' => $qsView,
'title' => ts('View Activity'),
- ),
- );
+ ],
+ ];
}
if ($showUpdate) {
@@ -231,15 +235,15 @@ public static function actionLinks(
$updateUrl = 'civicrm/activity/pdf/add';
}
if (CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::UPDATE)) {
- $actionLinks += array(
+ $actionLinks += [
CRM_Core_Action::
- UPDATE => array(
+ UPDATE => [
'name' => ts('Edit'),
'url' => $updateUrl,
'qs' => $qsUpdate,
'title' => ts('Update Activity'),
- ),
- );
+ ],
+ ];
}
}
@@ -247,42 +251,42 @@ public static function actionLinks(
$activityTypeName &&
CRM_Case_BAO_Case::checkPermission($activityId, 'File On Case', $activityTypeId)
) {
- $actionLinks += array(
+ $actionLinks += [
CRM_Core_Action::
- ADD => array(
+ ADD => [
'name' => ts('File on Case'),
'url' => '#',
'extra' => 'onclick="javascript:fileOnCase( \'file\', \'%%id%%\', null, this ); return false;"',
'title' => ts('File on Case'),
- ),
- );
+ ],
+ ];
}
if ($showDelete) {
if (!isset($delUrl) || !$delUrl) {
$delUrl = $url;
}
- $actionLinks += array(
+ $actionLinks += [
CRM_Core_Action::
- DELETE => array(
+ DELETE => [
'name' => ts('Delete'),
'url' => $delUrl,
'qs' => $qsDelete,
'title' => ts('Delete Activity'),
- ),
- );
+ ],
+ ];
}
if ($accessMailingReport) {
- $actionLinks += array(
+ $actionLinks += [
CRM_Core_Action::
- BROWSE => array(
+ BROWSE => [
'name' => ts('Mailing Report'),
'url' => 'civicrm/mailing/report',
'qs' => "mid={$sourceRecordId}&reset=1&cid=%%cid%%&context=activitySelector",
'title' => ts('View Mailing Report'),
- ),
- );
+ ],
+ ];
}
return $actionLinks;
@@ -317,7 +321,7 @@ public function getPagerParams($action, &$params) {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if ($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) {
- $csvHeaders = array(ts('Activity Type'), ts('Description'), ts('Activity Date'));
+ $csvHeaders = [ts('Activity Type'), ts('Description'), ts('Activity Date')];
foreach (self::_getColumnHeaders() as $column) {
if (array_key_exists('name', $column)) {
$csvHeaders[] = $column['name'];
@@ -342,7 +346,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* Total number of rows
*/
public function getTotalCount($action, $case = NULL) {
- $params = array(
+ $params = [
'contact_id' => $this->_contactId,
'admin' => $this->_admin,
'caseId' => $case,
@@ -351,8 +355,8 @@ public function getTotalCount($action, $case = NULL) {
'offset' => 0,
'rowCount' => 0,
'sort' => NULL,
- );
- return CRM_Activity_BAO_Activity::deprecatedGetActivitiesCount($params);
+ ];
+ return CRM_Activity_BAO_Activity::getActivitiesCount($params);
}
/**
@@ -375,7 +379,7 @@ public function getTotalCount($action, $case = NULL) {
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $case = NULL) {
- $params = array(
+ $params = [
'contact_id' => $this->_contactId,
'admin' => $this->_admin,
'caseId' => $case,
@@ -384,9 +388,9 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ca
'offset' => $offset,
'rowCount' => $rowCount,
'sort' => $sort,
- );
+ ];
$config = CRM_Core_Config::singleton();
- $rows = CRM_Activity_BAO_Activity::deprecatedGetActivities($params);
+ $rows = CRM_Activity_BAO_Activity::getActivities($params);
if (empty($rows)) {
return $rows;
@@ -397,7 +401,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ca
$engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
// CRM-4418
- $permissions = array($this->_permission);
+ $permissions = [$this->_permission];
if (CRM_Core_Permission::check('delete activities')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
@@ -467,12 +471,12 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL, $ca
if ($output != CRM_Core_Selector_Controller::EXPORT && $output != CRM_Core_Selector_Controller::SCREEN) {
$row['action'] = CRM_Core_Action::formLink($actionLinks,
$actionMask,
- array(
+ [
'id' => $row['activity_id'],
'cid' => $this->_contactId,
'cxt' => $this->_context,
'caseid' => CRM_Utils_Array::value('case_id', $row),
- ),
+ ],
ts('more'),
FALSE,
'activity.selector.action',
@@ -508,36 +512,36 @@ public function getExportFileName($output = 'csv') {
*/
private static function &_getColumnHeaders() {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Type'),
'sort' => 'activity_type',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Subject'),
'sort' => 'subject',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Added By'),
'sort' => 'source_contact_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('name' => ts('With')),
- array('name' => ts('Assigned')),
- array(
+ ],
+ ['name' => ts('With')],
+ ['name' => ts('Assigned')],
+ [
'name' => ts('Date'),
'sort' => 'activity_date_time',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
}
return self::$_columnHeaders;
diff --git a/CRM/Activity/Selector/Search.php b/CRM/Activity/Selector/Search.php
index 8252b500426f..8a21dde81faa 100644
--- a/CRM/Activity/Selector/Search.php
+++ b/CRM/Activity/Selector/Search.php
@@ -1,9 +1,9 @@
$componentName) {
// CRM-19201: Add support for searching CiviCampaign and CiviCase
// activities. For CiviCase, "access all cases and activities" is
@@ -261,7 +261,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
FALSE,
$this->_activityClause
);
- $rows = array();
+ $rows = [];
$mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs();
$accessCiviMail = CRM_Core_Permission::check('access CiviMail');
@@ -273,11 +273,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
- // Get all activity types
- $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE);
+ $bulkActivityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
while ($result->fetch()) {
- $row = array();
+ $row = [];
// Ignore rows where we dont have an activity id.
if (empty($result->activity_id)) {
@@ -311,9 +310,8 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$accessMailingReport = FALSE;
$activityTypeId = $row['activity_type_id'];
if ($row['activity_is_test']) {
- $row['activity_type'] = $row['activity_type'] . " (test)";
+ $row['activity_type'] = CRM_Core_TestEntity::appendTestText($row['activity_type']);
}
- $bulkActivityTypeID = CRM_Utils_Array::key('Bulk Email', $activityTypes);
$row['mailingId'] = '';
if (
$accessCiviMail &&
@@ -337,11 +335,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$this->_compContext
);
$row['action'] = CRM_Core_Action::formLink($actionLinks, NULL,
- array(
+ [
'id' => $result->activity_id,
'cid' => $contactId,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'activity.selector.row',
@@ -363,7 +361,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['activity_id'], 'civicrm_activity');
$row['repeat'] = '';
if ($repeat) {
- $row['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
+ $row['repeat'] = ts('Repeating (%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
}
$rows[] = $row;
}
@@ -393,38 +391,38 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Type'),
'sort' => 'activity_type_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Subject'),
'sort' => 'activity_subject',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Added By'),
'sort' => 'source_contact',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('name' => ts('With')),
- array('name' => ts('Assigned')),
- array(
+ ],
+ ['name' => ts('With')],
+ ['name' => ts('Assigned')],
+ [
'name' => ts('Date'),
'sort' => 'activity_date_time',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'activity_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'desc' => ts('Actions'),
- ),
- );
+ ],
+ ];
}
return self::$_columnHeaders;
}
@@ -433,7 +431,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Activity/StateMachine/Search.php b/CRM/Activity/StateMachine/Search.php
index 6aa81146fe0d..237e9704fdf3 100644
--- a/CRM/Activity/StateMachine/Search.php
+++ b/CRM/Activity/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Activity_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -76,7 +76,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Activity/Task.php b/CRM/Activity/Task.php
index dbb2e6307d3f..00bfcbffd952 100644
--- a/CRM/Activity/Task.php
+++ b/CRM/Activity/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete activities'),
'class' => 'CRM_Activity_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Activity_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export activities'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
+ ],
+ self::BATCH_UPDATE => [
'title' => ts('Update multiple activities'),
- 'class' => array(
+ 'class' => [
'CRM_Activity_Form_Task_PickProfile',
'CRM_Activity_Form_Task_Batch',
- ),
+ ],
'result' => FALSE,
- ),
- 5 => array(
- 'title' => ts('Email - send now'),
- 'class' => array(
+ ],
+ self::TASK_EMAIL => [
+ 'title' => ts('Email - send now (to %1 or less)', [
+ 1 => Civi::settings()
+ ->get('simple_mail_limit'),
+ ]),
+ 'class' => [
'CRM_Activity_Form_Task_PickOption',
'CRM_Activity_Form_Task_Email',
- ),
+ ],
'result' => FALSE,
- ),
- 6 => array(
+ ],
+ self::TASK_SMS => [
'title' => ts('SMS - send reply'),
'class' => 'CRM_Activity_Form_Task_SMS',
'result' => FALSE,
- ),
- 7 => array(
+ ],
+ self::TAG_ADD => [
'title' => ts('Tag - add to activities'),
'class' => 'CRM_Activity_Form_Task_AddToTag',
'result' => FALSE,
- ),
- 8 => array(
+ ],
+ self::TAG_REMOVE => [
'title' => ts('Tag - remove from activities'),
'class' => 'CRM_Activity_Form_Task_RemoveFromTag',
'result' => FALSE,
- ),
- );
+ ],
+ ];
$config = CRM_Core_Config::singleton();
if (in_array('CiviCase', $config->enableComponents)) {
if (CRM_Core_Permission::check('access all cases and activities') ||
CRM_Core_Permission::check('access my cases and activities')
) {
- self::$_tasks[6] = array(
+ self::$_tasks[self::TASK_SMS] = [
'title' => ts('File on case'),
'class' => 'CRM_Activity_Form_Task_FileOnCase',
'result' => FALSE,
- );
+ ];
}
}
// CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete activities')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
- CRM_Utils_Hook::searchTasks('activity', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles on activity.
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
- }
-
/**
* Show tasks selectively based on the permission level of the user.
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if ($permission == CRM_Core_Permission::EDIT) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete activities')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -195,12 +165,13 @@ public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
- $value = 2;
+ $value = self::TASK_PRINT;
}
- return array(
+
+ return [
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
- );
+ ];
}
}
diff --git a/CRM/Activity/Tokens.php b/CRM/Activity/Tokens.php
index eb5ad34b827b..3271b965922f 100644
--- a/CRM/Activity/Tokens.php
+++ b/CRM/Activity/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -28,7 +28,7 @@
/**
* @package CRM
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
*/
/**
@@ -50,14 +50,8 @@ class CRM_Activity_Tokens extends \Civi\Token\AbstractTokenSubscriber {
*/
public function __construct() {
parent::__construct('activity', array_merge(
- array(
- 'activity_id' => ts('Activity ID'),
- 'activity_type' => ts('Activity Type'),
- 'subject' => ts('Activity Subject'),
- 'details' => ts('Activity Details'),
- 'activity_date_time' => ts('Activity Date-Time'),
- ),
- CRM_Utils_Token::getCustomFieldTokens('Activity')
+ $this->getBasicTokens(),
+ $this->getCustomFieldTokens()
));
}
@@ -66,8 +60,7 @@ public function __construct() {
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
- return
- !empty($processor->context['actionMapping'])
+ return !empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_activity';
}
@@ -84,7 +77,8 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
// Q: Could we simplify & move the extra AND clauses into `where(...)`?
$e->query->param('casEntityJoinExpr', 'e.id = reminder.entity_id AND e.is_current_revision = 1 AND e.is_deleted = 0');
- $e->query->select('e.*'); // FIXME: seems too broad.
+ // FIXME: seems too broad.
+ $e->query->select('e.*');
$e->query->select('ov.label as activity_type, e.id as activity_id');
$e->query->join("og", "!casMailingJoinType civicrm_option_group og ON og.name = 'activity_type'");
@@ -118,4 +112,27 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
}
}
+ /**
+ * Get the basic tokens provided.
+ *
+ * @return array token name => token label
+ */
+ protected function getBasicTokens() {
+ return [
+ 'activity_id' => ts('Activity ID'),
+ 'activity_type' => ts('Activity Type'),
+ 'subject' => ts('Activity Subject'),
+ 'details' => ts('Activity Details'),
+ 'activity_date_time' => ts('Activity Date-Time'),
+ ];
+ }
+
+ /**
+ * Get the tokens for custom fields
+ * @return array token name => token label
+ */
+ protected function getCustomFieldTokens() {
+ return CRM_Utils_Token::getCustomFieldTokens('Activity');
+ }
+
}
diff --git a/CRM/Admin/Form.php b/CRM/Admin/Form.php
index 8129e3f18466..e4edfb0a7c60 100644
--- a/CRM/Admin/Form.php
+++ b/CRM/Admin/Form.php
@@ -1,9 +1,9 @@
addStyleFile('civicrm', 'css/admin.css');
- Civi::resources()->addScriptFile('civicrm', 'js/crm.admin.js');
+ Civi::resources()->addScriptFile('civicrm', 'js/jquery/jquery.crmIconPicker.js');
$this->_id = $this->get('id');
$this->_BAOName = $this->get('BAOName');
- $this->_values = array();
+ $this->_values = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
// this is needed if the form is outside the CRM name space
$baoName = $this->_BAOName;
$baoName::retrieve($params, $this->_values);
@@ -92,8 +92,8 @@ public function preProcess() {
public function setDefaultValues() {
// Fetch defaults from the db
if (!empty($this->_id) && empty($this->_values) && CRM_Utils_Rule::positiveInteger($this->_id)) {
- $this->_values = array();
- $params = array('id' => $this->_id);
+ $this->_values = [];
+ $params = ['id' => $this->_id];
$baoName = $this->_BAOName;
$baoName::retrieve($params, $this->_values);
}
@@ -127,28 +127,26 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::VIEW || $this->_action & CRM_Core_Action::PREVIEW) {
- $this->addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
else {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => $this->_action & CRM_Core_Action::DELETE ? ts('Delete') : ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => $this->_action & CRM_Core_Action::DELETE ? ts('Delete') : ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Admin/Form/CMSUser.php b/CRM/Admin/Form/CMSUser.php
index ee79cc774216..44305056b654 100644
--- a/CRM/Admin/Form/CMSUser.php
+++ b/CRM/Admin/Form/CMSUser.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('OK'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('OK'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -62,25 +61,25 @@ public function postProcess() {
$result = CRM_Utils_System::synchronizeUsers();
$status = ts('Checked one user record.',
- array(
+ [
'count' => $result['contactCount'],
'plural' => 'Checked %count user records.',
- )
+ ]
);
if ($result['contactMatching']) {
$status .= ' ' . ts('Found one matching contact record.',
- array(
+ [
'count' => $result['contactMatching'],
'plural' => 'Found %count matching contact records.',
- )
+ ]
);
}
$status .= ' ' . ts('Created one new contact record.',
- array(
+ [
'count' => $result['contactCreated'],
'plural' => 'Created %count new contact records.',
- )
+ ]
);
CRM_Core_Session::setStatus($status, ts('Synchronize Complete'), 'success');
CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
diff --git a/CRM/Admin/Form/ContactType.php b/CRM/Admin/Form/ContactType.php
index 9e50d1427358..3e6f2a753646 100644
--- a/CRM/Admin/Form/ContactType.php
+++ b/CRM/Admin/Form/ContactType.php
@@ -1,9 +1,9 @@
assign('cid', $this->_id);
- $this->addFormRule(array('CRM_Admin_Form_ContactType', 'formRule'), $this);
+ $this->addFormRule(['CRM_Admin_Form_ContactType', 'formRule'], $this);
}
/**
@@ -90,7 +90,7 @@ public function buildQuickForm() {
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($self->_id) {
$contactName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_ContactType', $self->_id, 'name');
@@ -142,7 +142,7 @@ public function postProcess() {
}
$contactType = CRM_Contact_BAO_ContactType::add($params);
CRM_Core_Session::setStatus(ts("The Contact Type '%1' has been saved.",
- array(1 => $contactType->label)
+ [1 => $contactType->label]
), ts('Saved'), 'success');
}
diff --git a/CRM/Admin/Form/Extensions.php b/CRM/Admin/Form/Extensions.php
index 7f273cb1632f..852ebb082083 100644
--- a/CRM/Admin/Form/Extensions.php
+++ b/CRM/Admin/Form/Extensions.php
@@ -1,9 +1,9 @@
formatLocalExtensionRows();
+ $this->assign('localExtensionRows', $localExtensionRows);
+
+ $remoteExtensionRows = $mainPage->formatRemoteExtensionRows($localExtensionRows);
+ $this->assign('remoteExtensionRows', $remoteExtensionRows);
+
$this->_key = CRM_Utils_Request::retrieve('key', 'String',
$this, FALSE, 0
);
- if (!CRM_Utils_Type::validate($this->_key, 'ExtensionKey')) {
+ if (!CRM_Utils_Type::validate($this->_key, 'ExtensionKey') && !empty($this->_key)) {
throw new CRM_Core_Exception('Extension Key does not match expected standard');
}
$session = CRM_Core_Session::singleton();
@@ -83,7 +90,7 @@ public function preProcess() {
* Set default values for the form.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
return $defaults;
}
@@ -94,53 +101,52 @@ public function buildQuickForm() {
switch ($this->_action) {
case CRM_Core_Action::ADD:
$buttonName = ts('Install');
- $title = ts('Install "%1"?', array(
+ $title = ts('Install "%1"?', [
1 => $this->_key,
- ));
+ ]);
break;
case CRM_Core_Action::UPDATE:
$buttonName = ts('Download and Install');
- $title = ts('Download and Install "%1"?', array(
+ $title = ts('Download and Install "%1"?', [
1 => $this->_key,
- ));
+ ]);
break;
case CRM_Core_Action::DELETE:
$buttonName = ts('Uninstall');
- $title = ts('Uninstall "%1"?', array(
+ $title = ts('Uninstall "%1"?', [
1 => $this->_key,
- ));
+ ]);
break;
case CRM_Core_Action::ENABLE:
$buttonName = ts('Enable');
- $title = ts('Enable "%1"?', array(
+ $title = ts('Enable "%1"?', [
1 => $this->_key,
- ));
+ ]);
break;
case CRM_Core_Action::DISABLE:
$buttonName = ts('Disable');
- $title = ts('Disable "%1"?', array(
+ $title = ts('Disable "%1"?', [
1 => $this->_key,
- ));
+ ]);
break;
}
$this->assign('title', $title);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => $buttonName,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => $buttonName,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -157,7 +163,7 @@ public function buildQuickForm() {
* true if no errors, else an array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
return empty($errors) ? TRUE : $errors;
}
@@ -170,7 +176,7 @@ public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
try {
- CRM_Extension_System::singleton()->getManager()->uninstall(array($this->_key));
+ CRM_Extension_System::singleton()->getManager()->uninstall([$this->_key]);
CRM_Core_Session::setStatus("", ts('Extension Uninstalled'), "success");
}
catch (CRM_Extension_Exception_DependencyException $e) {
@@ -180,25 +186,25 @@ public function postProcess() {
}
if ($this->_action & CRM_Core_Action::ADD) {
- CRM_Extension_System::singleton()->getManager()->install(array($this->_key));
+ civicrm_api3('Extension', 'install', ['keys' => $this->_key]);
CRM_Core_Session::setStatus("", ts('Extension Installed'), "success");
}
if ($this->_action & CRM_Core_Action::ENABLE) {
- CRM_Extension_System::singleton()->getManager()->enable(array($this->_key));
+ civicrm_api3('Extension', 'enable', ['keys' => $this->_key]);
CRM_Core_Session::setStatus("", ts('Extension Enabled'), "success");
}
if ($this->_action & CRM_Core_Action::DISABLE) {
- CRM_Extension_System::singleton()->getManager()->disable(array($this->_key));
+ CRM_Extension_System::singleton()->getManager()->disable([$this->_key]);
CRM_Core_Session::setStatus("", ts('Extension Disabled'), "success");
}
if ($this->_action & CRM_Core_Action::UPDATE) {
- $result = civicrm_api('Extension', 'download', array(
+ $result = civicrm_api('Extension', 'download', [
'version' => 3,
'key' => $this->_key,
- ));
+ ]);
if (!CRM_Utils_Array::value('is_error', $result, FALSE)) {
CRM_Core_Session::setStatus("", ts('Extension Upgraded'), "success");
}
diff --git a/CRM/Admin/Form/Generic.php b/CRM/Admin/Form/Generic.php
new file mode 100644
index 000000000000..04b29ecd9793
--- /dev/null
+++ b/CRM/Admin/Form/Generic.php
@@ -0,0 +1,112 @@
+setDefaultsForMetadataDefinedFields();
+ return $this->_defaults;
+ }
+
+ /**
+ * Build the form object.
+ */
+ public function buildQuickForm() {
+ $filter = $this->getSettingPageFilter();
+ $settings = civicrm_api3('Setting', 'getfields', [])['values'];
+ foreach ($settings as $key => $setting) {
+ if (isset($setting['settings_pages'][$filter])) {
+ $this->_settings[$key] = $setting;
+ }
+ }
+
+ $this->addFieldsDefinedInSettingsMetadata();
+
+ // @todo look at sharing the code below in the settings trait.
+ if ($this->includesReadOnlyFields) {
+ CRM_Core_Session::setStatus(ts("Some fields are loaded as 'readonly' as they have been set (overridden) in civicrm.settings.php."), '', 'info', ['expires' => 0]);
+ }
+
+ // @todo - do we still like this redirect?
+ CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+ }
+
+ /**
+ * Process the form submission.
+ */
+ public function postProcess() {
+ $params = $this->controller->exportValues($this->_name);
+ try {
+ $this->saveMetadataDefinedSettings($params);
+ }
+ catch (CiviCRM_API3_Exception $e) {
+ CRM_Core_Session::setStatus($e->getMessage(), ts('Save Failed'), 'error');
+ }
+ }
+
+}
diff --git a/CRM/Admin/Form/Job.php b/CRM/Admin/Form/Job.php
index 9003bda4e583..42f4a3c3861d 100644
--- a/CRM/Admin/Form/Job.php
+++ b/CRM/Admin/Form/Job.php
@@ -1,9 +1,9 @@
addRule('name', ts('Name already exists in Database.'), 'objectExists', array(
- 'CRM_Core_DAO_Job',
- $this->_id,
- ));
+ $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [
+ 'CRM_Core_DAO_Job',
+ $this->_id,
+ ]);
$this->add('text', 'description', ts('Description'),
$attributes['description']
@@ -97,7 +97,7 @@ public function buildQuickForm($check = FALSE) {
$this->add('select', 'run_frequency', ts('Run frequency'), CRM_Core_SelectValues::getJobFrequency());
// CRM-17686
- $this->add('datepicker', 'scheduled_run_date', ts('Scheduled Run Date'), NULL, FALSE, array('minDate' => time()));
+ $this->add('datepicker', 'scheduled_run_date', ts('Scheduled Run Date'), NULL, FALSE, ['minDate' => time()]);
$this->add('textarea', 'parameters', ts('Command parameters'),
"cols=50 rows=6"
@@ -106,7 +106,7 @@ public function buildQuickForm($check = FALSE) {
// is this job active ?
$this->add('checkbox', 'is_active', ts('Is this Scheduled Job active?'));
- $this->addFormRule(array('CRM_Admin_Form_Job', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Job', 'formRule']);
}
/**
@@ -117,13 +117,13 @@ public function buildQuickForm($check = FALSE) {
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
require_once 'api/api.php';
/** @var \Civi\API\Kernel $apiKernel */
$apiKernel = \Civi::service('civi_api_kernel');
- $apiRequest = \Civi\API\Request::create($fields['api_entity'], $fields['api_action'], array('version' => 3), NULL);
+ $apiRequest = \Civi\API\Request::create($fields['api_entity'], $fields['api_action'], ['version' => 3], NULL);
try {
$apiKernel->resolve($apiRequest);
}
@@ -142,7 +142,7 @@ public static function formRule($fields) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!$this->_id) {
$defaults['is_active'] = $defaults['is_default'] = 1;
@@ -180,7 +180,7 @@ public function setDefaultValues() {
*/
public function postProcess() {
- CRM_Utils_System::flushCache('CRM_Core_DAO_Job');
+ CRM_Utils_System::flushCache();
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Core_BAO_Job::del($this->_id);
@@ -217,13 +217,13 @@ public function postProcess() {
The result will land on the same day of the month except for days 29-31 when the target month contains fewer days than the previous month.
For example, if a job is scheduled to run on August 31st, the following invocation will occur on October 1st, and then the 1st of every month thereafter.
To avoid this issue, please schedule Monthly and Quarterly jobs to run within the first 28 days of the month.'),
- ts('Warning'), 'info', array('expires' => 0));
+ ts('Warning'), 'info', ['expires' => 0]);
}
}
}
// ...otherwise, if this isn't a new scheduled job, clear the next scheduled run
elseif ($dao->id) {
- $job = new CRM_Core_ScheduledJob(array('id' => $dao->id));
+ $job = new CRM_Core_ScheduledJob(['id' => $dao->id]);
$job->clearScheduledRunDate();
}
@@ -233,7 +233,7 @@ public function postProcess() {
if ($values['api_action'] == 'update_greeting' && CRM_Utils_Array::value('is_active', $values) == 1) {
// pass "wiki" as 6th param to docURL2 if you are linking to a page in wiki.civicrm.org
$docLink = CRM_Utils_System::docURL2("Managing Scheduled Jobs", NULL, NULL, NULL, NULL, "wiki");
- $msg = ts('The update greeting job can be very resource intensive and is typically not necessary to run on a regular basis. If you do choose to enable the job, we recommend you do not run it with the force=1 option, which would rebuild greetings on all records. Leaving that option absent, or setting it to force=0, will only rebuild greetings for contacts that do not currently have a value stored. %1', array(1 => $docLink));
+ $msg = ts('The update greeting job can be very resource intensive and is typically not necessary to run on a regular basis. If you do choose to enable the job, we recommend you do not run it with the force=1 option, which would rebuild greetings on all records. Leaving that option absent, or setting it to force=0, will only rebuild greetings for contacts that do not currently have a value stored. %1', [1 => $docLink]);
CRM_Core_Session::setStatus($msg, ts('Warning: Update Greeting job enabled'), 'alert');
}
diff --git a/CRM/Admin/Form/LabelFormats.php b/CRM/Admin/Form/LabelFormats.php
index 73ef984e89cd..6e3ad025df0c 100644
--- a/CRM/Admin/Form/LabelFormats.php
+++ b/CRM/Admin/Form/LabelFormats.php
@@ -1,7 +1,7 @@
_id = $this->get('id');
$this->_group = CRM_Utils_Request::retrieve('group', 'String', $this, FALSE, 'label_format');
- $this->_values = array();
+ $this->_values = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Core_BAO_LabelFormat::retrieve($params, $this->_values, $this->_group);
}
}
@@ -69,7 +71,7 @@ public function buildQuickForm() {
return;
}
- $disabled = array();
+ $disabled = [];
$required = TRUE;
$is_reserved = $this->_id ? CRM_Core_BAO_LabelFormat::getFieldValue('CRM_Core_BAO_LabelFormat', $this->_id, 'is_reserved') : FALSE;
if ($is_reserved) {
@@ -79,7 +81,7 @@ public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat');
$this->add('text', 'label', ts('Name'), $attributes['label'] + $disabled, $required);
- $this->add('text', 'description', ts('Description'), array('size' => CRM_Utils_Type::HUGE));
+ $this->add('text', 'description', ts('Description'), ['size' => CRM_Utils_Type::HUGE]);
$this->add('checkbox', 'is_default', ts('Is this Label Format the default?'));
// currently we support only mailing label creation, hence comment below code
@@ -97,18 +99,18 @@ public function buildQuickForm() {
*/
$this->add('select', 'paper_size', ts('Sheet Size'),
- array(
+ [
0 => ts('- default -'),
- ) + CRM_Core_BAO_PaperSize::getList(TRUE), FALSE,
- array(
+ ] + CRM_Core_BAO_PaperSize::getList(TRUE), FALSE,
+ [
'onChange' => "selectPaper( this.value );",
- ) + $disabled
+ ] + $disabled
);
$this->add('static', 'paper_dimensions', NULL, ts('Sheet Size (w x h)'));
$this->add('select', 'orientation', ts('Orientation'), CRM_Core_BAO_LabelFormat::getPageOrientations(), FALSE,
- array(
+ [
'onChange' => "updatePaperDimensions();",
- ) + $disabled
+ ] + $disabled
);
$this->add('select', 'font_name', ts('Font Name'), CRM_Core_BAO_LabelFormat::getFontNames($this->_group));
$this->add('select', 'font_size', ts('Font Size'), CRM_Core_BAO_LabelFormat::getFontSizes());
@@ -116,24 +118,24 @@ public function buildQuickForm() {
$this->add('checkbox', 'bold', ts('Bold'));
$this->add('checkbox', 'italic', ts('Italic'));
$this->add('select', 'metric', ts('Unit of Measure'), CRM_Core_BAO_LabelFormat::getUnits(), FALSE,
- array('onChange' => "selectMetric( this.value );")
+ ['onChange' => "selectMetric( this.value );"]
);
- $this->add('text', 'width', ts('Label Width'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
- $this->add('text', 'height', ts('Label Height'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
- $this->add('text', 'NX', ts('Labels Per Row'), array('size' => 3, 'maxlength' => 3) + $disabled, $required);
- $this->add('text', 'NY', ts('Labels Per Column'), array('size' => 3, 'maxlength' => 3) + $disabled, $required);
- $this->add('text', 'tMargin', ts('Top Margin'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
- $this->add('text', 'lMargin', ts('Left Margin'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
- $this->add('text', 'SpaceX', ts('Horizontal Spacing'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
- $this->add('text', 'SpaceY', ts('Vertical Spacing'), array('size' => 8, 'maxlength' => 8) + $disabled, $required);
- $this->add('text', 'lPadding', ts('Left Padding'), array('size' => 8, 'maxlength' => 8), $required);
- $this->add('text', 'tPadding', ts('Top Padding'), array('size' => 8, 'maxlength' => 8), $required);
- $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat', 'weight'), TRUE);
-
- $this->addRule('label', ts('Name already exists in Database.'), 'objectExists', array(
+ $this->add('text', 'width', ts('Label Width'), ['size' => 8, 'maxlength' => 8] + $disabled, $required);
+ $this->add('text', 'height', ts('Label Height'), ['size' => 8, 'maxlength' => 8] + $disabled, $required);
+ $this->add('text', 'NX', ts('Labels Per Row'), ['size' => 3, 'maxlength' => 3] + $disabled, $required);
+ $this->add('text', 'NY', ts('Labels Per Column'), ['size' => 3, 'maxlength' => 3] + $disabled, $required);
+ $this->add('text', 'tMargin', ts('Top Margin'), ['size' => 8, 'maxlength' => 8] + $disabled, $required);
+ $this->add('text', 'lMargin', ts('Left Margin'), ['size' => 8, 'maxlength' => 8] + $disabled, $required);
+ $this->add('text', 'SpaceX', ts('Horizontal Spacing'), ['size' => 8, 'maxlength' => 8] + $disabled, $required);
+ $this->add('text', 'SpaceY', ts('Vertical Spacing'), ['size' => 8, 'maxlength' => 8] + $disabled, $required);
+ $this->add('text', 'lPadding', ts('Left Padding'), ['size' => 8, 'maxlength' => 8], $required);
+ $this->add('text', 'tPadding', ts('Top Padding'), ['size' => 8, 'maxlength' => 8], $required);
+ $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_BAO_LabelFormat', 'weight'), TRUE);
+
+ $this->addRule('label', ts('Name already exists in Database.'), 'objectExists', [
'CRM_Core_BAO_LabelFormat',
$this->_id,
- ));
+ ]);
$this->addRule('NX', ts('Please enter a valid integer.'), 'integer');
$this->addRule('NY', ts('Please enter a valid integer.'), 'integer');
$this->addRule('tMargin', ts('Please enter a valid number.'), 'numeric');
@@ -186,14 +188,14 @@ public function postProcess() {
if ($this->_action & CRM_Core_Action::COPY) {
// make a copy of the Label Format
$labelFormat = CRM_Core_BAO_LabelFormat::getById($this->_id, $this->_group);
- $newlabel = ts('Copy of %1', array(1 => $labelFormat['label']));
+ $newlabel = ts('Copy of %1', [1 => $labelFormat['label']]);
$list = CRM_Core_BAO_LabelFormat::getList(TRUE, $this->_group);
$count = 1;
while (in_array($newlabel, $list)) {
$count++;
- $newlabel = ts('Copy %1 of %2', array(1 => $count, 2 => $labelFormat['label']));
+ $newlabel = ts('Copy %1 of %2', [1 => $count, 2 => $labelFormat['label']]);
}
$labelFormat['label'] = $newlabel;
@@ -203,7 +205,7 @@ public function postProcess() {
$bao = new CRM_Core_BAO_LabelFormat();
$bao->saveLabelFormat($labelFormat, NULL, $this->_group);
- CRM_Core_Session::setStatus(ts('%1 has been created.', array(1 => $labelFormat['label'])), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('%1 has been created.', [1 => $labelFormat['label']]), ts('Saved'), 'success');
return;
}
@@ -240,9 +242,9 @@ public function postProcess() {
$bao = new CRM_Core_BAO_LabelFormat();
$bao->saveLabelFormat($values, $this->_id, $values['label_type']);
- $status = ts('Your new Label Format titled %1 has been saved.', array(1 => $values['label']));
+ $status = ts('Your new Label Format titled %1 has been saved.', [1 => $values['label']]);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $status = ts('Your Label Format titled %1 has been updated.', array(1 => $values['label']));
+ $status = ts('Your Label Format titled %1 has been updated.', [1 => $values['label']]);
}
CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
}
diff --git a/CRM/Admin/Form/LocationType.php b/CRM/Admin/Form/LocationType.php
index 9c6dbb723b55..65e43aff0b12 100644
--- a/CRM/Admin/Form/LocationType.php
+++ b/CRM/Admin/Form/LocationType.php
@@ -1,9 +1,9 @@
addRule('name',
ts('Name already exists in Database.'),
'objectExists',
- array('CRM_Core_DAO_LocationType', $this->_id)
+ ['CRM_Core_DAO_LocationType', $this->_id]
);
$this->addRule('name',
ts('Name can only consist of alpha-numeric characters'),
@@ -74,10 +74,10 @@ public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::UPDATE) {
if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', $this->_id, 'is_reserved')) {
- $this->freeze(array('name', 'description', 'is_active'));
+ $this->freeze(['name', 'description', 'is_active']);
}
if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', $this->_id, 'is_default')) {
- $this->freeze(array('is_default'));
+ $this->freeze(['is_default']);
}
}
}
@@ -86,7 +86,7 @@ public function buildQuickForm() {
* Process the form submission.
*/
public function postProcess() {
- CRM_Utils_System::flushCache('CRM_Core_DAO_LocationType');
+ CRM_Utils_System::flushCache();
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Core_BAO_LocationType::del($this->_id);
@@ -120,7 +120,7 @@ public function postProcess() {
$locationType->save();
CRM_Core_Session::setStatus(ts("The location type '%1' has been saved.",
- array(1 => $locationType->name)
+ [1 => $locationType->name]
), ts('Saved'), 'success');
}
diff --git a/CRM/Admin/Form/MailSettings.php b/CRM/Admin/Form/MailSettings.php
index a40b3f2adcd2..b87ccd961047 100644
--- a/CRM/Admin/Form/MailSettings.php
+++ b/CRM/Admin/Form/MailSettings.php
@@ -1,9 +1,9 @@
add('select', 'protocol',
ts('Protocol'),
- array('' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_MailSettings', 'protocol'),
+ ['' => ts('- select -')] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_MailSettings', 'protocol'),
TRUE
);
$this->add('text', 'server', ts('Server'), $attributes['server']);
- $this->add('text', 'username', ts('Username'), array('autocomplete' => 'off'));
+ $this->add('text', 'username', ts('Username'), ['autocomplete' => 'off']);
- $this->add('password', 'password', ts('Password'), array('autocomplete' => 'off'));
+ $this->add('password', 'password', ts('Password'), ['autocomplete' => 'off']);
$this->add('text', 'source', ts('Source'), $attributes['source']);
$this->add('checkbox', 'is_ssl', ts('Use SSL?'));
- $usedfor = array(
+ $usedfor = [
1 => ts('Bounce Processing'),
0 => ts('Email-to-Activity Processing'),
- );
+ ];
$this->add('select', 'is_default', ts('Used For?'), $usedfor);
- $this->addField('activity_status', array('placeholder' => FALSE));
+ $this->addField('activity_status', ['placeholder' => FALSE]);
}
/**
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Admin_Form_MailSettings', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_MailSettings', 'formRule']);
}
public function getDefaultEntity() {
@@ -125,7 +125,7 @@ public function setDefaultValues() {
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
// Check for default from email address and organization (domain) name. Force them to change it.
if ($fields['domain'] == 'EXAMPLE.ORG') {
$errors['domain'] = ts('Please enter a valid domain for this mailbox account (the part after @).');
@@ -148,7 +148,7 @@ public function postProcess() {
$formValues = $this->controller->exportValues($this->_name);
//form fields.
- $fields = array(
+ $fields = [
'name',
'domain',
'localpart',
@@ -162,14 +162,14 @@ public function postProcess() {
'is_ssl',
'is_default',
'activity_status',
- );
+ ];
- $params = array();
+ $params = [];
foreach ($fields as $f) {
- if (in_array($f, array(
+ if (in_array($f, [
'is_default',
'is_ssl',
- ))) {
+ ])) {
$params[$f] = CRM_Utils_Array::value($f, $formValues, FALSE);
}
else {
diff --git a/CRM/Admin/Form/Mapping.php b/CRM/Admin/Form/Mapping.php
index 8286b9c6495f..2dac50e76328 100644
--- a/CRM/Admin/Form/Mapping.php
+++ b/CRM/Admin/Form/Mapping.php
@@ -1,9 +1,9 @@
add('text', 'name', ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Core_DAO_Mapping', 'name'), TRUE
);
- $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array(
- 'CRM_Core_DAO_Mapping',
- $this->_id,
- ));
+ $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [
+ 'CRM_Core_DAO_Mapping',
+ $this->_id,
+ ]);
$this->addElement('text', 'description', ts('Description'),
CRM_Core_DAO::getAttribute('CRM_Core_DAO_Mapping', 'description')
diff --git a/CRM/Admin/Form/MessageTemplates.php b/CRM/Admin/Form/MessageTemplates.php
index 7e2330dc5137..06f0259ec921 100644
--- a/CRM/Admin/Form/MessageTemplates.php
+++ b/CRM/Admin/Form/MessageTemplates.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- 'js' => array('onclick' => "location.href='{$cancelURL}'; return false;"),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ 'js' => ['onclick' => "location.href='{$cancelURL}'; return false;"],
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
else {
$this->_workflow_id = CRM_Utils_Array::value('workflow_id', $this->_values);
+ $this->checkUserPermission($this->_workflow_id);
$this->assign('workflow_id', $this->_workflow_id);
if ($this->_workflow_id) {
@@ -117,44 +123,43 @@ public function buildQuickForm() {
$cancelURL = CRM_Utils_System::url('civicrm/admin/messageTemplates', "selectedChild={$selectedChild}&reset=1");
$cancelURL = str_replace('&', '&', $cancelURL);
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => $this->_action & CRM_Core_Action::DELETE ? ts('Delete') : ts('Save'),
'isDefault' => TRUE,
- );
+ ];
if (!($this->_action & CRM_Core_Action::DELETE)) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'submit',
'name' => ts('Save and Done'),
'subName' => 'done',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- 'js' => array('onclick' => "location.href='{$cancelURL}'; return false;"),
- );
+ 'js' => ['onclick' => "location.href='{$cancelURL}'; return false;"],
+ ];
$this->addButtons($buttons);
}
if ($this->_action & CRM_Core_Action::DELETE) {
+ $this->assign('msg_title', $this->_values['msg_title']);
return;
}
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Message Templates'),
- 'url' => CRM_Utils_System::url('civicrm/admin/messageTemplates',
- 'action=browse&reset=1'
- ),
- ),
- );
+ 'url' => CRM_Utils_System::url('civicrm/admin/messageTemplates', 'action=browse&reset=1'),
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
$this->applyFilter('__ALL__', 'trim');
$this->add('text', 'msg_title', ts('Message Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_MessageTemplate', 'msg_title'), TRUE);
- $options = array(ts('Compose On-screen'), ts('Upload Document'));
+ $options = [ts('Compose On-screen'), ts('Upload Document')];
$element = $this->addRadio('file_type', ts('Source'), $options);
if ($this->_id) {
$element->freeze();
@@ -186,12 +191,12 @@ public function buildQuickForm() {
}
else {
$this->add('wysiwyg', 'msg_html', ts('HTML Message'),
- array(
+ [
'cols' => '80',
'rows' => '8',
'onkeyup' => "return verify(this)",
'preset' => 'civimail',
- )
+ ]
);
}
@@ -200,13 +205,13 @@ public function buildQuickForm() {
);
$this->add('select', 'pdf_format_id', ts('PDF Page Format'),
- array(
+ [
'null' => ts('- default -'),
- ) + CRM_Core_BAO_PdfFormat::getList(TRUE), FALSE
+ ] + CRM_Core_BAO_PdfFormat::getList(TRUE), FALSE
);
$this->add('checkbox', 'is_active', ts('Enabled?'));
- $this->addFormRule(array(__CLASS__, 'formRule'), $this);
+ $this->addFormRule([__CLASS__, 'formRule'], $this);
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
@@ -214,6 +219,26 @@ public function buildQuickForm() {
}
}
+ /**
+ * Restrict users access based on permission
+ *
+ * @param int $workflowId
+ */
+ private function checkUserPermission($workflowId) {
+ if (isset($workflowId)) {
+ $canView = CRM_Core_Permission::check('edit system workflow message templates');
+ }
+ else {
+ $canView = CRM_Core_Permission::check('edit user-driven message templates');
+ }
+
+ if (!$canView && !CRM_Core_Permission::check('edit message templates')) {
+ CRM_Core_Session::setStatus(ts('You do not have permission to view requested page.'), ts('Access Denied'));
+ $url = CRM_Utils_System::url('civicrm/admin/messageTemplates', "reset=1");
+ CRM_Utils_System::redirect($url);
+ }
+ }
+
/**
* Global form rule.
*
@@ -287,7 +312,7 @@ public function postProcess() {
}
$messageTemplate = CRM_Core_BAO_MessageTemplate::add($params);
- CRM_Core_Session::setStatus(ts('The Message Template \'%1\' has been saved.', array(1 => $messageTemplate->msg_title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The Message Template \'%1\' has been saved.', [1 => $messageTemplate->msg_title]), ts('Saved'), 'success');
if (isset($this->_submitValues['_qf_MessageTemplates_upload'])) {
// Save button was pressed
diff --git a/CRM/Admin/Form/Navigation.php b/CRM/Admin/Form/Navigation.php
index 12cd0804717a..1d7ae860cb18 100644
--- a/CRM/Admin/Form/Navigation.php
+++ b/CRM/Admin/Form/Navigation.php
@@ -1,9 +1,9 @@
_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Core_BAO_Navigation::retrieve($params, $this->_defaults);
}
@@ -68,21 +69,21 @@ public function buildQuickForm() {
$this->add('text', 'url', ts('Url'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Navigation', 'url'));
- $this->add('text', 'icon', ts('Icon'), array('class' => 'crm-icon-picker', 'title' => ts('Choose Icon'), 'allowClear' => TRUE));
+ $this->add('text', 'icon', ts('Icon'), ['class' => 'crm-icon-picker', 'title' => ts('Choose Icon'), 'allowClear' => TRUE]);
- $permissions = array();
+ $permissions = [];
foreach (CRM_Core_Permission::basicPermissions(TRUE, TRUE) as $id => $vals) {
- $permissions[] = array('id' => $id, 'label' => $vals[0], 'description' => (array) CRM_Utils_Array::value(1, $vals));
+ $permissions[] = ['id' => $id, 'text' => $vals[0], 'description' => (array) CRM_Utils_Array::value(1, $vals)];
}
- $this->add('text', 'permission', ts('Permission'),
- array('placeholder' => ts('Unrestricted'), 'class' => 'huge', 'data-select-params' => json_encode(array('data' => array('results' => $permissions, 'text' => 'label'))))
+ $this->add('select2', 'permission', ts('Permission'), $permissions, FALSE,
+ ['placeholder' => ts('Unrestricted'), 'class' => 'huge', 'multiple' => TRUE]
);
- $operators = array('AND' => ts('AND'), 'OR' => ts('OR'));
+ $operators = ['AND' => ts('AND'), 'OR' => ts('OR')];
$this->add('select', 'permission_operator', NULL, $operators);
//make separator location configurable
- $separator = array(ts('None'), ts('After menu element'), ts('Before menu element'));
+ $separator = [ts('None'), ts('After menu element'), ts('Before menu element')];
$this->add('select', 'has_separator', ts('Separator'), $separator);
$active = $this->add('advcheckbox', 'is_active', ts('Enabled'));
@@ -101,7 +102,7 @@ public function buildQuickForm() {
$homeMenuId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Navigation', 'Home', 'id', 'name');
unset($parentMenu[$homeMenuId]);
- $this->add('select', 'parent_id', ts('Parent'), array('' => ts('Top level')) + $parentMenu, FALSE, array('class' => 'crm-select2'));
+ $this->add('select', 'parent_id', ts('Parent'), ['' => ts('Top level')] + $parentMenu, FALSE, ['class' => 'crm-select2']);
}
}
@@ -122,6 +123,10 @@ public function setDefaultValues() {
// its ok if there is no element called is_active
$defaults['is_active'] = ($this->_id) ? $this->_defaults['is_active'] : 1;
+ if (!empty($defaults['icon'])) {
+ $defaults['icon'] = trim(str_replace('crm-i', '', $defaults['icon']));
+ }
+
return $defaults;
}
@@ -147,7 +152,7 @@ public function postProcess() {
CRM_Core_BAO_Navigation::resetNavigation();
CRM_Core_Session::setStatus(ts('Menu \'%1\' has been saved.',
- array(1 => $navigation->label)
+ [1 => $navigation->label]
), ts('Saved'), 'success');
}
diff --git a/CRM/Admin/Form/OptionGroup.php b/CRM/Admin/Form/OptionGroup.php
index c7622ff79070..8076680a6f81 100644
--- a/CRM/Admin/Form/OptionGroup.php
+++ b/CRM/Admin/Form/OptionGroup.php
@@ -1,9 +1,9 @@
addRule('name',
ts('Name already exists in Database.'),
'objectExists',
- array('CRM_Core_DAO_OptionGroup', $this->_id)
+ ['CRM_Core_DAO_OptionGroup', $this->_id]
);
$this->add('text',
@@ -78,15 +78,15 @@ public function buildQuickForm() {
CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionGroup', 'description')
);
- $this->addSelect('data_type', array('options' => CRM_Utils_Type::dataTypes()), TRUE);
+ $this->addSelect('data_type', ['options' => CRM_Utils_Type::dataTypes()], empty($this->_values['is_reserved']));
$element = $this->add('checkbox', 'is_active', ts('Enabled?'));
if ($this->_action & CRM_Core_Action::UPDATE) {
- if (in_array($this->_values['name'], array(
+ if (in_array($this->_values['name'], [
'encounter_medium',
'case_type',
'case_status',
- ))) {
+ ])) {
static $caseCount = NULL;
if (!isset($caseCount)) {
$caseCount = CRM_Case_BAO_Case::caseCount(NULL, FALSE);
@@ -96,8 +96,12 @@ public function buildQuickForm() {
$element->freeze();
}
}
+
+ $this->add('checkbox', 'is_reserved', ts('Reserved?'));
+ $this->freeze('is_reserved');
+
if (!empty($this->_values['is_reserved'])) {
- $this->freeze(array('name', 'is_active'));
+ $this->freeze(['name', 'is_active', 'data_type']);
}
}
@@ -110,23 +114,26 @@ public function buildQuickForm() {
public function postProcess() {
CRM_Utils_System::flushCache();
- $params = $this->exportValues();
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Core_BAO_OptionGroup::del($this->_id);
CRM_Core_Session::setStatus(ts('Selected option group has been deleted.'), ts('Record Deleted'), 'success');
}
else {
-
- $params = $ids = array();
// store the submitted values in an array
$params = $this->exportValues();
- if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['optionGroup'] = $this->_id;
+ if ($this->_action & CRM_Core_Action::ADD) {
+ // If we are adding option group via UI it should not be marked reserved.
+ if (!isset($params['is_reserved'])) {
+ $params['is_reserved'] = 0;
+ }
+ }
+ elseif ($this->_action & CRM_Core_Action::UPDATE) {
+ $params['id'] = $this->_id;
}
- $optionGroup = CRM_Core_BAO_OptionGroup::add($params, $ids);
- CRM_Core_Session::setStatus(ts('The Option Group \'%1\' has been saved.', array(1 => $optionGroup->name)), ts('Saved'), 'success');
+ $optionGroup = CRM_Core_BAO_OptionGroup::add($params);
+ CRM_Core_Session::setStatus(ts('The Option Group \'%1\' has been saved.', [1 => $optionGroup->name]), ts('Saved'), 'success');
}
}
diff --git a/CRM/Admin/Form/Options.php b/CRM/Admin/Form/Options.php
index e247f5519453..3e8dd6a65aa6 100644
--- a/CRM/Admin/Form/Options.php
+++ b/CRM/Admin/Form/Options.php
@@ -1,9 +1,9 @@
_gLabel = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $this->_gid, 'title');
+ $this->_domainSpecific = in_array($this->_gName, CRM_Core_OptionGroup::$_domainIDGroups);
$url = "civicrm/admin/options/{$this->_gName}";
$params = "reset=1";
if (($this->_action & CRM_Core_Action::DELETE) &&
- in_array($this->_gName, array('email_greeting', 'postal_greeting', 'addressee'))
+ in_array($this->_gName, ['email_greeting', 'postal_greeting', 'addressee'])
) {
// Don't allow delete if the option value belongs to addressee, postal or email greetings and is in use.
$findValue = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'value');
- $queryParam = array(1 => array($findValue, 'Integer'));
+ $queryParam = [1 => [$findValue, 'Integer']];
$columnName = $this->_gName . "_id";
$sql = "SELECT count(id) FROM civicrm_contact WHERE " . $columnName . " = %1";
$isInUse = CRM_Core_DAO::singleValueQuery($sql, $queryParam);
if ($isInUse) {
$scriptURL = "" . ts('Learn more about a script that can automatically update contact addressee and greeting options.') . "";
- CRM_Core_Session::setStatus(ts('The selected %1 option has not been deleted because it is currently in use. Please update these contacts to use a different format before deleting this option. %2', array(
- 1 => $this->_gLabel,
- 2 => $scriptURL,
- )), ts('Sorry'), 'error');
+ CRM_Core_Session::setStatus(ts('The selected %1 option has not been deleted because it is currently in use. Please update these contacts to use a different format before deleting this option. %2', [
+ 1 => $this->_gLabel,
+ 2 => $scriptURL,
+ ]), ts('Sorry'), 'error');
$redirect = CRM_Utils_System::url($url, $params);
CRM_Utils_System::redirect($redirect);
}
@@ -115,19 +122,19 @@ public function setDefaultValues() {
$defaults = parent::setDefaultValues();
// Default weight & value
- $fieldValues = array('option_group_id' => $this->_gid);
- foreach (array('weight', 'value') as $field) {
+ $fieldValues = ['option_group_id' => $this->_gid];
+ foreach (['weight', 'value'] as $field) {
if (empty($defaults[$field])) {
$defaults[$field] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues, $field);
}
}
- //setDefault of contact types for email greeting, postal greeting, addressee, CRM-4575
- if (in_array($this->_gName, array(
+ // setDefault of contact types for email greeting, postal greeting, addressee, CRM-4575
+ if (in_array($this->_gName, [
'email_greeting',
'postal_greeting',
'addressee',
- ))) {
+ ])) {
$defaults['contactOptions'] = (CRM_Utils_Array::value('filter', $defaults)) ? $defaults['filter'] : NULL;
}
// CRM-11516
@@ -145,7 +152,7 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->setPageTitle(ts('%1 Option', array(1 => $this->_gLabel)));
+ $this->setPageTitle(ts('%1 Option', [1 => $this->_gLabel]));
if ($this->_action & CRM_Core_Action::DELETE) {
return;
@@ -172,35 +179,35 @@ public function buildQuickForm() {
CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'),
TRUE
);
+ $this->addRule('value',
+ ts('This Value already exists in the database for this option group. Please select a different Value.'),
+ 'optionExists',
+ ['CRM_Core_DAO_OptionValue', $this->_id, $this->_gid, 'value', $this->_domainSpecific]
+ );
}
else {
- $this->add('text', 'icon', ts('Icon'), array('class' => 'crm-icon-picker', 'title' => ts('Choose Icon'), 'allowClear' => TRUE));
+ $this->add('text', 'icon', ts('Icon'), ['class' => 'crm-icon-picker', 'title' => ts('Choose Icon'), 'allowClear' => TRUE]);
}
- if (in_array($this->_gName, array('activity_status', 'case_status'))) {
+ if (in_array($this->_gName, ['activity_status', 'case_status'])) {
$this->add('color', 'color', ts('Color'));
}
- if (!in_array($this->_gName, array(
- 'email_greeting',
- 'postal_greeting',
- 'addressee',
- )) && !$isReserved
+ if (!in_array($this->_gName, ['email_greeting', 'postal_greeting', 'addressee'])
+ && !$isReserved
) {
- $domainSpecificOptionGroups = array('from_email_address');
- $domainSpecific = in_array($this->_gName, $domainSpecificOptionGroups) ? TRUE : FALSE;
$this->addRule('label',
- ts('This Label already exists in the database for this option group. Please select a different Value.'),
+ ts('This Label already exists in the database for this option group. Please select a different Label.'),
'optionExists',
- array('CRM_Core_DAO_OptionValue', $this->_id, $this->_gid, 'label', $domainSpecific)
+ ['CRM_Core_DAO_OptionValue', $this->_id, $this->_gid, 'label', $this->_domainSpecific]
);
}
if ($this->_gName == 'case_status') {
- $classes = array(
+ $classes = [
'Opened' => ts('Opened'),
'Closed' => ts('Closed'),
- );
+ ];
$grouping = $this->add('select',
'grouping',
@@ -217,7 +224,7 @@ public function buildQuickForm() {
$financialAccount = CRM_Contribute_PseudoConstant::financialAccount(NULL, key($accountType));
$this->add('select', 'financial_account_id', ts('Financial Account'),
- array('' => ts('- select -')) + $financialAccount,
+ ['' => ts('- select -')] + $financialAccount,
TRUE
);
}
@@ -226,11 +233,11 @@ public function buildQuickForm() {
$this->add('select',
'filter',
ts('Status Type'),
- array(
+ [
CRM_Activity_BAO_Activity::INCOMPLETE => ts('Incomplete'),
CRM_Activity_BAO_Activity::COMPLETED => ts('Completed'),
CRM_Activity_BAO_Activity::CANCELLED => ts('Cancelled'),
- )
+ ]
);
}
if ($this->_gName == 'redaction_rule') {
@@ -250,7 +257,7 @@ public function buildQuickForm() {
// Hard-coding attributes here since description is still stored as varchar and not text in the schema. dgg
$this->add('wysiwyg', 'description',
ts('Description'),
- array('rows' => 4, 'cols' => 80),
+ ['rows' => 4, 'cols' => 80],
$this->_gName == 'custom_search'
);
}
@@ -263,7 +270,7 @@ public function buildQuickForm() {
);
}
- $this->add('text',
+ $this->add('number',
'weight',
ts('Order'),
CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'),
@@ -278,7 +285,7 @@ public function buildQuickForm() {
(($this->_action & CRM_Core_Action::ADD) || !$isReserved)
) {
$caseID = CRM_Core_Component::getComponentID('CiviCase');
- $components = array('' => ts('Contacts AND Cases'), $caseID => ts('Cases Only'));
+ $components = ['' => ts('Contacts AND Cases'), $caseID => ts('Cases Only')];
$this->add('select',
'component_id',
ts('Component'),
@@ -292,8 +299,8 @@ public function buildQuickForm() {
$enabled->freeze();
}
- //fix for CRM-3552, CRM-4575
- $showIsDefaultGroups = array(
+ // fix for CRM-3552, CRM-4575
+ $showIsDefaultGroups = [
'email_greeting',
'postal_greeting',
'addressee',
@@ -305,33 +312,30 @@ public function buildQuickForm() {
'communication_style',
'soft_credit_type',
'website_type',
- );
+ ];
if (in_array($this->_gName, $showIsDefaultGroups)) {
$this->assign('showDefault', TRUE);
$this->add('checkbox', 'is_default', ts('Default Option?'));
}
- //get contact type for which user want to create a new greeting/addressee type, CRM-4575
- if (in_array($this->_gName, array(
- 'email_greeting',
- 'postal_greeting',
- 'addressee',
- )) && !$isReserved
+ // get contact type for which user want to create a new greeting/addressee type, CRM-4575
+ if (in_array($this->_gName, ['email_greeting', 'postal_greeting', 'addressee'])
+ && !$isReserved
) {
- $values = array(
+ $values = [
1 => ts('Individual'),
2 => ts('Household'),
3 => ts('Organization'),
4 => ts('Multiple Contact Merge'),
- );
- $this->add('select', 'contactOptions', ts('Contact Type'), array('' => '-select-') + $values, TRUE);
+ ];
+ $this->add('select', 'contactOptions', ts('Contact Type'), ['' => '-select-'] + $values, TRUE);
$this->assign('showContactFilter', TRUE);
}
if ($this->_gName == 'participant_status') {
// For Participant Status options, expose the 'filter' field to track which statuses are "Counted", and the Visibility field
- $element = $this->add('checkbox', 'filter', ts('Counted?'));
+ $this->add('checkbox', 'filter', ts('Counted?'));
$this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
}
if ($this->_gName == 'participant_role') {
@@ -339,7 +343,7 @@ public function buildQuickForm() {
$this->add('checkbox', 'filter', ts('Counted?'));
}
- $this->addFormRule(array('CRM_Admin_Form_Options', 'formRule'), $this);
+ $this->addFormRule(['CRM_Admin_Form_Options', 'formRule'], $this);
}
/**
@@ -354,18 +358,16 @@ public function buildQuickForm() {
*
* @return array
* array of errors / empty array.
+ * @throws \CRM_Core_Exception
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($self->_gName == 'case_status' && empty($fields['grouping'])) {
$errors['grouping'] = ts('Status class is a required field');
}
- if (in_array($self->_gName, array(
- 'email_greeting',
- 'postal_greeting',
- 'addressee',
- )) && empty($self->_defaultValues['is_reserved'])
+ if (in_array($self->_gName, ['email_greeting', 'postal_greeting', 'addressee'])
+ && empty($self->_defaultValues['is_reserved'])
) {
$label = $fields['label'];
$condition = " AND v.label = '{$label}' ";
@@ -396,7 +398,7 @@ public static function formRule($fields, $files, $self) {
$dataType = self::getOptionGroupDataType($self->_gName);
if ($dataType && $self->_gName !== 'activity_type') {
$validate = CRM_Utils_Type::validate($fields['value'], $dataType, FALSE);
- if (!$validate) {
+ if ($validate === FALSE) {
CRM_Core_Session::setStatus(
ts('Data Type of the value field for this option value does not match ' . $dataType),
ts('Value field Data Type mismatch'));
@@ -424,39 +426,38 @@ public static function getOptionGroupDataType($optionGroupName) {
*/
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $fieldValues = array('option_group_id' => $this->_gid);
- $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
+ $fieldValues = ['option_group_id' => $this->_gid];
+ CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
if (CRM_Core_BAO_OptionValue::del($this->_id)) {
if ($this->_gName == 'phone_type') {
CRM_Core_BAO_Phone::setOptionToNull(CRM_Utils_Array::value('value', $this->_defaultValues));
}
- CRM_Core_Session::setStatus(ts('Selected %1 type has been deleted.', array(1 => $this->_gLabel)), ts('Record Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts('Selected %1 type has been deleted.', [1 => $this->_gLabel]), ts('Record Deleted'), 'success');
}
else {
- CRM_Core_Session::setStatus(ts('Selected %1 type has not been deleted.', array(1 => $this->_gLabel)), ts('Sorry'), 'error');
+ CRM_Core_Session::setStatus(ts('Selected %1 type has not been deleted.', [1 => $this->_gLabel]), ts('Sorry'), 'error');
CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $fieldValues);
}
}
else {
- $ids = array();
$params = $this->exportValues();
// allow multiple defaults within group.
- $allowMultiDefaults = array('email_greeting', 'postal_greeting', 'addressee', 'from_email_address');
+ $allowMultiDefaults = ['email_greeting', 'postal_greeting', 'addressee', 'from_email_address'];
if (in_array($this->_gName, $allowMultiDefaults)) {
if ($this->_gName == 'from_email_address') {
- $params['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
+ $params['reset_default_for'] = ['domain_id' => CRM_Core_Config::domainID()];
}
elseif ($filter = CRM_Utils_Array::value('contactOptions', $params)) {
$params['filter'] = $filter;
- $params['reset_default_for'] = array('filter' => "0, " . $params['filter']);
+ $params['reset_default_for'] = ['filter' => "0, " . $params['filter']];
}
- //make sure we should has to have space, CRM-6977
+ //make sure we only have a single space, CRM-6977 and dev/mail/15
if ($this->_gName == 'from_email_address') {
- $params['label'] = str_replace('"<', '" <', $params['label']);
+ $params['label'] = $this->sanitizeFromEmailAddress($params['label']);
}
}
@@ -474,28 +475,20 @@ public function postProcess() {
$params['color'] = 'null';
}
- $groupParams = array('name' => ($this->_gName));
- $optionValue = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $this->_action, $this->_id);
-
- // CRM-11516
- if (!empty($params['financial_account_id'])) {
- $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
- $params = array(
- 'entity_table' => 'civicrm_option_value',
- 'entity_id' => $optionValue->id,
- 'account_relationship' => $relationTypeId,
- 'financial_account_id' => $params['financial_account_id'],
- );
- CRM_Financial_BAO_FinancialTypeAccount::add($params);
- }
+ $optionValue = CRM_Core_OptionValue::addOptionValue($params, $this->_gName, $this->_action, $this->_id);
- CRM_Core_Session::setStatus(ts('The %1 \'%2\' has been saved.', array(
- 1 => $this->_gLabel,
- 2 => $optionValue->label,
- )), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The %1 \'%2\' has been saved.', [
+ 1 => $this->_gLabel,
+ 2 => $optionValue->label,
+ ]), ts('Saved'), 'success');
$this->ajaxResponse['optionValue'] = $optionValue->toArray();
}
}
+ public function sanitizeFromEmailAddress($email) {
+ preg_match("/^\"(.*)\" *<([^@>]*@[^@>]*)>$/", $email, $parts);
+ return "\"{$parts[1]}\" <$parts[2]>";
+ }
+
}
diff --git a/CRM/Admin/Form/ParticipantStatusType.php b/CRM/Admin/Form/ParticipantStatusType.php
index e55c74827122..fcaac917b1af 100644
--- a/CRM/Admin/Form/ParticipantStatusType.php
+++ b/CRM/Admin/Form/ParticipantStatusType.php
@@ -1,9 +1,9 @@
add('text', 'label', ts('Label'), $attributes['label'], TRUE);
- $this->addSelect('class', array('required' => TRUE));
+ $this->addSelect('class', ['required' => TRUE]);
$this->add('checkbox', 'is_active', ts('Active?'));
$this->add('checkbox', 'is_counted', ts('Counted?'));
- $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
+ $this->add('number', 'weight', ts('Order'), $attributes['weight'], TRUE);
- $this->addSelect('visibility_id', array('label' => ts('Visibility'), 'required' => TRUE));
+ $this->addSelect('visibility_id', ['label' => ts('Visibility'), 'required' => TRUE]);
$this->assign('id', $this->_id);
}
@@ -83,7 +83,7 @@ public function setDefaultValues() {
}
$this->_isReserved = CRM_Utils_Array::value('is_reserved', $defaults);
if ($this->_isReserved) {
- $this->freeze(array('name', 'class', 'is_active'));
+ $this->freeze(['name', 'class', 'is_active']);
}
return $defaults;
}
@@ -101,7 +101,7 @@ public function postProcess() {
$formValues = $this->controller->exportValues($this->_name);
- $params = array(
+ $params = [
'name' => CRM_Utils_Array::value('name', $formValues),
'label' => CRM_Utils_Array::value('label', $formValues),
'class' => CRM_Utils_Array::value('class', $formValues),
@@ -109,7 +109,7 @@ public function postProcess() {
'is_counted' => CRM_Utils_Array::value('is_counted', $formValues, FALSE),
'weight' => CRM_Utils_Array::value('weight', $formValues),
'visibility_id' => CRM_Utils_Array::value('visibility_id', $formValues),
- );
+ ];
// make sure a malicious POST does not change these on reserved statuses
if ($this->_isReserved) {
diff --git a/CRM/Admin/Form/PaymentProcessor.php b/CRM/Admin/Form/PaymentProcessor.php
index 64fd697ea88a..d8b32939550b 100644
--- a/CRM/Admin/Form/PaymentProcessor.php
+++ b/CRM/Admin/Form/PaymentProcessor.php
@@ -1,9 +1,9 @@
_id) {
- $this->_ppType = CRM_Utils_Request::retrieve('pp', 'String', $this, FALSE, NULL);
- if (!$this->_ppType) {
- $this->_ppType = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor',
+ $this->_paymentProcessorType = CRM_Utils_Request::retrieve('pp', 'String', $this, FALSE, NULL);
+ if (!$this->_paymentProcessorType) {
+ $this->_paymentProcessorType = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor',
$this->_id,
'payment_processor_type_id'
);
}
- $this->set('pp', $this->_ppType);
+ $this->set('pp', $this->_paymentProcessorType);
}
else {
- $this->_ppType = CRM_Utils_Request::retrieve('pp', 'String', $this, TRUE, NULL);
+ $this->_paymentProcessorType = CRM_Utils_Request::retrieve('pp', 'String', $this, TRUE, NULL);
}
- $this->assign('ppType', $this->_ppType);
+ $this->assign('ppType', $this->_paymentProcessorType);
$ppTypeName = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
- $this->_ppType,
+ $this->_paymentProcessorType,
'name'
);
$this->assign('ppTypeName', $ppTypeName);
- $this->_ppDAO = new CRM_Financial_DAO_PaymentProcessorType();
- $this->_ppDAO->id = $this->_ppType;
+ $this->_paymentProcessorDAO = new CRM_Financial_DAO_PaymentProcessorType();
+ $this->_paymentProcessorDAO->id = $this->_paymentProcessorType;
- $this->_ppDAO->find(TRUE);
+ $this->_paymentProcessorDAO->find(TRUE);
if ($this->_id) {
$refreshURL = CRM_Utils_System::url('civicrm/admin/paymentProcessor',
@@ -101,60 +107,61 @@ public function preProcess() {
$refreshURL .= "&civicrmDestination=$destination";
}
+ $this->refreshURL = $refreshURL;
$this->assign('refreshURL', $refreshURL);
- $this->assign('is_recur', $this->_ppDAO->is_recur);
+ $this->assign('is_recur', $this->_paymentProcessorDAO->is_recur);
- $this->_fields = array(
- array(
+ $this->_fields = [
+ [
'name' => 'user_name',
- 'label' => $this->_ppDAO->user_name_label,
- ),
- array(
+ 'label' => $this->_paymentProcessorDAO->user_name_label,
+ ],
+ [
'name' => 'password',
- 'label' => $this->_ppDAO->password_label,
- ),
- array(
+ 'label' => $this->_paymentProcessorDAO->password_label,
+ ],
+ [
'name' => 'signature',
- 'label' => $this->_ppDAO->signature_label,
- ),
- array(
+ 'label' => $this->_paymentProcessorDAO->signature_label,
+ ],
+ [
'name' => 'subject',
- 'label' => $this->_ppDAO->subject_label,
- ),
- array(
+ 'label' => $this->_paymentProcessorDAO->subject_label,
+ ],
+ [
'name' => 'url_site',
'label' => ts('Site URL'),
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- );
+ ],
+ ];
- if ($this->_ppDAO->is_recur) {
- $this->_fields[] = array(
+ if ($this->_paymentProcessorDAO->is_recur) {
+ $this->_fields[] = [
'name' => 'url_recur',
'label' => ts('Recurring Payments URL'),
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- );
+ ];
}
- if (!empty($this->_ppDAO->url_button_default)) {
- $this->_fields[] = array(
+ if (!empty($this->_paymentProcessorDAO->url_button_default)) {
+ $this->_fields[] = [
'name' => 'url_button',
'label' => ts('Button URL'),
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- );
+ ];
}
- if (!empty($this->_ppDAO->url_api_default)) {
- $this->_fields[] = array(
+ if (!empty($this->_paymentProcessorDAO->url_api_default)) {
+ $this->_fields[] = [
'name' => 'url_api',
'label' => ts('API URL'),
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- );
+ ];
}
}
@@ -176,20 +183,23 @@ public function buildQuickForm($check = FALSE) {
$attributes['name'], TRUE
);
- $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array(
- 'CRM_Financial_DAO_PaymentProcessor',
- $this->_id,
- 'name',
- CRM_Core_Config::domainID(),
- ));
+ $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [
+ 'CRM_Financial_DAO_PaymentProcessor',
+ $this->_id,
+ 'name',
+ CRM_Core_Config::domainID(),
+ ]);
$this->add('text', 'description', ts('Description'),
$attributes['description']
);
- $types = CRM_Core_PseudoConstant::paymentProcessorType();
- $this->add('select', 'payment_processor_type_id', ts('Payment Processor Type'), $types, TRUE,
- array('onchange' => "reload(true)")
+ $this->add('select',
+ 'payment_processor_type_id',
+ ts('Payment Processor Type'),
+ CRM_Financial_BAO_PaymentProcessor::buildOptions('payment_processor_type_id'),
+ TRUE,
+ ['onchange' => "reload(true)"]
);
// Financial Account of account type asset CRM-11515
@@ -199,15 +209,15 @@ public function buildQuickForm($check = FALSE) {
$this->assign('financialAccount', $fcount);
}
$this->add('select', 'financial_account_id', ts('Financial Account'),
- array('' => ts('- select -')) + $financialAccount,
+ ['' => ts('- select -')] + $financialAccount,
TRUE
);
$this->addSelect('payment_instrument_id',
- array(
+ [
'entity' => 'contribution',
'label' => ts('Payment Method'),
'placeholder' => NULL,
- )
+ ]
);
// is this processor active ?
@@ -221,12 +231,12 @@ public function buildQuickForm($check = FALSE) {
continue;
}
- $this->addField($field['name'], array('label' => $field['label']));
+ $this->addField($field['name'], ['label' => $field['label']]);
- $fieldSpec = civicrm_api3($this->getDefaultEntity(), 'getfield', array(
+ $fieldSpec = civicrm_api3($this->getDefaultEntity(), 'getfield', [
'name' => $field['name'],
'action' => 'create',
- ));
+ ]);
$this->add($fieldSpec['values']['html']['type'], "test_{$field['name']}",
$field['label'], $attributes[$field['name']]
);
@@ -236,7 +246,7 @@ public function buildQuickForm($check = FALSE) {
}
}
- $this->addFormRule(array('CRM_Admin_Form_PaymentProcessor', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_PaymentProcessor', 'formRule']);
}
/**
@@ -249,7 +259,7 @@ public static function formRule($fields) {
// make sure that at least one of live or test is present
// and we have at least name and url_site
// would be good to make this processor specific
- $errors = array();
+ $errors = [];
if (!(self::checkSection($fields, $errors) ||
self::checkSection($fields, $errors, 'test')
@@ -273,7 +283,7 @@ public static function formRule($fields) {
* @return bool
*/
public static function checkSection(&$fields, &$errors, $section = NULL) {
- $names = array('user_name');
+ $names = ['user_name'];
$present = FALSE;
$allPresent = TRUE;
@@ -301,23 +311,24 @@ public static function checkSection(&$fields, &$errors, $section = NULL) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!$this->_id) {
$defaults['is_active'] = $defaults['is_default'] = 1;
- $defaults['url_site'] = $this->_ppDAO->url_site_default;
- $defaults['url_api'] = $this->_ppDAO->url_api_default;
- $defaults['url_recur'] = $this->_ppDAO->url_recur_default;
- $defaults['url_button'] = $this->_ppDAO->url_button_default;
- $defaults['test_url_site'] = $this->_ppDAO->url_site_test_default;
- $defaults['test_url_api'] = $this->_ppDAO->url_api_test_default;
- $defaults['test_url_recur'] = $this->_ppDAO->url_recur_test_default;
- $defaults['test_url_button'] = $this->_ppDAO->url_button_test_default;
- $defaults['payment_instrument_id'] = $this->_ppDAO->payment_instrument_id;
+ $defaults['url_site'] = $this->_paymentProcessorDAO->url_site_default;
+ $defaults['url_api'] = $this->_paymentProcessorDAO->url_api_default;
+ $defaults['url_recur'] = $this->_paymentProcessorDAO->url_recur_default;
+ $defaults['url_button'] = $this->_paymentProcessorDAO->url_button_default;
+ $defaults['test_url_site'] = $this->_paymentProcessorDAO->url_site_test_default;
+ $defaults['test_url_api'] = $this->_paymentProcessorDAO->url_api_test_default;
+ $defaults['test_url_recur'] = $this->_paymentProcessorDAO->url_recur_test_default;
+ $defaults['test_url_button'] = $this->_paymentProcessorDAO->url_button_test_default;
+ $defaults['payment_instrument_id'] = $this->_paymentProcessorDAO->payment_instrument_id;
// When user changes payment processor type, it is passed in via $this->_ppType so update defaults array.
- if ($this->_ppType) {
- $defaults['payment_processor_type_id'] = $this->_ppType;
+ if ($this->_paymentProcessorType) {
+ $defaults['payment_processor_type_id'] = $this->_paymentProcessorType;
}
+ $defaults['financial_account_id'] = CRM_Financial_BAO_PaymentProcessor::getDefaultFinancialAccountID();
return $defaults;
}
$domainID = CRM_Core_Config::domainID();
@@ -330,15 +341,21 @@ public function setDefaultValues() {
}
CRM_Core_DAO::storeValues($dao, $defaults);
- // When user changes payment processor type, it is passed in via $this->_ppType so update defaults array.
- if ($this->_ppType) {
- $defaults['payment_processor_type_id'] = $this->_ppType;
+ // If payment processor ID does not exist, $paymentProcessorName will be FALSE
+ $paymentProcessorName = CRM_Core_PseudoConstant::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessorType);
+ if ($this->_paymentProcessorType && $paymentProcessorName) {
+ // When user changes payment processor type, it is passed in via $this->_ppType so update defaults array.
+ $defaults['payment_processor_type_id'] = $this->_paymentProcessorType;
}
+ else {
+ CRM_Core_Session::setStatus('Payment Processor Type (ID=' . $this->_paymentProcessorType . ') not found. Did you disable the payment processor extension?', 'Missing Payment Processor', 'alert');
+ }
+
$cards = json_decode(CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor',
$this->_id,
'accepted_credit_cards'
), TRUE);
- $acceptedCards = array();
+ $acceptedCards = [];
if (!empty($cards)) {
foreach ($cards as $card => $val) {
$acceptedCards[$card] = 1;
@@ -383,9 +400,26 @@ public function postProcess() {
CRM_Core_DAO::executeQuery($query);
}
+ if ($this->_paymentProcessorType !== $values['payment_processor_type_id']) {
+ // If we changed the payment processor type, need to update the object as well
+ $this->_paymentProcessorType = $values['payment_processor_type_id'];
+ $this->_paymentProcessorDAO = new CRM_Financial_DAO_PaymentProcessorType();
+ $this->_paymentProcessorDAO->id = $values['payment_processor_type_id'];
+ $this->_paymentProcessorDAO->find(TRUE);
+ }
$this->updatePaymentProcessor($values, $domainID, FALSE);
$this->updatePaymentProcessor($values, $domainID, TRUE);
- CRM_Core_Session::setStatus(ts('Payment processor %1 has been saved.', array(1 => "{$values['name']}")), ts('Saved'), 'success');
+
+ $processor = civicrm_api3('payment_processor', 'getsingle', ['name' => $values['name'], 'is_test' => 0]);
+ $errors = Civi\Payment\System::singleton()->checkProcessorConfig($processor);
+ if ($errors) {
+ CRM_Core_Session::setStatus($errors, 'Payment processor configuration invalid', 'error');
+ Civi::log()->error('Payment processor configuration invalid: ' . $errors);
+ CRM_Core_Session::singleton()->pushUserContext($this->refreshURL);
+ }
+ else {
+ CRM_Core_Session::setStatus(ts('Payment processor %1 has been saved.', [1 => "{$values['name']}"]), ts('Saved'), 'success');
+ }
}
/**
@@ -397,12 +431,12 @@ public function postProcess() {
*/
public function updatePaymentProcessor(&$values, $domainID, $test) {
if ($test) {
- foreach (array('user_name', 'password', 'signature', 'url_site', 'url_recur', 'url_api', 'url_button', 'subject') as $field) {
+ foreach (['user_name', 'password', 'signature', 'url_site', 'url_recur', 'url_api', 'url_button', 'subject'] as $field) {
$values[$field] = empty($values["test_{$field}"]) ? CRM_Utils_Array::value($field, $values) : $values["test_{$field}"];
}
}
if (!empty($values['accept_credit_cards'])) {
- $creditCards = array();
+ $creditCards = [];
$accptedCards = array_keys($values['accept_credit_cards']);
$creditCardTypes = CRM_Contribute_PseudoConstant::creditCard();
foreach ($creditCardTypes as $type => $val) {
@@ -415,20 +449,20 @@ public function updatePaymentProcessor(&$values, $domainID, $test) {
else {
$creditCards = "NULL";
}
- $params = array_merge(array(
+ $params = array_merge([
'id' => $test ? $this->_testID : $this->_id,
'domain_id' => $domainID,
'is_test' => $test,
'is_active' => 0,
'is_default' => 0,
- 'is_recur' => $this->_ppDAO->is_recur,
- 'billing_mode' => $this->_ppDAO->billing_mode,
- 'class_name' => $this->_ppDAO->class_name,
- 'payment_type' => $this->_ppDAO->payment_type,
- 'payment_instrument_id' => $this->_ppDAO->payment_instrument_id,
+ 'is_recur' => $this->_paymentProcessorDAO->is_recur,
+ 'billing_mode' => $this->_paymentProcessorDAO->billing_mode,
+ 'class_name' => $this->_paymentProcessorDAO->class_name,
+ 'payment_type' => $this->_paymentProcessorDAO->payment_type,
+ 'payment_instrument_id' => $this->_paymentProcessorDAO->payment_instrument_id,
'financial_account_id' => $values['financial_account_id'],
'accepted_credit_cards' => $creditCards,
- ), $values);
+ ], $values);
civicrm_api3('PaymentProcessor', 'create', $params);
}
diff --git a/CRM/Admin/Form/PaymentProcessorType.php b/CRM/Admin/Form/PaymentProcessorType.php
index 9edb6eb7f51b..29c2e5fde6cc 100644
--- a/CRM/Admin/Form/PaymentProcessorType.php
+++ b/CRM/Admin/Form/PaymentProcessorType.php
@@ -1,9 +1,9 @@
_fields = array(
- array(
+ $this->_fields = [
+ [
'name' => 'name',
'label' => ts('Name'),
'required' => TRUE,
- ),
- array(
+ ],
+ [
'name' => 'title',
'label' => ts('Title'),
'required' => TRUE,
- ),
- array(
+ ],
+ [
'name' => 'billing_mode',
'label' => ts('Billing Mode'),
'required' => TRUE,
'rule' => 'positiveInteger',
'msg' => ts('Enter a positive integer'),
- ),
- array(
+ ],
+ [
'name' => 'description',
'label' => ts('Description'),
- ),
- array(
+ ],
+ [
'name' => 'user_name_label',
'label' => ts('User Name Label'),
- ),
- array(
+ ],
+ [
'name' => 'password_label',
'label' => ts('Password Label'),
- ),
- array(
+ ],
+ [
'name' => 'signature_label',
'label' => ts('Signature Label'),
- ),
- array(
+ ],
+ [
'name' => 'subject_label',
'label' => ts('Subject Label'),
- ),
- array(
+ ],
+ [
'name' => 'class_name',
'label' => ts('PHP class name'),
'required' => TRUE,
- ),
- array(
+ ],
+ [
'name' => 'url_site_default',
'label' => ts('Live Site URL'),
'required' => TRUE,
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_api_default',
'label' => ts('Live API URL'),
'required' => FALSE,
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_recur_default',
'label' => ts('Live Recurring Payments URL'),
'required' => TRUE,
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_button_default',
'label' => ts('Live Button URL'),
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_site_test_default',
'label' => ts('Test Site URL'),
'required' => TRUE,
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_api_test_default',
'label' => ts('Test API URL'),
'required' => FALSE,
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_recur_test_default',
'label' => ts('Test Recurring Payments URL'),
'required' => TRUE,
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- array(
+ ],
+ [
'name' => 'url_button_test_default',
'label' => ts('Test Button URL'),
'rule' => 'url',
'msg' => ts('Enter a valid URL'),
- ),
- );
+ ],
+ ];
}
/**
@@ -176,7 +176,7 @@ public function buildQuickForm($check = FALSE) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!$this->_id) {
$defaults['is_active'] = $defaults['is_default'] = 1;
@@ -203,7 +203,7 @@ public function setDefaultValues() {
* Process the form submission.
*/
public function postProcess() {
- CRM_Utils_System::flushCache('CRM_Financial_DAO_PaymentProcessorType');
+ CRM_Utils_System::flushCache();
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Financial_BAO_PaymentProcessorType::del($this->_id);
diff --git a/CRM/Admin/Form/PdfFormats.php b/CRM/Admin/Form/PdfFormats.php
index c984a4e4dc33..ea8e7c40c91c 100644
--- a/CRM/Admin/Form/PdfFormats.php
+++ b/CRM/Admin/Form/PdfFormats.php
@@ -1,7 +1,7 @@
add('text', 'name', ts('Name'), $attributes['name'], TRUE);
- $this->add('text', 'description', ts('Description'), array('size' => CRM_Utils_Type::HUGE));
+ $this->add('text', 'description', ts('Description'), ['size' => CRM_Utils_Type::HUGE]);
$this->add('checkbox', 'is_default', ts('Is this PDF Page Format the default?'));
$this->add('select', 'paper_size', ts('Paper Size'),
- array(
+ [
0 => ts('- default -'),
- ) + CRM_Core_BAO_PaperSize::getList(TRUE), FALSE,
- array('onChange' => "selectPaper( this.value );")
+ ] + CRM_Core_BAO_PaperSize::getList(TRUE), FALSE,
+ ['onChange' => "selectPaper( this.value );"]
);
$this->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
$this->add('select', 'orientation', ts('Orientation'), CRM_Core_BAO_PdfFormat::getPageOrientations(), FALSE,
- array('onChange' => "updatePaperDimensions();")
+ ['onChange' => "updatePaperDimensions();"]
);
$this->add('select', 'metric', ts('Unit of Measure'), CRM_Core_BAO_PdfFormat::getUnits(), FALSE,
- array('onChange' => "selectMetric( this.value );")
+ ['onChange' => "selectMetric( this.value );"]
);
- $this->add('text', 'margin_left', ts('Left Margin'), array('size' => 8, 'maxlength' => 8), TRUE);
- $this->add('text', 'margin_right', ts('Right Margin'), array('size' => 8, 'maxlength' => 8), TRUE);
- $this->add('text', 'margin_top', ts('Top Margin'), array('size' => 8, 'maxlength' => 8), TRUE);
- $this->add('text', 'margin_bottom', ts('Bottom Margin'), array('size' => 8, 'maxlength' => 8), TRUE);
- $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_BAO_PdfFormat', 'weight'), TRUE);
+ $this->add('text', 'margin_left', ts('Left Margin'), ['size' => 8, 'maxlength' => 8], TRUE);
+ $this->add('text', 'margin_right', ts('Right Margin'), ['size' => 8, 'maxlength' => 8], TRUE);
+ $this->add('text', 'margin_top', ts('Top Margin'), ['size' => 8, 'maxlength' => 8], TRUE);
+ $this->add('text', 'margin_bottom', ts('Bottom Margin'), ['size' => 8, 'maxlength' => 8], TRUE);
+ $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_BAO_PdfFormat', 'weight'), TRUE);
- $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array(
- 'CRM_Core_BAO_PdfFormat',
- $this->_id,
- ));
+ $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [
+ 'CRM_Core_BAO_PdfFormat',
+ $this->_id,
+ ]);
$this->addRule('margin_left', ts('Margin must be numeric'), 'numeric');
$this->addRule('margin_right', ts('Margin must be numeric'), 'numeric');
$this->addRule('margin_top', ts('Margin must be numeric'), 'numeric');
@@ -119,9 +120,9 @@ public function postProcess() {
$bao = new CRM_Core_BAO_PdfFormat();
$bao->savePdfFormat($values, $this->_id);
- $status = ts('Your new PDF Page Format titled %1 has been saved.', array(1 => $values['name']), ts('Saved'), 'success');
+ $status = ts('Your new PDF Page Format titled %1 has been saved.', [1 => $values['name']], ts('Saved'), 'success');
if ($this->_action & CRM_Core_Action::UPDATE) {
- $status = ts('Your PDF Page Format titled %1 has been updated.', array(1 => $values['name']), ts('Saved'), 'success');
+ $status = ts('Your PDF Page Format titled %1 has been updated.', [1 => $values['name']], ts('Saved'), 'success');
}
CRM_Core_Session::setStatus($status);
}
diff --git a/CRM/Admin/Form/Persistent.php b/CRM/Admin/Form/Persistent.php
index 1f93a2c724ae..e62d3313bc0b 100644
--- a/CRM/Admin/Form/Persistent.php
+++ b/CRM/Admin/Form/Persistent.php
@@ -1,9 +1,9 @@
_indexID && ($this->_action & (CRM_Core_Action::UPDATE))) {
- $params = array('id' => $this->_indexID);
+ $params = ['id' => $this->_indexID];
CRM_Core_BAO_Persistent::retrieve($params, $defaults);
if (CRM_Utils_Array::value('is_config', $defaults) == 1) {
$defaults['data'] = implode(',', $defaults['data']);
@@ -71,23 +71,22 @@ public function setDefaultValues() {
public function buildQuickForm() {
$this->add('text', 'context', ts('Context:'), NULL, TRUE);
$this->add('text', 'name', ts('Name:'), NULL, TRUE);
- $this->add('textarea', 'data', ts('Data:'), array('rows' => 4, 'cols' => 50), TRUE);
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->add('textarea', 'data', ts('Data:'), ['rows' => 4, 'cols' => 50], TRUE);
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
public function postProcess() {
- $params = $ids = array();
+ $params = $ids = [];
$params = $this->controller->exportValues($this->_name);
$params['is_config'] = $this->_config;
diff --git a/CRM/Admin/Form/Preferences.php b/CRM/Admin/Form/Preferences.php
index ab6519517da3..55578d404a53 100644
--- a/CRM/Admin/Form/Preferences.php
+++ b/CRM/Admin/Form/Preferences.php
@@ -1,9 +1,9 @@
_config->contact_id = $this->_contactID;
}
+ $this->addFieldsDefinedInSettingsMetadata();
$settings = Civi::settings();
+ // @todo replace this by defining all in settings.
foreach ($this->_varNames as $groupName => $settingNames) {
+ CRM_Core_Error::deprecatedFunctionWarning('deprecated use of preferences form. This will be removed from core soon');
foreach ($settingNames as $settingName => $options) {
$this->_config->$settingName = $settings->get($settingName);
}
@@ -98,23 +104,28 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $this->_defaults = [];
+ $this->setDefaultsForMetadataDefinedFields();
foreach ($this->_varNames as $groupName => $settings) {
+ CRM_Core_Error::deprecatedFunctionWarning('deprecated use of preferences form. This will be removed from core soon');
foreach ($settings as $settingName => $settingDetails) {
- $defaults[$settingName] = isset($this->_config->$settingName) ? $this->_config->$settingName : CRM_Utils_Array::value('default', $settingDetails, NULL);
+ $this->_defaults[$settingName] = isset($this->_config->$settingName) ? $this->_config->$settingName : CRM_Utils_Array::value('default', $settingDetails, NULL);
}
}
- return $defaults;
+ return $this->_defaults;
}
/**
+ * @todo deprecate in favour of setting using metadata.
+ *
* @param $defaults
*/
public function cbsDefaultValues(&$defaults) {
foreach ($this->_varNames as $groupName => $groupValues) {
+ CRM_Core_Error::deprecatedFunctionWarning('deprecated use of preferences form. This will be removed from core soon');
foreach ($groupValues as $settingName => $fieldValue) {
if ($fieldValue['html_type'] == 'checkboxes') {
if (isset($this->_config->$settingName) &&
@@ -124,7 +135,7 @@ public function cbsDefaultValues(&$defaults) {
substr($this->_config->$settingName, 1, -1)
);
if (!empty($value)) {
- $defaults[$settingName] = array();
+ $defaults[$settingName] = [];
foreach ($value as $n => $v) {
$defaults[$settingName][$v] = 1;
}
@@ -142,10 +153,11 @@ public function buildQuickForm() {
parent::buildQuickForm();
if (!empty($this->_varNames)) {
+ CRM_Core_Error::deprecatedFunctionWarning('deprecated use of preferences form. This will be removed from core soon');
foreach ($this->_varNames as $groupName => $groupValues) {
$formName = CRM_Utils_String::titleToVar($groupName);
$this->assign('formName', $formName);
- $fields = array();
+ $fields = [];
foreach ($groupValues as $fieldName => $fieldValue) {
$fields[$fieldName] = $fieldValue;
@@ -154,10 +166,10 @@ public function buildQuickForm() {
$this->addElement('text',
$fieldName,
$fieldValue['title'],
- array(
+ [
'maxlength' => 64,
'size' => 32,
- )
+ ]
);
break;
@@ -175,12 +187,12 @@ public function buildQuickForm() {
break;
case 'YesNo':
- $this->addRadio($fieldName, $fieldValue['title'], array(0 => 'No', 1 => 'Yes'), NULL, ' ');
+ $this->addRadio($fieldName, $fieldValue['title'], [0 => 'No', 1 => 'Yes'], NULL, ' ');
break;
case 'checkboxes':
$options = array_flip(CRM_Core_OptionGroup::values($fieldName, FALSE, FALSE, TRUE));
- $newOptions = array();
+ $newOptions = [];
foreach ($options as $key => $val) {
$newOptions[$key] = $val;
}
@@ -188,7 +200,7 @@ public function buildQuickForm() {
$fieldValue['title'],
$newOptions,
NULL, NULL, NULL, NULL,
- array(' ', ' ', ' ')
+ [' ', ' ', ' ']
);
break;
@@ -196,7 +208,8 @@ public function buildQuickForm() {
$this->addElement('select',
$fieldName,
$fieldValue['title'],
- $fieldValue['option_values']
+ $fieldValue['option_values'],
+ CRM_Utils_Array::value('attributes', $fieldValue)
);
break;
@@ -205,7 +218,7 @@ public function buildQuickForm() {
break;
case 'entity_reference':
- $this->addEntityRef($fieldName, $fieldValue['title'], CRM_Utils_Array::value('options', $fieldValue, array()));
+ $this->addEntityRef($fieldName, $fieldValue['title'], CRM_Utils_Array::value('options', $fieldValue, []));
}
}
@@ -214,18 +227,17 @@ public function buildQuickForm() {
}
}
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
if ($this->_action == CRM_Core_Action::VIEW) {
$this->freeze();
@@ -250,6 +262,14 @@ public function postProcess() {
* Process the form submission.
*/
public function postProcessCommon() {
+ try {
+ $this->saveMetadataDefinedSettings($this->_params);
+ $this->filterParamsSetByMetadata($this->_params);
+ }
+ catch (CiviCRM_API3_Exception $e) {
+ CRM_Core_Session::setStatus($e->getMessage(), ts('Save Failed'), 'error');
+ }
+
foreach ($this->_varNames as $groupName => $groupValues) {
foreach ($groupValues as $settingName => $fieldValue) {
switch ($fieldValue['html_type']) {
@@ -282,7 +302,7 @@ public function postProcessCommon() {
$value = CRM_Utils_Array::value($settingName, $this->_params);
if ($value) {
$value = trim($value);
- $value = str_replace(array("\r\n", "\r"), "\n", $value);
+ $value = str_replace(["\r\n", "\r"], "\n", $value);
}
$this->_config->$settingName = $value;
break;
diff --git a/CRM/Admin/Form/Preferences/Address.php b/CRM/Admin/Form/Preferences/Address.php
index b00f7b673953..059b5bc6ff5f 100644
--- a/CRM/Admin/Form/Preferences/Address.php
+++ b/CRM/Admin/Form/Preferences/Address.php
@@ -1,9 +1,9 @@
'- select -',
- ) + CRM_Core_SelectValues::addressProvider();
-
- $this->_varNames = array(
- CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME => array(
- 'address_options' => array(
- 'html_type' => 'checkboxes',
- 'title' => ts('Address Fields'),
- 'weight' => 1,
- ),
- 'address_format' => array(
- 'html_type' => 'textarea',
- 'title' => ts('Display Format'),
- 'description' => NULL,
- 'weight' => 2,
- ),
- 'mailing_format' => array(
- 'html_type' => 'textarea',
- 'title' => ts('Mailing Label Format'),
- 'description' => NULL,
- 'weight' => 3,
- ),
- 'hideCountryMailingLabels' => array(
- 'html_type' => 'YesNo',
- 'title' => ts('Hide Country in Mailing Labels when same as domain country'),
- 'weight' => 4,
- ),
- ),
- CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME => array(
- 'address_standardization_provider' => array(
- 'html_type' => 'select',
- 'title' => ts('Provider'),
- 'option_values' => $addrProviders,
- 'weight' => 5,
- ),
- 'address_standardization_userid' => array(
- 'html_type' => 'text',
- 'title' => ts('User ID'),
- 'description' => NULL,
- 'weight' => 6,
- ),
- 'address_standardization_url' => array(
- 'html_type' => 'text',
- 'title' => ts('Web Service URL'),
- 'description' => NULL,
- 'weight' => 7,
- ),
- ),
- );
-
- parent::preProcess();
- }
-
- /**
- * @return array
- */
- public function setDefaultValues() {
- $defaults = array();
- $defaults['address_standardization_provider'] = $this->_config->address_standardization_provider;
- $defaults['address_standardization_userid'] = $this->_config->address_standardization_userid;
- $defaults['address_standardization_url'] = $this->_config->address_standardization_url;
-
- $this->addressSequence = isset($newSequence) ? $newSequence : "";
-
- $defaults['address_format'] = $this->_config->address_format;
- $defaults['mailing_format'] = $this->_config->mailing_format;
- $defaults['hideCountryMailingLabels'] = $this->_config->hideCountryMailingLabels;
- parent::cbsDefaultValues($defaults);
-
- return $defaults;
- }
+ protected $_settings = [
+ 'address_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'address_format' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'mailing_format' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'hideCountryMailingLabels' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'address_standardization_provider' => CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME,
+ 'address_standardization_userid' => CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME,
+ 'address_standardization_url' => CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME,
+ ];
/**
* Build the form object.
@@ -120,7 +52,7 @@ public function setDefaultValues() {
public function buildQuickForm() {
$this->applyFilter('__ALL__', 'trim');
- $this->addFormRule(array('CRM_Admin_Form_Preferences_Address', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Preferences_Address', 'formRule']);
//get the tokens for Mailing Label field
$tokens = CRM_Core_SelectValues::contactTokens();
@@ -142,13 +74,9 @@ public static function formRule($fields) {
// make sure that there is a value for all of them
// if any of them are set
if ($p || $u || $w) {
- if (!CRM_Utils_System::checkPHPVersion(5, FALSE)) {
- $errors['_qf_default'] = ts('Address Standardization features require PHP version 5 or greater.');
- return $errors;
- }
if (!($p && $u && $w)) {
- $errors['_qf_default'] = ts('You must provide values for all three Address Standarization fields.');
+ $errors['_qf_default'] = ts('You must provide values for all three Address Standardization fields.');
return $errors;
}
}
@@ -165,27 +93,29 @@ public function postProcess() {
}
$this->_params = $this->controller->exportValues($this->_name);
+ $addressOptions = CRM_Core_OptionGroup::values('address_options', TRUE);
// check if county option has been set
- $options = CRM_Core_OptionGroup::values('address_options', FALSE, FALSE, TRUE);
- foreach ($options as $key => $title) {
- if ($title == ts('County')) {
- // check if the $key is present in $this->_params
- if (isset($this->_params['address_options']) &&
- !empty($this->_params['address_options'][$key])
- ) {
- // print a status message to the user if county table seems small
- $countyCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_county");
- if ($countyCount < 10) {
- CRM_Core_Session::setStatus(ts('You have enabled the County option. Please ensure you populate the county table in your CiviCRM Database. You can find extensions to populate counties in the CiviCRM Extensions Directory.', array(1 => 'href="' . CRM_Utils_System::url('civicrm/admin/extensions', array('reset' => 1), TRUE, 'extensions-addnew') . '"')),
- ts('Populate counties'),
- "info"
- );
- }
- }
+ if (CRM_Utils_Array::value($addressOptions['County'], $this->_params['address_options'])) {
+ $countyCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_county");
+ if ($countyCount < 10) {
+ CRM_Core_Session::setStatus(ts('You have enabled the County option. Please ensure you populate the county table in your CiviCRM Database. You can find extensions to populate counties in the CiviCRM Extensions Directory.', [1 => 'href="' . CRM_Utils_System::url('civicrm/admin/extensions', ['reset' => 1], TRUE, 'extensions-addnew') . '"']),
+ ts('Populate counties'),
+ "info"
+ );
}
}
+ // check that locale supports address parsing
+ if (
+ CRM_Utils_Array::value($addressOptions['Street Address Parsing'], $this->_params['address_options']) &&
+ !CRM_Core_BAO_Address::isSupportedParsingLocale()
+ ) {
+ $config = CRM_Core_Config::singleton();
+ $locale = $config->lcMessages;
+ CRM_Core_Session::setStatus(ts('Default locale (%1) does not support street parsing. en_US locale will be used instead.', [1 => $locale]), ts('Unsupported Locale'), 'alert');
+ }
+
$this->postProcessCommon();
}
diff --git a/CRM/Admin/Form/Preferences/Campaign.php b/CRM/Admin/Form/Preferences/Campaign.php
index 7c628073d743..3e372da4c94f 100644
--- a/CRM/Admin/Form/Preferences/Campaign.php
+++ b/CRM/Admin/Form/Preferences/Campaign.php
@@ -1,9 +1,9 @@
_varNames = array(
- CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME => array(
- 'tag_unconfirmed' => array(
- 'html_type' => 'text',
- 'title' => ts('Tag for Unconfirmed Petition Signers'),
- 'weight' => 1,
- 'description' => ts('If set, new contacts that are created when signing a petition are assigned a tag of this name.'),
- ),
- 'petition_contacts' => array(
- 'html_type' => 'text',
- 'title' => ts('Petition Signers Group'),
- 'weight' => 2,
- 'description' => ts('All contacts that have signed a CiviCampaign petition will be added to this group. The group will be created if it does not exist (it is required for email verification).'),
- ),
- ),
- );
- parent::preProcess();
- }
+ protected $_settings = [
+ 'tag_unconfirmed' => CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME,
+ 'petition_contacts' => CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME,
+ ];
}
diff --git a/CRM/Admin/Form/Preferences/Contribute.php b/CRM/Admin/Form/Preferences/Contribute.php
index 9fb2377ccc66..7421754c7229 100644
--- a/CRM/Admin/Form/Preferences/Contribute.php
+++ b/CRM/Admin/Form/Preferences/Contribute.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
'update_contribution_on_membership_type_change' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
'acl_financial_type' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
@@ -43,130 +43,130 @@ class CRM_Admin_Form_Preferences_Contribute extends CRM_Admin_Form_Preferences {
'deferred_revenue_enabled' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
'default_invoice_page' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
'invoicing' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
- );
+ ];
/**
- * Process the form submission.
+ * Our standards for settings are to have a setting per value with defined metadata.
+ *
+ * Unfortunately the 'contribution_invoice_settings' has been added in non-compliance.
+ * We use this array to hack-handle.
+ *
+ * I think the best way forwards would be to covert to multiple individual settings.
+ *
+ * @var array
*/
- public function preProcess() {
- $config = CRM_Core_Config::singleton();
- CRM_Utils_System::setTitle(ts('CiviContribute Component Settings'));
- $this->_varNames = array(
- CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME => array(
- 'invoice_prefix' => array(
- 'html_type' => 'text',
- 'title' => ts('Invoice Prefix'),
- 'weight' => 1,
- 'description' => ts('Enter prefix to be display on PDF for invoice'),
- ),
- 'credit_notes_prefix' => array(
- 'html_type' => 'text',
- 'title' => ts('Credit Notes Prefix'),
- 'weight' => 2,
- 'description' => ts('Enter prefix to be display on PDF for credit notes.'),
- ),
- 'due_date' => array(
- 'html_type' => 'text',
- 'title' => ts('Due Date'),
- 'weight' => 3,
- ),
- 'due_date_period' => array(
- 'html_type' => 'select',
- 'title' => ts('For transmission'),
- 'weight' => 4,
- 'description' => ts('Select the interval for due date.'),
- 'option_values' => array(
- 'select' => ts('- select -'),
- 'days' => ts('Days'),
- 'months' => ts('Months'),
- 'years' => ts('Years'),
- ),
- ),
- 'notes' => array(
- 'html_type' => 'wysiwyg',
- 'title' => ts('Notes or Standard Terms'),
- 'weight' => 5,
- 'description' => ts('Enter note or message to be displayed on PDF invoice or credit notes '),
- 'attributes' => array('rows' => 2, 'cols' => 40),
- ),
- 'is_email_pdf' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Automatically email invoice when user purchases online'),
- 'weight' => 6,
- ),
- 'tax_term' => array(
- 'html_type' => 'text',
- 'title' => ts('Tax Term'),
- 'weight' => 7,
- ),
- 'tax_display_settings' => array(
- 'html_type' => 'select',
- 'title' => ts('Tax Display Settings'),
- 'weight' => 8,
- 'option_values' => array(
- 'Do_not_show' => ts('Do not show breakdown, only show total -i.e ' .
- $config->defaultCurrencySymbol . '120.00'),
- 'Inclusive' => ts('Show [tax term] inclusive price - i.e. ' .
- $config->defaultCurrencySymbol .
- '120.00 (includes [tax term] of ' .
- $config->defaultCurrencySymbol . '20.00)'),
- 'Exclusive' => ts('Show [tax term] exclusive price - i.e. ' .
- $config->defaultCurrencySymbol . '100.00 + ' .
- $config->defaultCurrencySymbol . '20.00 [tax term]'),
- ),
- ),
- ),
- );
- parent::preProcess();
- }
+ protected $invoiceSettings = [];
/**
* Build the form object.
*/
public function buildQuickForm() {
- $htmlFields = array();
- foreach ($this->_settings as $setting => $group) {
- $settingMetaData = civicrm_api3('setting', 'getfields', array('name' => $setting));
- $props = $settingMetaData['values'][$setting];
- if (isset($props['quick_form_type'])) {
- $add = 'add' . $props['quick_form_type'];
- if ($add == 'addElement') {
- if (in_array($props['html_type'], array('checkbox', 'textarea'))) {
- $this->add($props['html_type'],
- $setting,
- $props['title']
- );
- }
- else {
- if ($props['html_type'] == 'select') {
- $functionName = CRM_Utils_Array::value('name', CRM_Utils_Array::value('pseudoconstant', $props));
- if ($functionName) {
- $props['option_values'] = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::$functionName();
- }
- }
- $this->$add(
- $props['html_type'],
- $setting,
- ts($props['title']),
- CRM_Utils_Array::value($props['html_type'] == 'select' ? 'option_values' : 'html_attributes', $props, array()),
- $props['html_type'] == 'select' ? CRM_Utils_Array::value('html_attributes', $props) : NULL
- );
- }
- }
- elseif ($add == 'addMonthDay') {
- $this->add('date', $setting, ts($props['title']), CRM_Core_SelectValues::date(NULL, 'M d'));
- }
- elseif ($add == 'addDate') {
- $this->addDate($setting, ts($props['title']), FALSE, array('formatType' => $props['type']));
- }
- else {
- $this->$add($setting, ts($props['title']));
- }
+ parent::buildQuickForm();
+ $config = CRM_Core_Config::singleton();
+ $this->invoiceSettings = [
+ 'invoice_prefix' => [
+ 'html_type' => 'text',
+ 'title' => ts('Invoice Prefix'),
+ 'weight' => 1,
+ 'description' => ts('Enter prefix to be display on PDF for invoice'),
+ ],
+ 'credit_notes_prefix' => [
+ 'html_type' => 'text',
+ 'title' => ts('Credit Notes Prefix'),
+ 'weight' => 2,
+ 'description' => ts('Enter prefix to be display on PDF for credit notes.'),
+ ],
+ 'due_date' => [
+ 'html_type' => 'text',
+ 'title' => ts('Due Date'),
+ 'weight' => 3,
+ ],
+ 'due_date_period' => [
+ 'html_type' => 'select',
+ 'title' => ts('For transmission'),
+ 'weight' => 4,
+ 'description' => ts('Select the interval for due date.'),
+ 'option_values' => [
+ 'select' => ts('- select -'),
+ 'days' => ts('Days'),
+ 'months' => ts('Months'),
+ 'years' => ts('Years'),
+ ],
+ ],
+ 'notes' => [
+ 'html_type' => 'wysiwyg',
+ 'title' => ts('Notes or Standard Terms'),
+ 'weight' => 5,
+ 'description' => ts('Enter note or message to be displayed on PDF invoice or credit notes '),
+ 'attributes' => ['rows' => 2, 'cols' => 40],
+ ],
+ 'is_email_pdf' => [
+ 'html_type' => 'checkbox',
+ 'title' => ts('Automatically email invoice when user purchases online'),
+ 'weight' => 6,
+ 'description' => ts('Should a pdf invoice be emailed automatically?'),
+ ],
+ 'tax_term' => [
+ 'html_type' => 'text',
+ 'title' => ts('Tax Term'),
+ 'weight' => 7,
+ ],
+ 'tax_display_settings' => [
+ 'html_type' => 'select',
+ 'title' => ts('Tax Display Settings'),
+ 'weight' => 8,
+ 'option_values' => [
+ 'Do_not_show' => ts('Do not show breakdown, only show total -i.e ' .
+ $config->defaultCurrencySymbol . '120.00'),
+ 'Inclusive' => ts('Show [tax term] inclusive price - i.e. ' .
+ $config->defaultCurrencySymbol .
+ '120.00 (includes [tax term] of ' .
+ $config->defaultCurrencySymbol . '20.00)'),
+ 'Exclusive' => ts('Show [tax term] exclusive price - i.e. ' .
+ $config->defaultCurrencySymbol . '100.00 + ' .
+ $config->defaultCurrencySymbol . '20.00 [tax term]'),
+ ],
+ ],
+ ];
+
+ // @todo this is a faux metadata approach - we should be honest & add them correctly or find a way to make this
+ // compatible with our settings standards.
+ foreach ($this->invoiceSettings as $fieldName => $fieldValue) {
+ switch ($fieldValue['html_type']) {
+ case 'text':
+ $this->addElement('text',
+ $fieldName,
+ $fieldValue['title'],
+ [
+ 'maxlength' => 64,
+ 'size' => 32,
+ ]
+ );
+ break;
+
+ case 'checkbox':
+ $this->add($fieldValue['html_type'],
+ $fieldName,
+ $fieldValue['title']
+ );
+ break;
+
+ case 'select':
+ $this->addElement('select',
+ $fieldName,
+ $fieldValue['title'],
+ $fieldValue['option_values'],
+ CRM_Utils_Array::value('attributes', $fieldValue)
+ );
+ break;
+
+ case 'wysiwyg':
+ $this->add('wysiwyg', $fieldName, $fieldValue['title'], $fieldValue['attributes']);
+ break;
}
- $htmlFields[$setting] = ts($props['description']);
}
- $this->assign('htmlFields', $htmlFields);
- parent::buildQuickForm();
+
+ $this->assign('htmlFields', $this->invoiceSettings);
}
/**
@@ -175,16 +175,8 @@ public function buildQuickForm() {
* default values are retrieved from the database
*/
public function setDefaultValues() {
- $defaults = Civi::settings()->get('contribution_invoice_settings');
- //CRM-16691: Changes made related to settings of 'CVV'.
- foreach (array('cvv_backoffice_required') as $setting) {
- $defaults[$setting] = civicrm_api3('setting', 'getvalue',
- array(
- 'name' => $setting,
- 'group' => CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,
- )
- );
- }
+ $defaults = parent::setDefaultValues();
+ $defaults = array_merge($defaults, Civi::settings()->get('contribution_invoice_settings'));
return $defaults;
}
@@ -194,40 +186,14 @@ public function setDefaultValues() {
public function postProcess() {
// store the submitted values in an array
$params = $this->controller->exportValues($this->_name);
- unset($params['qfKey']);
- unset($params['entryURL']);
- Civi::settings()->set('contribution_invoice_settings', $params);
- Civi::settings()->set('update_contribution_on_membership_type_change',
- CRM_Utils_Array::value('update_contribution_on_membership_type_change', $params)
- );
-
- // to set default value for 'Invoices / Credit Notes' checkbox on display preferences
- $values = CRM_Core_BAO_Setting::getItem("CiviCRM Preferences");
- $optionValues = CRM_Core_OptionGroup::values('user_dashboard_options', FALSE, FALSE, FALSE, NULL, 'name');
- $setKey = array_search('Invoices / Credit Notes', $optionValues);
-
- if (isset($params['invoicing'])) {
- $value = array($setKey => $optionValues[$setKey]);
- $setInvoice = CRM_Core_DAO::VALUE_SEPARATOR .
- implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value)) .
- CRM_Core_DAO::VALUE_SEPARATOR;
- Civi::settings()->set('user_dashboard_options', $values['user_dashboard_options'] . $setInvoice);
- }
- else {
- $setting = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($values['user_dashboard_options'], 1, -1));
- $invoiceKey = array_search($setKey, $setting);
- if ($invoiceKey !== FALSE) {
- unset($setting[$invoiceKey]);
- }
- $settingName = CRM_Core_DAO::VALUE_SEPARATOR .
- implode(CRM_Core_DAO::VALUE_SEPARATOR, array_values($setting)) .
- CRM_Core_DAO::VALUE_SEPARATOR;
- Civi::settings()->set('user_dashboard_options', $settingName);
- }
- //CRM-16691: Changes made related to settings of 'CVV'.
- $settings = array_intersect_key($params, array('cvv_backoffice_required' => 1));
- $result = civicrm_api3('setting', 'create', $settings);
- CRM_Core_Session::setStatus(ts('Your changes have been saved.'), ts('Changes Saved'), "success");
+ $invoiceParams = array_intersect_key($params, $this->invoiceSettings);
+ // This is a hack - invoicing is it's own setting but it is being used from invoice params
+ // too. This means that saving from api will not have the desired core effect.
+ // but we should fix that elsewhere - ie. stop abusing the settings
+ // and fix the code repetition associated with invoicing
+ $invoiceParams['invoicing'] = CRM_Utils_Array::value('invoicing', $params, 0);
+ Civi::settings()->set('contribution_invoice_settings', $invoiceParams);
+ parent::postProcess();
}
}
diff --git a/CRM/Admin/Form/Preferences/Display.php b/CRM/Admin/Form/Preferences/Display.php
index bc678af44497..9ba36825cdf9 100644
--- a/CRM/Admin/Form/Preferences/Display.php
+++ b/CRM/Admin/Form/Preferences/Display.php
@@ -1,9 +1,9 @@
_varNames = array(
- CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME => array(
- 'contact_view_options' => array(
- 'html_type' => 'checkboxes',
- 'title' => ts('Viewing Contacts'),
- 'weight' => 1,
- ),
- 'contact_smart_group_display' => array(
- 'html_type' => 'radio',
- 'title' => ts('Viewing Smart Groups'),
- 'weight' => 2,
- ),
- 'contact_edit_options' => array(
- 'html_type' => 'checkboxes',
- 'title' => ts('Editing Contacts'),
- 'weight' => 3,
- ),
- 'advanced_search_options' => array(
- 'html_type' => 'checkboxes',
- 'title' => ts('Contact Search'),
- 'weight' => 4,
- ),
- 'activity_assignee_notification' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Notify Activity Assignees'),
- 'weight' => 5,
- ),
- 'activity_assignee_notification_ics' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Include ICal Invite to Activity Assignees'),
- 'weight' => 6,
- ),
- 'preserve_activity_tab_filter' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Preserve activity filters as a user preference'),
- 'weight' => 7,
- ),
- 'contact_ajax_check_similar' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Check for Similar Contacts'),
- 'weight' => 8,
- ),
- 'user_dashboard_options' => array(
- 'html_type' => 'checkboxes',
- 'title' => ts('Contact Dashboard'),
- 'weight' => 9,
- ),
- 'display_name_format' => array(
- 'html_type' => 'textarea',
- 'title' => ts('Individual Display Name Format'),
- 'weight' => 10,
- ),
- 'sort_name_format' => array(
- 'html_type' => 'textarea',
- 'title' => ts('Individual Sort Name Format'),
- 'weight' => 11,
- ),
- 'editor_id' => array(
- 'html_type' => NULL,
- 'weight' => 12,
- ),
- 'ajaxPopupsEnabled' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable Popup Forms'),
- 'weight' => 13,
- ),
- ),
- );
-
- parent::preProcess();
- }
- /**
- * @return array
- */
- public function setDefaultValues() {
- $defaults = parent::setDefaultValues();
- parent::cbsDefaultValues($defaults);
-
- if ($this->_config->display_name_format) {
- $defaults['display_name_format'] = $this->_config->display_name_format;
- }
- if ($this->_config->sort_name_format) {
- $defaults['sort_name_format'] = $this->_config->sort_name_format;
- }
-
- return $defaults;
- }
+ protected $_settings = [
+ 'contact_view_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'contact_smart_group_display' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'contact_edit_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'advanced_search_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'user_dashboard_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'contact_ajax_check_similar' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'activity_assignee_notification' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'activity_assignee_notification_ics' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'do_not_notify_assignees_for' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'preserve_activity_tab_filter' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'editor_id' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'ajaxPopupsEnabled' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'display_name_format' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'sort_name_format' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'menubar_position' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'menubar_color' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ ];
/**
* Build the form object.
*/
public function buildQuickForm() {
- $wysiwyg_options = CRM_Core_OptionGroup::values('wysiwyg_editor', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
//changes for freezing the invoices/credit notes checkbox if invoicing is uncheck
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
- $this->assign('invoicing', $invoicing);
- $extra = array();
+ $this->assign('invoicing', CRM_Invoicing_Utils::isInvoicingEnabled());
- $this->addElement('select', 'editor_id', ts('WYSIWYG Editor'), $wysiwyg_options, $extra);
$this->addElement('submit', 'ckeditor_config', ts('Configure CKEditor'));
$editOptions = CRM_Core_OptionGroup::values('contact_edit_options', FALSE, FALSE, FALSE, 'AND v.filter = 0');
@@ -151,7 +75,7 @@ public function buildQuickForm() {
$nameFields = CRM_Core_OptionGroup::values('contact_edit_options', FALSE, FALSE, FALSE, 'AND v.filter = 2');
$this->assign('nameFields', $nameFields);
- $this->addElement('hidden', 'contact_edit_preferences', NULL, array('id' => 'contact_edit_preferences'));
+ $this->addElement('hidden', 'contact_edit_preferences', NULL, ['id' => 'contact_edit_preferences']);
$optionValues = CRM_Core_OptionGroup::values('user_dashboard_options', FALSE, FALSE, FALSE, NULL, 'name');
$invoicesKey = array_search('Invoices / Credit Notes', $optionValues);
@@ -180,8 +104,6 @@ public function postProcess() {
CRM_Core_BAO_OptionValue::updateOptionWeights($opGroupId, array_flip($preferenceWeights));
}
- $this->_config->editor_id = $this->_params['editor_id'];
-
$this->postProcessCommon();
// If "Configure CKEditor" button was clicked
diff --git a/CRM/Admin/Form/Preferences/Event.php b/CRM/Admin/Form/Preferences/Event.php
deleted file mode 100644
index 5d8d75a66038..000000000000
--- a/CRM/Admin/Form/Preferences/Event.php
+++ /dev/null
@@ -1,72 +0,0 @@
-_varNames = array(
- CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME => array(
- 'enable_cart' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Use Shopping Cart Style Event Registration'),
- 'weight' => 1,
- 'description' => ts('This feature allows users to register for more than one event at a time. When enabled, users will add event(s) to a "cart" and then pay for them all at once. Enabling this setting will affect online registration for all active events. The code is an alpha state, and you will potentially need to have developer resources to debug and fix sections of the codebase while testing and deploying it. %1',
- array(1 => $docLink)),
- ),
- 'show_events' => array(
- 'html_type' => 'select',
- 'title' => ts('Dashboard entries'),
- 'weight' => 2,
- 'description' => ts('Configure how many events should be shown on the dashboard. This overrides the default value of 10 entries.'),
- 'option_values' => array('' => ts('- select -')) + $optionValues + array(-1 => ts('show all')),
- ),
- ),
- );
-
- parent::preProcess();
- }
-
-}
diff --git a/CRM/Admin/Form/Preferences/Mailing.php b/CRM/Admin/Form/Preferences/Mailing.php
index 2b8af0a29a73..ab6069fbed44 100644
--- a/CRM/Admin/Form/Preferences/Mailing.php
+++ b/CRM/Admin/Form/Preferences/Mailing.php
@@ -1,9 +1,9 @@
_varNames = array(
- CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME => array(
- 'profile_double_optin' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable Double Opt-in for Profile Group(s) field'),
- 'weight' => 1,
- 'description' => ts('When CiviMail is enabled, users who "subscribe" to a group from a profile Group(s) checkbox will receive a confirmation email. They must respond (opt-in) before they are added to the group.'),
- ),
- 'profile_add_to_group_double_optin' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable Double Opt-in for Profiles which use the "Add to Group" setting'),
- 'weight' => 2,
- 'description' => ts('When CiviMail is enabled and a profile uses the "Add to Group" setting, users who complete the profile form will receive a confirmation email. They must respond (opt-in) before they are added to the group.'),
- ),
- 'track_civimail_replies' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Track replies using VERP in Reply-To header'),
- 'weight' => 3,
- 'description' => ts('If checked, mailings will default to tracking replies using VERP-ed Reply-To.'),
- ),
- 'civimail_workflow' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable workflow support for CiviMail'),
- 'weight' => 4,
- 'description' => ts('Drupal-only. Rules module must be enabled (beta feature - use with caution).'),
- ),
- 'civimail_multiple_bulk_emails' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable multiple bulk email address for a contact.'),
- 'weight' => 5,
- 'description' => ts('CiviMail will deliver a copy of the email to each bulk email listed for the contact.'),
- ),
- 'civimail_server_wide_lock' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable global server wide lock for CiviMail'),
- 'weight' => 6,
- 'description' => NULL,
- ),
- 'include_message_id' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable CiviMail to generate Message-ID header'),
- 'weight' => 7,
- 'description' => NULL,
- ),
- 'write_activity_record' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable CiviMail to create activities on delivery'),
- 'weight' => 8,
- 'description' => NULL,
- ),
- 'disable_mandatory_tokens_check' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Disable check for mandatory tokens'),
- 'weight' => 9,
- 'description' => ts('Don\'t check for presence of mandatory tokens (domain address; unsubscribe/opt-out) before sending mailings. WARNING: Mandatory tokens are a safe-guard which facilitate compliance with the US CAN-SPAM Act. They should only be disabled if your organization adopts other mechanisms for compliance or if your organization is not subject to CAN-SPAM.'),
- ),
- 'dedupe_email_default' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('CiviMail dedupes e-mail addresses by default'),
- 'weight' => 10,
- 'description' => NULL,
- ),
- 'hash_mailing_url' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Hashed Mailing URL\'s'),
- 'weight' => 11,
- 'description' => 'If enabled, a randomized hash key will be used to reference the mailing URL in the mailing.viewUrl token, instead of the mailing ID',
- ),
- ),
- );
- parent::preProcess();
- }
+ protected $_settings = [
+ 'profile_double_optin' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'profile_add_to_group_double_optin' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'track_civimail_replies' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'civimail_workflow' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'civimail_multiple_bulk_emails' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'civimail_server_wide_lock' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'include_message_id' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'write_activity_record' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'disable_mandatory_tokens_check' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'dedupe_email_default' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'hash_mailing_url' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ 'auto_recipient_rebuild' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
+ ];
public function postProcess() {
- // check if mailing tab is enabled, if not prompt user to enable the tab if "write_activity_record" is disabled
$params = $this->controller->exportValues($this->_name);
if (empty($params['write_activity_record'])) {
+ // @todo use the setting onToggle & add an action rather than have specific form handling.
+ // see logging setting for eg.
$existingViewOptions = Civi::settings()->get('contact_view_options');
$displayValue = CRM_Core_OptionGroup::getValue('contact_view_options', 'CiviMail', 'name');
diff --git a/CRM/Admin/Form/Preferences/Member.php b/CRM/Admin/Form/Preferences/Member.php
index e1f68214d02d..f9b9b8fe4eed 100644
--- a/CRM/Admin/Form/Preferences/Member.php
+++ b/CRM/Admin/Form/Preferences/Member.php
@@ -1,9 +1,9 @@
_varNames = array(
- CRM_Core_BAO_Setting::MEMBER_PREFERENCES_NAME => array(
- 'default_renewal_contribution_page' => array(
- 'html_type' => 'select',
- 'title' => ts('Default online membership renewal page'),
- 'option_values' => array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionPage(),
- 'weight' => 1,
- 'description' => ts('If you select a default online contribution page for self-service membership renewals, a "renew" link pointing to that page will be displayed on the Contact Dashboard for memberships which were entered offline. You will need to ensure that the membership block for the selected online contribution page includes any currently available memberships.'),
- ),
- ),
- );
- parent::preProcess();
- }
-
- /**
- * Build the form object.
- */
- public function buildQuickForm() {
- parent::buildQuickForm();
- }
+ protected $_settings = [
+ 'default_renewal_contribution_page' => CRM_Core_BAO_Setting::MEMBER_PREFERENCES_NAME,
+ ];
}
diff --git a/CRM/Admin/Form/Preferences/Multisite.php b/CRM/Admin/Form/Preferences/Multisite.php
index 4aa58a961bf7..e5616922686f 100644
--- a/CRM/Admin/Form/Preferences/Multisite.php
+++ b/CRM/Admin/Form/Preferences/Multisite.php
@@ -1,9 +1,9 @@
_varNames = array(
- CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME => array(
- 'is_enabled' => array(
- 'html_type' => 'checkbox',
- 'title' => ts('Enable Multi Site Configuration'),
- 'weight' => 1,
- 'description' => ts('Make CiviCRM aware of multiple domains. You should configure a domain group if enabled') . ' ' . $msDoc,
- ),
- /** Remove this checkbox until some one knows what this setting does
- * 'uniq_email_per_site' => array(
- * 'html_type' => 'checkbox',
- * 'title' => ts('Ensure multi sites have a unique email per site'),
- * 'weight' => 2,
- * 'description' => NULL,
- * ),
- */
- 'domain_group_id' => array(
- 'html_type' => 'entity_reference',
- 'title' => ts('Domain Group'),
- 'weight' => 3,
- 'options' => array('entity' => 'group', 'select' => array('minimumInputLength' => 0)),
- 'description' => ts('Contacts created on this site are added to this group'),
- ),
- /** Remove this checkbox until some one knows what this setting does
- * 'event_price_set_domain_id' => array(
- * 'html_type' => 'text',
- * 'title' => ts('Domain for event price sets'),
- * 'weight' => 4,
- * 'description' => NULL,
- * ),
- */
- ),
- );
- parent::preProcess();
- }
+ protected $_settings = [
+ 'is_enabled' => CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
+ 'domain_group_id' => CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
+ ];
}
diff --git a/CRM/Admin/Form/PreferencesDate.php b/CRM/Admin/Form/PreferencesDate.php
index fcea91b7397b..95940ff6f8f7 100644
--- a/CRM/Admin/Form/PreferencesDate.php
+++ b/CRM/Admin/Form/PreferencesDate.php
@@ -1,9 +1,9 @@
add('select', 'date_format', ts('Format'),
- array('' => ts('- default input format -')) + CRM_Core_SelectValues::getDatePluginInputFormats()
+ ['' => ts('- default input format -')] + CRM_Core_SelectValues::getDatePluginInputFormats()
);
$this->add('select', 'time_format', ts('Time'),
- array('' => ts('- none -')) + CRM_Core_SelectValues::getTimeFormats()
+ ['' => ts('- none -')] + CRM_Core_SelectValues::getTimeFormats()
);
}
$this->addRule('start', ts('Value must be an integer.'), 'integer');
$this->addRule('end', ts('Value must be an integer.'), 'integer');
// add a form rule
- $this->addFormRule(array('CRM_Admin_Form_PreferencesDate', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_PreferencesDate', 'formRule']);
}
/**
@@ -93,7 +93,7 @@ public function buildQuickForm() {
* true otherwise
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
if ($fields['name'] == 'activityDateTime' && !$fields['time_format']) {
$errors['time_format'] = ts('Time is required for this format.');
@@ -129,7 +129,7 @@ public function postProcess() {
CRM_Core_Resources::singleton()->resetCacheCode();
CRM_Core_Session::setStatus(ts("The date type '%1' has been saved.",
- array(1 => $params['name'])
+ [1 => $params['name']]
), ts('Saved'), 'success');
}
diff --git a/CRM/Admin/Form/RelationshipType.php b/CRM/Admin/Form/RelationshipType.php
index c42db6dc3170..b0c604c0103b 100644
--- a/CRM/Admin/Form/RelationshipType.php
+++ b/CRM/Admin/Form/RelationshipType.php
@@ -1,9 +1,9 @@
'' to hide)
+ * - not-auto-addable - this class will not attempt to add the field using addField.
+ * (this will be automatically set if the field does not have html in it's metadata
+ * or is not a core field on the form's entity).
+ * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * - is_freeze (field should be frozen).
+ *
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'label_a_b' => [
+ 'name' => 'label_a_b',
+ 'description' => ts("Label for the relationship from Contact A to Contact B. EXAMPLE: Contact A is 'Parent of' Contact B."),
+ 'required' => TRUE,
+ ],
+ 'label_b_a' => [
+ 'name' => 'label_b_a',
+ 'description' => ts("Label for the relationship from Contact B to Contact A. EXAMPLE: Contact B is 'Child of' Contact A. You may leave this blank for relationships where the name is the same in both directions (e.g. Spouse)."),
+ ],
+ 'description' => [
+ 'name' => 'description',
+ 'description' => '',
+ ],
+ 'contact_types_a' => ['name' => 'contact_types_a', 'not-auto-addable' => TRUE],
+ 'contact_types_b' => ['name' => 'contact_types_b', 'not-auto-addable' => TRUE],
+ 'is_active' => ['name' => 'is_active'],
+ ];
+
+ self::setEntityFieldsMetadata();
+ }
+
+ /**
+ * Deletion message to be assigned to the form.
+ *
+ * @var string
+ */
+ protected $deleteMessage;
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'RelationshipType';
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('WARNING: Deleting this option will result in the loss of all Relationship records of this type.') . ts('This may mean the loss of a substantial amount of data, and the action cannot be undone.') . ts('Do you want to continue?');
+ }
+
/**
* Build the form object.
*/
public function buildQuickForm() {
- parent::buildQuickForm();
- $this->setPageTitle(ts('Relationship Type'));
+ $isReserved = ($this->_id && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $this->_id, 'is_reserved'));
+ $this->entityFields['is_active']['is_freeze'] = $isReserved;
+ self::buildQuickEntityForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
- $this->applyFilter('__ALL__', 'trim');
-
- $this->add('text', 'label_a_b', ts('Relationship Label-A to B'),
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_RelationshipType', 'label_a_b'), TRUE
- );
$this->addRule('label_a_b', ts('Label already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_RelationshipType', $this->_id, 'label_a_b')
- );
-
- $this->add('text', 'label_b_a', ts('Relationship Label-B to A'),
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_RelationshipType', 'label_b_a')
+ 'objectExists', ['CRM_Contact_DAO_RelationshipType', $this->_id, 'label_a_b']
);
-
$this->addRule('label_b_a', ts('Label already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_RelationshipType', $this->_id, 'label_b_a')
- );
-
- $this->add('text', 'description', ts('Description'),
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_RelationshipType', 'description')
+ 'objectExists', ['CRM_Contact_DAO_RelationshipType', $this->_id, 'label_b_a']
);
$contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, '__');
-
- // add select for contact type
- $contactTypeA = &$this->add('select', 'contact_types_a', ts('Contact Type A') . ' ',
- array(
- '' => ts('All Contacts'),
- ) + $contactTypes
- );
- $contactTypeB = &$this->add('select', 'contact_types_b', ts('Contact Type B') . ' ',
- array(
- '' => ts('All Contacts'),
- ) + $contactTypes
- );
-
- $isActive = &$this->add('checkbox', 'is_active', ts('Enabled?'));
-
- //only selected field should be allow for edit, CRM-4888
- if ($this->_id &&
- CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $this->_id, 'is_reserved')
- ) {
- foreach (array('contactTypeA', 'contactTypeB', 'isActive') as $field) {
- $$field->freeze();
+ foreach (['contact_types_a' => ts('Contact Type A'), 'contact_types_b' => ts('Contact Type B')] as $name => $label) {
+ $element = $this->add('select', $name, $label . ' ',
+ [
+ '' => ts('All Contacts'),
+ ] + $contactTypes
+ );
+ if ($isReserved) {
+ $element->freeze();
}
}
@@ -97,8 +141,6 @@ public function buildQuickForm() {
$this->freeze();
}
- $this->assign('relationship_type_id', $this->_id);
-
}
/**
@@ -108,8 +150,8 @@ public function setDefaultValues() {
if ($this->_action != CRM_Core_Action::DELETE &&
isset($this->_id)
) {
- $defaults = $params = array();
- $params = array('id' => $this->_id);
+ $defaults = $params = [];
+ $params = ['id' => $this->_id];
$baoName = $this->_BAOName;
$baoName::retrieve($params, $defaults);
$defaults['contact_types_a'] = CRM_Utils_Array::value('contact_type_a', $defaults);
@@ -137,14 +179,12 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected Relationship type has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $ids = array();
-
// store the submitted values in an array
$params = $this->exportValues();
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['relationshipType'] = $this->_id;
+ $params['id'] = $this->_id;
}
$cTypeA = CRM_Utils_System::explode('__',
@@ -159,12 +199,22 @@ public function postProcess() {
$params['contact_type_a'] = $cTypeA[0];
$params['contact_type_b'] = $cTypeB[0];
- $params['contact_sub_type_a'] = $cTypeA[1] ? $cTypeA[1] : 'NULL';
- $params['contact_sub_type_b'] = $cTypeB[1] ? $cTypeB[1] : 'NULL';
+ $params['contact_sub_type_a'] = $cTypeA[1] ? $cTypeA[1] : 'null';
+ $params['contact_sub_type_b'] = $cTypeB[1] ? $cTypeB[1] : 'null';
+
+ if (!strlen(trim(CRM_Utils_Array::value('label_b_a', $params)))) {
+ $params['label_b_a'] = CRM_Utils_Array::value('label_a_b', $params);
+ }
+
+ if (empty($params['id'])) {
+ // Set name on created but don't update on update as the machine name is not exposed.
+ $params['name_b_a'] = $params['label_b_a'];
+ $params['name_a_b'] = $params['label_a_b'];
+ }
- $result = CRM_Contact_BAO_RelationshipType::add($params, $ids);
+ $result = civicrm_api3('RelationshipType', 'create', $params);
- $this->ajaxResponse['relationshipType'] = $result->toArray();
+ $this->ajaxResponse['relationshipType'] = $result['values'];
CRM_Core_Session::setStatus(ts('The Relationship Type has been saved.'), ts('Saved'), 'success');
}
diff --git a/CRM/Admin/Form/ScheduleReminders.php b/CRM/Admin/Form/ScheduleReminders.php
index 9e47d4b404e4..e2365cb9d01e 100644
--- a/CRM/Admin/Form/ScheduleReminders.php
+++ b/CRM/Admin/Form/ScheduleReminders.php
@@ -1,9 +1,9 @@
_compId;
+ }
+
+ /**
+ * @param mixed $compId
+ */
+ public function setComponentID($compId) {
+ $this->_compId = $compId;
+ }
+
/**
* Build the form object.
*/
@@ -50,57 +67,46 @@ public function buildQuickForm() {
parent::buildQuickForm();
$this->_mappingID = $mappingID = NULL;
$providersCount = CRM_SMS_BAO_Provider::activeProviderCount();
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->setContext();
+ $isEvent = $this->getContext() == 'event';
- //CRM-16777: Don't provide access to administer schedule reminder page, with user that does not have 'administer CiviCRM' permission
- if (empty($this->_context) && !CRM_Core_Permission::check('administer CiviCRM')) {
- CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
- }
- //CRM-16777: When user have ACLs 'edit' permission for specific event, do not give access to add, delete & updtae
- //schedule reminder for other events.
- else {
- $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
- if (!CRM_Event_BAO_Event::checkPermission($this->_compId, CRM_Core_Permission::EDIT)) {
- CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ if ($isEvent) {
+ $this->setComponentID(CRM_Utils_Request::retrieve('compId', 'Integer', $this));
+ if (!CRM_Event_BAO_Event::checkPermission($this->getComponentID(), CRM_Core_Permission::EDIT)) {
+ throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
}
}
+ elseif (!CRM_Core_Permission::check('administer CiviCRM')) {
+ throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
+ }
if ($this->_action & (CRM_Core_Action::DELETE)) {
$reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title');
- if ($this->_context == 'event') {
- $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
- }
$this->assign('reminderName', $reminderName);
return;
}
elseif ($this->_action & (CRM_Core_Action::UPDATE)) {
$this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id');
- if ($this->_context == 'event') {
- $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
- }
}
- elseif (!empty($this->_context)) {
- if ($this->_context == 'event') {
- $this->_compId = CRM_Utils_Request::retrieve('compId', 'Integer', $this);
- $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_compId, 'is_template');
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
- 'id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
- )));
- if ($mapping) {
- $this->_mappingID = $mapping->getId();
- }
- else {
- CRM_Core_Error::fatal('Could not find mapping for event scheduled reminders.');
- }
+ if ($isEvent) {
+ $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->getComponentID(), 'is_template');
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
+ 'id' => $isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
+ ]));
+ if ($mapping) {
+ $this->_mappingID = $mapping->getId();
+ }
+ else {
+ throw new CRM_Core_Exception('Could not find mapping for event scheduled reminders.');
}
}
- if (!empty($_POST) && !empty($_POST['entity']) && empty($this->_context)) {
+ if (!empty($_POST) && !empty($_POST['entity']) && empty($this->getContext())) {
$mappingID = $_POST['entity'][0];
}
elseif ($this->_mappingID) {
$mappingID = $this->_mappingID;
- if ($this->_context == 'event') {
+ if ($isEvent) {
$this->add('hidden', 'mappingID', $mappingID);
}
}
@@ -123,21 +129,21 @@ public function buildQuickForm() {
array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels))
));
- if (empty($this->_context)) {
+ if (!$this->getContext()) {
$sel = &$this->add(
'hierselect',
'entity',
ts('Entity'),
- array(
+ [
'name' => 'entity[0]',
'style' => 'vertical-align: top;',
- )
+ ]
);
- $sel->setOptions(array(
+ $sel->setOptions([
CRM_Utils_Array::collectMethod('getLabel', $mappings),
CRM_Core_BAO_ActionSchedule::getAllEntityValueLabels(),
CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels(),
- ));
+ ]);
if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
// make second selector a multi-select -
@@ -155,31 +161,30 @@ public function buildQuickForm() {
// Dig deeper - this code is sublimely stupid.
$allEntityStatusLabels = CRM_Core_BAO_ActionSchedule::getAllEntityStatusLabels();
$options = $allEntityStatusLabels[$this->_mappingID][0];
- $attributes = array('multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]);
+ $attributes = ['multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]];
unset($options[0]);
$this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes);
- $this->assign('context', $this->_context);
+ $this->assign('context', $this->getContext());
}
//get the frequency units.
$this->_freqUnits = CRM_Core_SelectValues::getRecurringFrequencyUnits();
//reminder_interval
- $this->add('number', 'start_action_offset', ts('When'), array('class' => 'six', 'min' => 0));
+ $this->add('number', 'start_action_offset', ts('When'), ['class' => 'six', 'min' => 0]);
$this->addRule('start_action_offset', ts('Value should be a positive number'), 'positiveInteger');
- $isActive = ts('Send email');
+ $isActive = ts('Scheduled Reminder Active');
$recordActivity = ts('Record activity for automated email');
if ($providersCount) {
$this->assign('sms', $providersCount);
- $isActive = ts('Send email or SMS');
$recordActivity = ts('Record activity for automated email or SMS');
$options = CRM_Core_OptionGroup::values('msg_mode');
$this->add('select', 'mode', ts('Send as'), $options);
$providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
- $providerSelect = array();
+ $providerSelect = [];
foreach ($providers as $provider) {
$providerSelect[$provider['id']] = $provider['title'];
}
@@ -187,18 +192,18 @@ public function buildQuickForm() {
}
foreach ($this->_freqUnits as $val => $label) {
- $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
+ $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
}
- $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing'));
+ $this->add('datepicker', 'absolute_date', ts('Start Date'), [], FALSE, ['time' => FALSE]);
//reminder_frequency
$this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE);
- $condition = array(
+ $condition = [
'before' => ts('before'),
'after' => ts('after'),
- );
+ ];
//reminder_action
$this->add('select', 'start_action_condition', ts('Action Condition'), $condition);
@@ -207,15 +212,15 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'record_activity', $recordActivity);
$this->addElement('checkbox', 'is_repeat', ts('Repeat'),
- NULL, array('onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);")
+ NULL, ['onchange' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);"]
);
$this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay);
- $this->add('number', 'repetition_frequency_interval', ts('every'), array('class' => 'six', 'min' => 0));
+ $this->add('number', 'repetition_frequency_interval', ts('every'), ['class' => 'six', 'min' => 0]);
$this->addRule('repetition_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
$this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay);
- $this->add('number', 'end_frequency_interval', ts('until'), array('class' => 'six', 'min' => 0));
+ $this->add('number', 'end_frequency_interval', ts('until'), ['class' => 'six', 'min' => 0]);
$this->addRule('end_frequency_interval', ts('Value should be a positive number'), 'positiveInteger');
$this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE);
@@ -224,27 +229,27 @@ public function buildQuickForm() {
$this->add('text', 'from_name', ts('From Name'));
$this->add('text', 'from_email', ts('From Email'));
- $recipientListingOptions = array();
+ $recipientListingOptions = [];
if ($mappingID) {
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => $mappingID,
- )));
+ ]));
}
- $limitOptions = array('' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include'));
+ $limitOptions = ['' => '-neither-', 1 => ts('Limit to'), 0 => ts('Also include')];
- $recipientLabels = array('activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients'));
+ $recipientLabels = ['activity' => ts('Recipients'), 'other' => ts('Limit or Add Recipients')];
$this->assign('recipientLabels', $recipientLabels);
- $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, array('onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"));
+ $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions, FALSE, ['onChange' => "showHideByValue('limit_to','','recipient', 'select','select',true);"]);
$this->add('select', 'recipient', $recipientLabels['other'], $entityRecipientLabels,
- FALSE, array('onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);")
+ FALSE, ['onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);"]
);
if (!empty($this->_submitValues['recipient_listing'])) {
- if (!empty($this->_context)) {
+ if ($this->getContext()) {
$recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_mappingID, $this->_submitValues['recipient']);
}
else {
@@ -256,12 +261,12 @@ public function buildQuickForm() {
}
$this->add('select', 'recipient_listing', ts('Recipient Roles'), $recipientListingOptions, FALSE,
- array('multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE));
+ ['multiple' => TRUE, 'class' => 'crm-select2 huge', 'placeholder' => TRUE]);
- $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), array('multiple' => TRUE, 'create' => TRUE));
+ $this->addEntityRef('recipient_manual_id', ts('Manual Recipients'), ['multiple' => TRUE, 'create' => TRUE]);
$this->add('select', 'group_id', ts('Group'),
- CRM_Core_PseudoConstant::nestedGroup('Mailing'), FALSE, array('class' => 'crm-select2 huge')
+ CRM_Core_PseudoConstant::nestedGroup('Mailing'), FALSE, ['class' => 'crm-select2 huge']
);
// multilingual only options
@@ -271,14 +276,14 @@ public function buildQuickForm() {
$smarty->assign('multilingual', $multilingual);
$languages = CRM_Core_I18n::languages(TRUE);
- $languageFilter = $languages + array(CRM_Core_I18n::NONE => ts('Contacts with no preferred language'));
+ $languageFilter = $languages + [CRM_Core_I18n::NONE => ts('Contacts with no preferred language')];
$element = $this->add('select', 'filter_contact_language', ts('Recipients language'), $languageFilter, FALSE,
- array('multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE));
+ ['multiple' => TRUE, 'class' => 'crm-select2', 'placeholder' => TRUE]);
- $communicationLanguage = array(
+ $communicationLanguage = [
'' => ts('System default language'),
CRM_Core_I18n::AUTO => ts('Follow recipient preferred language'),
- );
+ ];
$communicationLanguage = $communicationLanguage + $languages;
$this->add('select', 'communication_language', ts('Communication language'), $communicationLanguage);
}
@@ -291,7 +296,7 @@ public function buildQuickForm() {
$this->add('checkbox', 'is_active', $isActive);
- $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule'), $this);
+ $this->addFormRule(['CRM_Admin_Form_ScheduleReminders', 'formRule'], $this);
$this->setPageTitle(ts('Scheduled Reminder'));
}
@@ -308,52 +313,73 @@ public function buildQuickForm() {
* True if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ((array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0) ||
(array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0)
) {
$errors['entity'] = ts('Please select appropriate value');
}
+ $mode = CRM_Utils_Array::value('mode', $fields, FALSE);
if (!empty($fields['is_active']) &&
- CRM_Utils_System::isNull($fields['subject'])
+ CRM_Utils_System::isNull($fields['subject']) && (!$mode || $mode != 'SMS')
) {
$errors['subject'] = ts('Subject is a required field.');
}
if (!empty($fields['is_active']) &&
- CRM_Utils_System::isNull(trim(strip_tags($fields['html_message'])))
+ CRM_Utils_System::isNull(trim(strip_tags($fields['html_message']))) && (!$mode || $mode != 'SMS')
) {
$errors['html_message'] = ts('The HTML message is a required field.');
}
- if (empty($self->_context) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
+ if (!empty($mode) && ($mode == 'SMS' || $mode == 'User_Preference') && !empty($fields['is_active']) &&
+ CRM_Utils_System::isNull(trim(strip_tags($fields['sms_text_message'])))
+ ) {
+ $errors['sms_text_message'] = ts('The SMS message is a required field.');
+ }
+
+ if (empty($self->getContext()) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
$errors['entity'] = ts('Please select entity value');
}
if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
- if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('Ymd'))) {
+ if ($fields['absolute_date'] < date('Y-m-d')) {
$errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
}
}
-
- $recipientKind = array(
- 'participant_role' => array(
+ else {
+ if (CRM_Utils_System::isNull($fields['start_action_offset'])) {
+ $errors['start_action_offset'] = ts('Start Action Offset must be filled in or Absolute Date set');
+ }
+ }
+ if (!CRM_Utils_Rule::email($fields['from_email']) && (!$mode || $mode != 'SMS')) {
+ $errors['from_email'] = ts('Please enter a valid email address.');
+ }
+ $recipientKind = [
+ 'participant_role' => [
'name' => 'participant role',
'target_id' => 'recipient_listing',
- ),
- 'manual' => array(
+ ],
+ 'manual' => [
'name' => 'recipient',
'target_id' => 'recipient_manual_id',
- ),
- );
+ ],
+ ];
if ($fields['limit_to'] != '' && array_key_exists($fields['recipient'], $recipientKind) && empty($fields[$recipientKind[$fields['recipient']]['target_id']])) {
- $errors[$recipientKind[$fields['recipient']]['target_id']] = ts('If "Also include" or "Limit to" are selected, you must specify at least one %1', array(1 => $recipientKind[$fields['recipient']]['name']));
+ $errors[$recipientKind[$fields['recipient']]['target_id']] = ts('If "Also include" or "Limit to" are selected, you must specify at least one %1', [1 => $recipientKind[$fields['recipient']]['name']]);
}
- $actionSchedule = $self->parseActionSchedule($fields);
- if ($actionSchedule->mapping_id) {
- $mapping = CRM_Core_BAO_ActionSchedule::getMapping($actionSchedule->mapping_id);
- CRM_Utils_Array::extend($errors, $mapping->validateSchedule($actionSchedule));
+ //CRM-21523
+ if (!empty($fields['is_repeat']) &&
+ (empty($fields['repetition_frequency_interval']) || ($fields['end_frequency_interval'] == NULL))
+ ) {
+ $errors['is_repeat'] = ts('If you are enabling repetition you must indicate the frequency and ending term.');
+ }
+
+ $self->_actionSchedule = $self->parseActionSchedule($fields);
+ if ($self->_actionSchedule->mapping_id) {
+ $mapping = CRM_Core_BAO_ActionSchedule::getMapping($self->_actionSchedule->mapping_id);
+ CRM_Utils_Array::extend($errors, $mapping->validateSchedule($self->_actionSchedule));
}
if (!empty($errors)) {
@@ -376,7 +402,7 @@ public function setDefaultValues() {
$defaults = $this->_values;
$entityValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('entity_value', $defaults));
$entityStatus = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('entity_status', $defaults));
- if (empty($this->_context)) {
+ if (empty($this->getContext())) {
$defaults['entity'][0] = CRM_Utils_Array::value('mapping_id', $defaults);
$defaults['entity'][1] = $entityValue;
$defaults['entity'][2] = $entityStatus;
@@ -384,10 +410,6 @@ public function setDefaultValues() {
else {
$defaults['entity'] = $entityStatus;
}
- if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $defaults)) {
- list($date, $time) = CRM_Utils_Date::setDateDefaults($absoluteDate);
- $defaults['absolute_date'] = $date;
- }
if ($recipientListing = CRM_Utils_Array::value('recipient_listing', $defaults)) {
$defaults['recipient_listing'] = explode(CRM_Core_DAO::VALUE_SEPARATOR,
@@ -422,9 +444,9 @@ public function postProcess() {
// delete reminder
CRM_Core_BAO_ActionSchedule::del($this->_id);
CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success');
- if ($this->_context == 'event' && $this->_compId) {
+ if ($this->getContext() == 'event' && $this->getComponentID()) {
$url = CRM_Utils_System::url('civicrm/event/manage/reminder',
- "reset=1&action=browse&id={$this->_compId}&component={$this->_context}&setTab=1"
+ "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1"
);
$session = CRM_Core_Session::singleton();
$session->pushUserContext($url);
@@ -432,25 +454,29 @@ public function postProcess() {
return;
}
$values = $this->controller->exportValues($this->getName());
- $bao = $this->parseActionSchedule($values)->save();
+ if (empty($this->_actionSchedule)) {
+ $bao = $this->parseActionSchedule($values)->save();
+ }
+ else {
+ $bao = $this->_actionSchedule->save();
+ }
// we need to set this on the form so that hooks can identify the created entity
$this->set('id', $bao->id);
- $bao->free();
$status = ts("Your new Reminder titled %1 has been saved.",
- array(1 => "{$values['title']}")
+ [1 => "{$values['title']}"]
);
if ($this->_action) {
if ($this->_action & CRM_Core_Action::UPDATE) {
$status = ts("Your Reminder titled %1 has been updated.",
- array(1 => "{$values['title']}")
+ [1 => "{$values['title']}"]
);
}
- if ($this->_context == 'event' && $this->_compId) {
- $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=browse&id={$this->_compId}&component={$this->_context}&setTab=1");
+ if ($this->getContext() == 'event' && $this->getComponentID()) {
+ $url = CRM_Utils_System::url('civicrm/event/manage/reminder', "reset=1&action=browse&id=" . $this->getComponentID() . "&component=" . $this->getContext() . "&setTab=1");
$session = CRM_Core_Session::singleton();
$session->pushUserContext($url);
}
@@ -464,9 +490,9 @@ public function postProcess() {
* @return CRM_Core_DAO_ActionSchedule
*/
public function parseActionSchedule($values) {
- $params = array();
+ $params = [];
- $keys = array(
+ $keys = [
'title',
'subject',
'absolute_date',
@@ -477,14 +503,14 @@ public function parseActionSchedule($values) {
'sms_provider_id',
'from_name',
'from_email',
- );
+ ];
foreach ($keys as $key) {
$params[$key] = CRM_Utils_Array::value($key, $values);
}
$params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
- $moreKeys = array(
+ $moreKeys = [
'start_action_offset',
'start_action_unit',
'start_action_condition',
@@ -495,12 +521,9 @@ public function parseActionSchedule($values) {
'end_frequency_interval',
'end_action',
'end_date',
- );
+ ];
- if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) {
- $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate);
- }
- else {
+ if (!CRM_Utils_Array::value('absolute_date', $params)) {
$params['absolute_date'] = 'null';
}
foreach ($moreKeys as $mkey) {
@@ -535,9 +558,9 @@ public function parseActionSchedule($values) {
$params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
}
- if (!empty($this->_mappingID) && !empty($this->_compId)) {
+ if (!empty($this->_mappingID) && !empty($this->getComponentID())) {
$params['mapping_id'] = $this->_mappingID;
- $params['entity_value'] = $this->_compId;
+ $params['entity_value'] = $this->getComponentID();
$params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
}
else {
@@ -546,8 +569,8 @@ public function parseActionSchedule($values) {
$params['limit_to'] = 1;
}
- $entity_value = CRM_Utils_Array::value(1, $values['entity'], array());
- $entity_status = CRM_Utils_Array::value(2, $values['entity'], array());
+ $entity_value = CRM_Utils_Array::value(1, $values['entity'], []);
+ $entity_status = CRM_Utils_Array::value(2, $values['entity'], []);
$params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value);
$params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status);
}
@@ -564,7 +587,7 @@ public function parseActionSchedule($values) {
}
// multilingual options
- $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, array());
+ $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, []);
$params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']);
$params['communication_language'] = CRM_Utils_Array::value('communication_language', $values, NULL);
@@ -576,7 +599,7 @@ public function parseActionSchedule($values) {
$params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
}
- $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
+ $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
if ($params['mode'] == 'Email' || empty($params['sms_provider_id'])) {
unset($modePrefixes['SMS']);
@@ -587,17 +610,17 @@ public function parseActionSchedule($values) {
//TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes
- $composeFields = array(
+ $composeFields = [
'template',
'saveTemplate',
'updateTemplate',
'saveTemplateName',
- );
+ ];
$msgTemplate = NULL;
//mail template is composed
foreach ($modePrefixes as $prefix) {
- $composeParams = array();
+ $composeParams = [];
foreach ($composeFields as $key) {
$key = $prefix . $key;
if (!empty($values[$key])) {
@@ -606,19 +629,19 @@ public function parseActionSchedule($values) {
}
if (!empty($composeParams[$prefix . 'updateTemplate'])) {
- $templateParams = array('is_active' => TRUE);
+ $templateParams = ['is_active' => TRUE];
if ($prefix == 'SMS') {
- $templateParams += array(
+ $templateParams += [
'msg_text' => $params['sms_body_text'],
'is_sms' => TRUE,
- );
+ ];
}
else {
- $templateParams += array(
+ $templateParams += [
'msg_text' => $params['body_text'],
'msg_html' => $params['body_html'],
'msg_subject' => $params['subject'],
- );
+ ];
}
$templateParams['id'] = $values[$prefix . 'template'];
@@ -626,19 +649,19 @@ public function parseActionSchedule($values) {
}
if (!empty($composeParams[$prefix . 'saveTemplate'])) {
- $templateParams = array('is_active' => TRUE);
+ $templateParams = ['is_active' => TRUE];
if ($prefix == 'SMS') {
- $templateParams += array(
+ $templateParams += [
'msg_text' => $params['sms_body_text'],
'is_sms' => TRUE,
- );
+ ];
}
else {
- $templateParams += array(
+ $templateParams += [
'msg_text' => $params['body_text'],
'msg_html' => $params['body_html'],
'msg_subject' => $params['subject'],
- );
+ ];
}
$templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
diff --git a/CRM/Admin/Form/Setting.php b/CRM/Admin/Form/Setting.php
index 89e2574084d2..e0be4241a38e 100644
--- a/CRM/Admin/Form/Setting.php
+++ b/CRM/Admin/Form/Setting.php
@@ -1,9 +1,9 @@
_defaults) {
- $this->_defaults = array();
- $formArray = array('Component', 'Localization');
+ $this->_defaults = [];
+ $formArray = ['Component', 'Localization'];
$formMode = FALSE;
if (in_array($this->_name, $formArray)) {
$formMode = TRUE;
}
- CRM_Core_BAO_ConfigSetting::retrieve($this->_defaults);
+ $this->setDefaultsForMetadataDefinedFields();
- // we can handle all the ones defined in the metadata here. Others to be converted
- foreach ($this->_settings as $setting => $group) {
- $this->_defaults[$setting] = civicrm_api('setting', 'getvalue', array(
- 'version' => 3,
- 'name' => $setting,
- 'group' => $group,
- )
- );
- }
-
- $this->_defaults['contact_autocomplete_options'] = self::getAutocompleteContactSearch();
- $this->_defaults['contact_reference_options'] = self::getAutocompleteContactReference();
+ // @todo these should be retrievable from the above function.
$this->_defaults['enableSSL'] = Civi::settings()->get('enableSSL');
$this->_defaults['verifySSL'] = Civi::settings()->get('verifySSL');
$this->_defaults['environment'] = CRM_Core_Config::environment();
@@ -80,85 +73,23 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $descriptions = array();
- $settingMetaData = $this->getSettingsMetaData();
- foreach ($settingMetaData as $setting => $props) {
- if (isset($props['quick_form_type'])) {
- if (isset($props['pseudoconstant'])) {
- $options = civicrm_api3('Setting', 'getoptions', array(
- 'field' => $setting,
- ));
- }
- else {
- $options = NULL;
- }
-
- $add = 'add' . $props['quick_form_type'];
- if ($add == 'addElement') {
- $this->$add(
- $props['html_type'],
- $setting,
- ts($props['title']),
- ($options !== NULL) ? $options['values'] : CRM_Utils_Array::value('html_attributes', $props, array()),
- ($options !== NULL) ? CRM_Utils_Array::value('html_attributes', $props, array()) : NULL
- );
- }
- elseif ($add == 'addSelect') {
- $this->addElement('select', $setting, ts($props['title']), $options['values'], CRM_Utils_Array::value('html_attributes', $props));
- }
- elseif ($add == 'addCheckBox') {
- $this->addCheckBox($setting, ts($props['title']), $options['values'], NULL, CRM_Utils_Array::value('html_attributes', $props), NULL, NULL, array(' '));
- }
- elseif ($add == 'addChainSelect') {
- $this->addChainSelect($setting, array(
- 'label' => ts($props['title']),
- ));
- }
- elseif ($add == 'addMonthDay') {
- $this->add('date', $setting, ts($props['title']), CRM_Core_SelectValues::date(NULL, 'M d'));
- }
- else {
- $this->$add($setting, ts($props['title']));
- }
- // Migrate to using an array as easier in smart...
- $descriptions[$setting] = ts($props['description']);
- $this->assign("{$setting}_description", ts($props['description']));
- if ($setting == 'max_attachments') {
- //temp hack @todo fix to get from metadata
- $this->addRule('max_attachments', ts('Value should be a positive number'), 'positiveInteger');
- }
- if ($setting == 'maxFileSize') {
- //temp hack
- $this->addRule('maxFileSize', ts('Value should be a positive number'), 'positiveInteger');
- }
-
- }
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFieldsDefinedInSettingsMetadata();
+
+ if ($this->includesReadOnlyFields) {
+ CRM_Core_Session::setStatus(ts("Some fields are loaded as 'readonly' as they have been set (overridden) in civicrm.settings.php."), '', 'info', ['expires' => 0]);
}
- // setting_description should be deprecated - see Mail.tpl for metadata based tpl.
- $this->assign('setting_descriptions', $descriptions);
- $this->assign('settings_fields', $settingMetaData);
- }
-
- /**
- * Get default entity.
- *
- * @return string
- */
- public function getDefaultEntity() {
- return 'Setting';
}
/**
@@ -177,54 +108,42 @@ public function postProcess() {
* @todo Document what I do.
*
* @param array $params
+ * @throws \CRM_Core_Exception
*/
public function commonProcess(&$params) {
- // save autocomplete search options
- if (!empty($params['contact_autocomplete_options'])) {
- Civi::settings()->set('contact_autocomplete_options',
- CRM_Utils_Array::implodePadded(array_keys($params['contact_autocomplete_options'])));
- unset($params['contact_autocomplete_options']);
- }
-
- // save autocomplete contact reference options
- if (!empty($params['contact_reference_options'])) {
- Civi::settings()->set('contact_reference_options',
- CRM_Utils_Array::implodePadded(array_keys($params['contact_reference_options'])));
- unset($params['contact_reference_options']);
- }
-
// save components to be enabled
if (array_key_exists('enableComponents', $params)) {
- civicrm_api3('setting', 'create', array(
+ civicrm_api3('setting', 'create', [
'enable_components' => $params['enableComponents'],
- ));
+ ]);
unset($params['enableComponents']);
}
- foreach (array('verifySSL', 'enableSSL') as $name) {
+ foreach (['verifySSL', 'enableSSL'] as $name) {
if (isset($params[$name])) {
Civi::settings()->set($name, $params[$name]);
unset($params[$name]);
}
}
- $settings = array_intersect_key($params, $this->_settings);
- $result = civicrm_api('setting', 'create', $settings + array('version' => 3));
- foreach ($settings as $setting => $settingGroup) {
- //@todo array_diff this
- unset($params[$setting]);
+ try {
+ $settings = $this->getSettingsToSetByMetadata($params);
+ $this->saveMetadataDefinedSettings($params);
}
- if (!empty($result['error_message'])) {
- CRM_Core_Session::setStatus($result['error_message'], ts('Save Failed'), 'error');
+ catch (CiviCRM_API3_Exception $e) {
+ CRM_Core_Session::setStatus($e->getMessage(), ts('Save Failed'), 'error');
}
- //CRM_Core_BAO_ConfigSetting::create($params);
+ $this->filterParamsSetByMetadata($params);
+
$params = CRM_Core_BAO_ConfigSetting::filterSkipVars($params);
if (!empty($params)) {
- CRM_Core_Error::fatal('Unrecognized setting. This may be a config field which has not been properly migrated to a setting. (' . implode(', ', array_keys($params)) . ')');
+ throw new CRM_Core_Exception('Unrecognized setting. This may be a config field which has not been properly migrated to a setting. (' . implode(', ', array_keys($params)) . ')');
}
CRM_Core_Config::clearDBCache();
+ // This doesn't make a lot of sense to me, but it maintains pre-existing behavior.
+ Civi::cache('session')->clear();
CRM_Utils_System::flushCache();
CRM_Core_Resources::singleton()->resetCacheCode();
@@ -243,64 +162,4 @@ public function rebuildMenu() {
@unlink($configFile);
}
- /**
- * Ugh, this shouldn't exist.
- *
- * Get the selected values of "contact_reference_options" formatted for checkboxes.
- *
- * @return array
- */
- public static function getAutocompleteContactReference() {
- $cRlist = array_flip(CRM_Core_OptionGroup::values('contact_reference_options',
- FALSE, FALSE, TRUE, NULL, 'name'
- ));
- $cRlistEnabled = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
- 'contact_reference_options'
- );
- $cRSearchFields = array();
- if (!empty($cRlist) && !empty($cRlistEnabled)) {
- $cRSearchFields = array_combine($cRlist, $cRlistEnabled);
- }
- return array(
- '1' => 1,
- ) + $cRSearchFields;
- }
-
- /**
- * Ugh, this shouldn't exist.
- *
- * Get the selected values of "contact_autocomplete_options" formatted for checkboxes.
- *
- * @return array
- */
- public static function getAutocompleteContactSearch() {
- $list = array_flip(CRM_Core_OptionGroup::values('contact_autocomplete_options',
- FALSE, FALSE, TRUE, NULL, 'name'
- ));
- $listEnabled = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
- 'contact_autocomplete_options'
- );
- $autoSearchFields = array();
- if (!empty($list) && !empty($listEnabled)) {
- $autoSearchFields = array_combine($list, $listEnabled);
- }
- //Set defaults for autocomplete and contact reference options
- return array(
- '1' => 1,
- ) + $autoSearchFields;
- }
-
- /**
- * Get the metadata relating to the settings on the form, ordered by the keys in $this->_settings.
- *
- * @return array
- */
- protected function getSettingsMetaData() {
- $allSettingMetaData = civicrm_api3('setting', 'getfields', array());
- $settingMetaData = array_intersect_key($allSettingMetaData['values'], $this->_settings);
- // This array_merge re-orders to the key order of $this->_settings.
- $settingMetaData = array_merge($this->_settings, $settingMetaData);
- return $settingMetaData;
- }
-
}
diff --git a/CRM/Admin/Form/Setting/Case.php b/CRM/Admin/Form/Setting/Case.php
index d530c87e530e..242c93adcdcd 100644
--- a/CRM/Admin/Form/Setting/Case.php
+++ b/CRM/Admin/Form/Setting/Case.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'civicaseAllowMultipleClients' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'civicaseNaturalActivityTypeSort' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'civicaseActivityRevisions' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
diff --git a/CRM/Admin/Form/Setting/Component.php b/CRM/Admin/Form/Setting/Component.php
index 4a45be0e23bc..f64cf081e761 100644
--- a/CRM/Admin/Form/Setting/Component.php
+++ b/CRM/Admin/Form/Setting/Component.php
@@ -1,9 +1,9 @@
_getComponentSelectValues();
$include = &$this->addElement('advmultiselect', 'enableComponents',
ts('Components') . ' ', $components,
- array(
+ [
'size' => 5,
'style' => 'width:150px',
'class' => 'advmultiselect',
- )
+ ]
);
- $include->setButtonAttributes('add', array('value' => ts('Enable >>')));
- $include->setButtonAttributes('remove', array('value' => ts('<< Disable')));
+ $include->setButtonAttributes('add', ['value' => ts('Enable >>')]);
+ $include->setButtonAttributes('remove', ['value' => ts('<< Disable')]);
- $this->addFormRule(array('CRM_Admin_Form_Setting_Component', 'formRule'), $this);
+ $this->addFormRule(['CRM_Admin_Form_Setting_Component', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -74,7 +74,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $options) {
- $errors = array();
+ $errors = [];
if (array_key_exists('enableComponents', $fields) && is_array($fields['enableComponents'])) {
if (in_array('CiviPledge', $fields['enableComponents']) &&
@@ -96,7 +96,7 @@ public static function formRule($fields, $files, $options) {
* @return array
*/
private function _getComponentSelectValues() {
- $ret = array();
+ $ret = [];
$this->_components = CRM_Core_Component::getComponents();
foreach ($this->_components as $name => $object) {
$ret[$name] = $object->info['translatedName'];
diff --git a/CRM/Admin/Form/Setting/Date.php b/CRM/Admin/Form/Setting/Date.php
index ae510be0965d..cd8d5976e60b 100644
--- a/CRM/Admin/Form/Setting/Date.php
+++ b/CRM/Admin/Form/Setting/Date.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'dateformatFull' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'dateformatPartial' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
@@ -48,7 +48,7 @@ class CRM_Admin_Form_Setting_Date extends CRM_Admin_Form_Setting {
'dateInputFormat' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'timeInputFormat' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'fiscalYearStart' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
diff --git a/CRM/Admin/Form/Setting/Debugging.php b/CRM/Admin/Form/Setting/Debugging.php
index 40d95b0ee7bd..133ed57a9dc6 100644
--- a/CRM/Admin/Form/Setting/Debugging.php
+++ b/CRM/Admin/Form/Setting/Debugging.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::DEVELOPER_PREFERENCES_NAME,
'backtrace' => CRM_Core_BAO_Setting::DEVELOPER_PREFERENCES_NAME,
'fatalErrorHandler' => CRM_Core_BAO_Setting::DEVELOPER_PREFERENCES_NAME,
'assetCache' => CRM_Core_BAO_Setting::DEVELOPER_PREFERENCES_NAME,
'environment' => CRM_Core_BAO_Setting::DEVELOPER_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
diff --git a/CRM/Admin/Form/Setting/Localization.php b/CRM/Admin/Form/Setting/Localization.php
index 21cd8f8a3a49..2940f4136fa6 100644
--- a/CRM/Admin/Form/Setting/Localization.php
+++ b/CRM/Admin/Form/Setting/Localization.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'countryLimit' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'customTranslateFunction' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
@@ -52,7 +52,15 @@ class CRM_Admin_Form_Setting_Localization extends CRM_Admin_Form_Setting {
'moneyformat' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'moneyvalueformat' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
'provinceLimit' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
- );
+ 'uiLanguages' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
+ ];
+
+ public function preProcess() {
+ if (!CRM_Core_I18n::isMultiLingual()) {
+ CRM_Core_Resources::singleton()
+ ->addScriptFile('civicrm', 'templates/CRM/Admin/Form/Setting/Localization.js', 1, 'html-header');
+ }
+ }
/**
* Build the form object.
@@ -65,20 +73,17 @@ public function buildQuickForm() {
$warningTitle = json_encode(ts("Warning"));
$defaultLocaleOptions = CRM_Admin_Form_Setting_Localization::getDefaultLocaleOptions();
- $domain = new CRM_Core_DAO_Domain();
- $domain->find(TRUE);
-
- if ($domain->locales) {
+ if (CRM_Core_I18n::isMultiLingual()) {
// add language limiter and language adder
$this->addCheckBox('languageLimit', ts('Available Languages'), array_flip($defaultLocaleOptions), NULL, NULL, NULL, NULL, ' ');
- $this->addElement('select', 'addLanguage', ts('Add Language'), array_merge(array('' => ts('- select -')), array_diff(CRM_Core_I18n::languages(), $defaultLocaleOptions)));
+ $this->addElement('select', 'addLanguage', ts('Add Language'), array_merge(['' => ts('- select -')], array_diff(CRM_Core_I18n::languages(), $defaultLocaleOptions)));
// add the ability to return to single language
$warning = ts('This will make your CiviCRM installation a single-language one again. THIS WILL DELETE ALL DATA RELATED TO LANGUAGES OTHER THAN THE DEFAULT ONE SELECTED ABOVE (and only that language will be preserved).');
$this->assign('warning', $warning);
$warning = json_encode($warning);
$this->addElement('checkbox', 'makeSinglelingual', ts('Return to Single Language'),
- NULL, array('onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)")
+ NULL, ['onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)"]
);
}
else {
@@ -91,7 +96,7 @@ public function buildQuickForm() {
!\Civi::settings()->get('logging')
) {
$this->addElement('checkbox', 'makeMultilingual', ts('Enable Multiple Languages'),
- NULL, array('onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)")
+ NULL, ['onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)"]
);
}
}
@@ -100,17 +105,17 @@ public function buildQuickForm() {
$includeCurrency = &$this->addElement('advmultiselect', 'currencyLimit',
ts('Available Currencies') . ' ', self::getCurrencySymbols(),
- array(
+ [
'size' => 5,
'style' => 'width:150px',
'class' => 'advmultiselect',
- )
+ ]
);
- $includeCurrency->setButtonAttributes('add', array('value' => ts('Add >>')));
- $includeCurrency->setButtonAttributes('remove', array('value' => ts('<< Remove')));
+ $includeCurrency->setButtonAttributes('add', ['value' => ts('Add >>')]);
+ $includeCurrency->setButtonAttributes('remove', ['value' => ts('<< Remove')]);
- $this->addFormRule(array('CRM_Admin_Form_Setting_Localization', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Setting_Localization', 'formRule']);
parent::buildQuickForm();
}
@@ -121,7 +126,7 @@ public function buildQuickForm() {
* @return array|bool
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
if (CRM_Utils_Array::value('monetaryThousandSeparator', $fields) ==
CRM_Utils_Array::value('monetaryDecimalPoint', $fields)
) {
@@ -194,7 +199,7 @@ public function postProcess() {
// save enabled currencies and default currency in option group 'currencies_enabled'
// CRM-1496
if (empty($values['currencyLimit'])) {
- $values['currencyLimit'] = array($values['defaultCurrency']);
+ $values['currencyLimit'] = [$values['defaultCurrency']];
}
elseif (!in_array($values['defaultCurrency'], $values['currencyLimit'])) {
$values['currencyLimit'][] = $values['defaultCurrency'];
@@ -226,6 +231,11 @@ public function postProcess() {
$values['languageLimit'][$values['addLanguage']] = 1;
}
+ // current language should be in the ui list
+ if (!in_array($values['lcMessages'], $values['uiLanguages'])) {
+ $values['uiLanguages'][] = $values['lcMessages'];
+ }
+
// if we manipulated the language list, return to the localization admin screen
$return = (bool) (CRM_Utils_Array::value('makeMultilingual', $values) or CRM_Utils_Array::value('addLanguage', $values));
@@ -245,7 +255,6 @@ public function postProcess() {
}
}
-
/**
* Replace available currencies by the ones provided
*
@@ -258,17 +267,17 @@ public static function updateEnabledCurrencies($currencies, $default) {
sort($currencies);
// get labels for all the currencies
- $options = array();
+ $options = [];
$currencySymbols = CRM_Admin_Form_Setting_Localization::getCurrencySymbols();
for ($i = 0; $i < count($currencies); $i++) {
- $options[] = array(
+ $options[] = [
'label' => $currencySymbols[$currencies[$i]],
'value' => $currencies[$i],
'weight' => $i + 1,
'is_active' => 1,
'is_default' => $currencies[$i] == $default,
- );
+ ];
}
$dontCare = NULL;
@@ -276,15 +285,14 @@ public static function updateEnabledCurrencies($currencies, $default) {
}
-
/**
* @return array
*/
public static function getAvailableCountries() {
$i18n = CRM_Core_I18n::singleton();
- $country = array();
+ $country = [];
CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
- $i18n->localizeArray($country, array('context' => 'country'));
+ $i18n->localizeArray($country, ['context' => 'country']);
asort($country);
return $country;
}
@@ -300,7 +308,7 @@ public static function getDefaultLocaleOptions() {
$locales = CRM_Core_I18n::languages();
if ($domain->locales) {
// for multi-lingual sites, populate default language drop-down with available languages
- $defaultLocaleOptions = array();
+ $defaultLocaleOptions = [];
foreach ($locales as $loc => $lang) {
if (substr_count($domain->locales, $loc)) {
$defaultLocaleOptions[$loc] = $lang;
@@ -320,11 +328,11 @@ public static function getDefaultLocaleOptions() {
* Array('USD' => 'USD ($)').
*/
public static function getCurrencySymbols() {
- $symbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', array(
+ $symbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
'labelColumn' => 'symbol',
'orderColumn' => TRUE,
- ));
- $_currencySymbols = array();
+ ]);
+ $_currencySymbols = [];
foreach ($symbols as $key => $value) {
$_currencySymbols[$key] = "$key";
if ($value) {
@@ -368,7 +376,7 @@ public static function onChangeDefaultCurrency($oldCurrency, $newCurrency, $meta
$currencies = array_keys(CRM_Core_OptionGroup::values('currencies_enabled'));
if (!in_array($newCurrency, $currencies)) {
if (empty($currencies)) {
- $currencies = array($values['defaultCurrency']);
+ $currencies = [$values['defaultCurrency']];
}
else {
$currencies[] = $newCurrency;
@@ -383,11 +391,11 @@ public static function onChangeDefaultCurrency($oldCurrency, $newCurrency, $meta
* @return array
*/
public static function getDefaultLanguageOptions() {
- return array(
+ return [
'*default*' => ts('Use default site language'),
'undefined' => ts('Leave undefined'),
'current_site_language' => ts('Use language in use at the time'),
- );
+ ];
}
}
diff --git a/CRM/Admin/Form/Setting/Mail.php b/CRM/Admin/Form/Setting/Mail.php
index 83679cabe9b7..bd75e95a8381 100644
--- a/CRM/Admin/Form/Setting/Mail.php
+++ b/CRM/Admin/Form/Setting/Mail.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'mailThrottleTime' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'mailerJobSize' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'mailerJobsMax' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'verpSeparator' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'replyTo' => CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Settings - CiviMail'));
- $this->addFormRule(array('CRM_Admin_Form_Setting_Mail', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Setting_Mail', 'formRule']);
parent::buildQuickForm();
}
@@ -61,7 +61,7 @@ public function buildQuickForm() {
* @return array|bool
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
if (CRM_Utils_Array::value('mailerJobSize', $fields) > 0) {
if (CRM_Utils_Array::value('mailerJobSize', $fields) < 1000) {
diff --git a/CRM/Admin/Form/Setting/Mapping.php b/CRM/Admin/Form/Setting/Mapping.php
index 9e6ac247f076..2d71f739df02 100644
--- a/CRM/Admin/Form/Setting/Mapping.php
+++ b/CRM/Admin/Form/Setting/Mapping.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::MAP_PREFERENCES_NAME,
'mapProvider' => CRM_Core_BAO_Setting::MAP_PREFERENCES_NAME,
'geoAPIKey' => CRM_Core_BAO_Setting::MAP_PREFERENCES_NAME,
'geoProvider' => CRM_Core_BAO_Setting::MAP_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
@@ -61,7 +61,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
if (!CRM_Utils_System::checkPHPVersion(5, FALSE)) {
$errors['_qf_default'] = ts('Mapping features require PHP version 5 or greater');
@@ -84,7 +84,7 @@ public static function formRule($fields) {
* All local rules are added near the element
*/
public function addRules() {
- $this->addFormRule(array('CRM_Admin_Form_Setting_Mapping', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Setting_Mapping', 'formRule']);
}
}
diff --git a/CRM/Admin/Form/Setting/Miscellaneous.php b/CRM/Admin/Form/Setting/Miscellaneous.php
index 6f9b6457e465..8b92a4b411f5 100644
--- a/CRM/Admin/Form/Setting/Miscellaneous.php
+++ b/CRM/Admin/Form/Setting/Miscellaneous.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_undelete' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'empoweredBy' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
@@ -49,12 +49,15 @@ class CRM_Admin_Form_Setting_Miscellaneous extends CRM_Admin_Form_Setting {
'recaptchaOptions' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'recaptchaPublicKey' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'recaptchaPrivateKey' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'forceRecaptcha' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'wkhtmltopdfPath' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'recentItemsMaxCount' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'recentItemsProviders' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'dedupe_default_limit' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'remote_profile_submissions' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
- );
+ 'allow_alert_autodismissal' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'prevNextBackend' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
+ ];
public $_uploadMaxSize;
@@ -67,7 +70,7 @@ public function preProcess() {
CRM_Utils_Number::formatUnitSize(ini_get('post_max_size'), TRUE);
// This is a temp hack for the fact we really don't need to hard-code each setting in the tpl but
// we haven't worked through NOT doing that. These settings have been un-hardcoded.
- $this->assign('pure_config_settings', array(
+ $this->assign('pure_config_settings', [
'empoweredBy',
'max_attachments',
'maxFileSize',
@@ -75,7 +78,8 @@ public function preProcess() {
'recentItemsMaxCount',
'recentItemsProviders',
'dedupe_default_limit',
- ));
+ 'prevNextBackend',
+ ]);
}
/**
@@ -86,7 +90,7 @@ public function buildQuickForm() {
$this->assign('validTriggerPermission', CRM_Core_DAO::checkTriggerViewPermission(FALSE));
- $this->addFormRule(array('CRM_Admin_Form_Setting_Miscellaneous', 'formRule'), $this);
+ $this->addFormRule(['CRM_Admin_Form_Setting_Miscellaneous', 'formRule'], $this);
parent::buildQuickForm();
$this->addRule('checksum_timeout', ts('Value should be a positive number'), 'positiveInteger');
@@ -106,7 +110,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $options) {
- $errors = array();
+ $errors = [];
// validate max file size
if ($fields['maxFileSize'] > $options->_uploadMaxSize) {
@@ -115,7 +119,7 @@ public static function formRule($fields, $files, $options) {
// validate recent items stack size
if ($fields['recentItemsMaxCount'] && ($fields['recentItemsMaxCount'] < 1 || $fields['recentItemsMaxCount'] > CRM_Utils_Recent::MAX_ITEMS)) {
- $errors['recentItemsMaxCount'] = ts("Illegal stack size. Use values between 1 and %1.", array(1 => CRM_Utils_Recent::MAX_ITEMS));
+ $errors['recentItemsMaxCount'] = ts("Illegal stack size. Use values between 1 and %1.", [1 => CRM_Utils_Recent::MAX_ITEMS]);
}
if (!empty($fields['wkhtmltopdfPath'])) {
diff --git a/CRM/Admin/Form/Setting/Path.php b/CRM/Admin/Form/Setting/Path.php
index edb8e959bf2f..b83c52706748 100644
--- a/CRM/Admin/Form/Setting/Path.php
+++ b/CRM/Admin/Form/Setting/Path.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
'imageUploadDir' => CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
'customFileUploadDir' => CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
'customTemplateDir' => CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
'customPHPPathDir' => CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
'extensionsDir' => CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
@@ -52,19 +52,19 @@ public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Settings - Upload Directories'));
parent::buildQuickForm();
- $directories = array(
+ $directories = [
'uploadDir' => ts('Temporary Files'),
'imageUploadDir' => ts('Images'),
'customFileUploadDir' => ts('Custom Files'),
'customTemplateDir' => ts('Custom Templates'),
'customPHPPathDir' => ts('Custom PHP Path Directory'),
'extensionsDir' => ts('CiviCRM Extensions Directory'),
- );
+ ];
foreach ($directories as $name => $title) {
//$this->add('text', $name, $title);
$this->addRule($name,
ts("'%1' directory does not exist",
- array(1 => $title)
+ [1 => $title]
),
'settingPath'
);
diff --git a/CRM/Admin/Form/Setting/Search.php b/CRM/Admin/Form/Setting/Search.php
index 5d4a3b2245c5..95cab96824fe 100644
--- a/CRM/Admin/Form/Setting/Search.php
+++ b/CRM/Admin/Form/Setting/Search.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
- 'contact_autocomplete_options' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
+ protected $_settings = [
+ 'contact_reference_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'contact_autocomplete_options' => CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'search_autocomplete_count' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
'enable_innodb_fts' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
'includeWildCardInName' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
@@ -50,7 +50,8 @@ class CRM_Admin_Form_Setting_Search extends CRM_Admin_Form_Setting {
'smartGroupCacheTimeout' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
'defaultSearchProfileID' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
'searchPrimaryDetailsOnly' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
- );
+ 'quicksearch_options' => CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME,
+ ];
/**
* Build the form object.
@@ -69,40 +70,36 @@ public function buildQuickForm() {
// Autocomplete for Contact Reference (custom fields)
$element = $this->getElement('contact_reference_options');
$element->_elements[0]->_flagFrozen = TRUE;
+
+ // Freeze first element of quicksearch options
+ $element = $this->getElement('quicksearch_options');
+ $element->_elements[0]->_flagFrozen = TRUE;
}
/**
* @return array
*/
public static function getContactAutocompleteOptions() {
- return array(
- ts('Contact Name') => 1,
- ) + array_flip(CRM_Core_OptionGroup::values('contact_autocomplete_options',
- FALSE, FALSE, TRUE
- ));
+ return [1 => ts('Contact Name')] + CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, TRUE);
}
/**
* @return array
*/
public static function getAvailableProfiles() {
- return array('' => ts('- none -')) + CRM_Core_BAO_UFGroup::getProfiles(array(
+ return ['' => ts('- none -')] + CRM_Core_BAO_UFGroup::getProfiles([
'Contact',
'Individual',
'Organization',
'Household',
- ));
+ ]);
}
/**
* @return array
*/
public static function getContactReferenceOptions() {
- return array(
- ts('Contact Name') => 1,
- ) + array_flip(CRM_Core_OptionGroup::values('contact_reference_options',
- FALSE, FALSE, TRUE
- ));
+ return [1 => ts('Contact Name')] + CRM_Core_OptionGroup::values('contact_reference_options', FALSE, FALSE, TRUE);
}
}
diff --git a/CRM/Admin/Form/Setting/Smtp.php b/CRM/Admin/Form/Setting/Smtp.php
index 84c872828797..e70260e63f77 100644
--- a/CRM/Admin/Form/Setting/Smtp.php
+++ b/CRM/Admin/Form/Setting/Smtp.php
@@ -1,9 +1,9 @@
ts('mail()'),
CRM_Mailing_Config::OUTBOUND_OPTION_SMTP => ts('SMTP'),
CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL => ts('Sendmail'),
CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED => ts('Disable Outbound Email'),
CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB => ts('Redirect to Database'),
- );
+ ];
$this->addRadio('outBound_option', ts('Select Mailer'), $outBoundOption);
CRM_Utils_System::setTitle(ts('Settings - Outbound Mail'));
+ $this->add('checkbox', 'allow_mail_from_logged_in_contact', ts('Allow Mail to be sent from logged in contact\'s email address'));
$this->add('text', 'sendmail_path', ts('Sendmail Path'));
$this->add('text', 'sendmail_args', ts('Sendmail Argument'));
$this->add('text', 'smtpServer', ts('SMTP Server'));
@@ -62,10 +63,10 @@ public function buildQuickForm() {
$this->_testButtonName = $this->getButtonName('refresh', 'test');
- $this->addFormRule(array('CRM_Admin_Form_Setting_Smtp', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Setting_Smtp', 'formRule']);
parent::buildQuickForm();
$buttons = $this->getElement('buttons')->getElements();
- $buttons[] = $this->createElement('submit', $this->_testButtonName, ts('Save & Send Test Email'), array('crm-icon' => 'fa-envelope-o'));
+ $buttons[] = $this->createElement('submit', $this->_testButtonName, ts('Save & Send Test Email'), ['crm-icon' => 'fa-envelope-o']);
$this->getElement('buttons')->setElements($buttons);
}
@@ -79,6 +80,9 @@ public function postProcess() {
$formValues = $this->controller->exportValues($this->_name);
+ Civi::settings()->set('allow_mail_from_logged_in_contact', (!empty($formValues['allow_mail_from_logged_in_contact'])));
+ unset($formValues['allow_mail_from_logged_in_contact']);
+
$buttonName = $this->controller->getButtonName();
// check if test button
if ($buttonName == $this->_testButtonName) {
@@ -98,7 +102,7 @@ public function postProcess() {
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]));
}
if (!$toEmail) {
@@ -111,12 +115,11 @@ public function postProcess() {
$to = '"' . $toDisplayName . '"' . "<$toEmail>";
$from = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
- $testMailStatusMsg = ts('Sending test email. FROM: %1 TO: %2. ', array(
- 1 => $domainEmailAddress,
- 2 => $toEmail,
- ));
+ $testMailStatusMsg = ts('Sending test email') . ': '
+ . ts('From: %1', [1 => $domainEmailAddress]) . ' '
+ . ts('To: %1', [1 => $toEmail]) . ' ';
- $params = array();
+ $params = [];
if ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
$subject = "Test for SMTP settings";
$message = "SMTP settings are correct.";
@@ -155,26 +158,29 @@ public function postProcess() {
$mailerName = 'mail';
}
- $headers = array(
+ $headers = [
'From' => $from,
'To' => $to,
'Subject' => $subject,
- );
+ ];
$mailer = Mail::factory($mailerName, $params);
$errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
$result = $mailer->send($toEmail, $headers, $message);
unset($errorScope);
- if (defined('CIVICRM_MAIL_LOG')) {
- CRM_Core_Session::setStatus($testMailStatusMsg . ts('You have defined CIVICRM_MAIL_LOG - no mail will be sent. Your %1 settings have not been tested.', array(1 => strtoupper($mailerName))), ts("Mail not sent"), "warning");
+ if (defined('CIVICRM_MAIL_LOG') && defined('CIVICRM_MAIL_LOG_AND_SEND')) {
+ $testMailStatusMsg .= ' ' . ts('You have defined CIVICRM_MAIL_LOG_AND_SEND - mail will be logged.') . '
';
+ }
+ if (defined('CIVICRM_MAIL_LOG') && !defined('CIVICRM_MAIL_LOG_AND_SEND')) {
+ CRM_Core_Session::setStatus($testMailStatusMsg . ts('You have defined CIVICRM_MAIL_LOG - no mail will be sent. Your %1 settings have not been tested.', [1 => strtoupper($mailerName)]), ts("Mail not sent"), "warning");
}
elseif (!is_a($result, 'PEAR_Error')) {
- CRM_Core_Session::setStatus($testMailStatusMsg . ts('Your %1 settings are correct. A test email has been sent to your email address.', array(1 => strtoupper($mailerName))), ts("Mail Sent"), "success");
+ CRM_Core_Session::setStatus($testMailStatusMsg . ts('Your %1 settings are correct. A test email has been sent to your email address.', [1 => strtoupper($mailerName)]), ts("Mail Sent"), "success");
}
else {
$message = CRM_Utils_Mail::errorMessage($mailer, $result);
- CRM_Core_Session::setStatus($testMailStatusMsg . ts('Oops. Your %1 settings are incorrect. No test mail has been sent.', array(1 => strtoupper($mailerName))) . $message, ts("Mail Not Sent"), "error");
+ CRM_Core_Session::setStatus($testMailStatusMsg . ts('Oops. Your %1 settings are incorrect. No test mail has been sent.', [1 => strtoupper($mailerName)]) . $message, ts("Mail Not Sent"), "error");
}
}
}
@@ -236,7 +242,7 @@ public static function formRule($fields) {
*/
public function setDefaultValues() {
if (!$this->_defaults) {
- $this->_defaults = array();
+ $this->_defaults = [];
$mailingBackend = Civi::settings()->get('mailing_backend');
if (!empty($mailingBackend)) {
@@ -259,6 +265,7 @@ public function setDefaultValues() {
}
}
}
+ $this->_defaults['allow_mail_from_logged_in_contact'] = Civi::settings()->get('allow_mail_from_logged_in_contact');
return $this->_defaults;
}
diff --git a/CRM/Admin/Form/Setting/UF.php b/CRM/Admin/Form/Setting/UF.php
index ab290514d38b..efb8e9a44fbb 100644
--- a/CRM/Admin/Form/Setting/UF.php
+++ b/CRM/Admin/Form/Setting/UF.php
@@ -1,9 +1,9 @@
$this->_uf))
+ ts('Settings - %1 Integration', [1 => $this->_uf])
);
if ($config->userSystem->is_drupal) {
@@ -82,7 +82,11 @@ function_exists('module_exists') &&
$dsnArray = DB::parseDSN($config->dsn);
$tableNames = CRM_Core_DAO::getTableNames();
$tablePrefixes = '$databases[\'default\'][\'default\'][\'prefix\']= array(';
- $tablePrefixes .= "\n 'default' => '$drupal_prefix',"; // add default prefix: the drupal database prefix
+ if ($config->userFramework === 'Backdrop') {
+ $tablePrefixes = '$database_prefix = array(';
+ }
+ // add default prefix: the drupal database prefix
+ $tablePrefixes .= "\n 'default' => '$drupal_prefix',";
$prefix = "";
if ($config->dsn != $config->userFrameworkDSN) {
$prefix = "`{$dsnArray['database']}`.";
diff --git a/CRM/Admin/Form/Setting/UpdateConfigBackend.php b/CRM/Admin/Form/Setting/UpdateConfigBackend.php
index e1b6a3627e74..d1a258738c8b 100644
--- a/CRM/Admin/Form/Setting/UpdateConfigBackend.php
+++ b/CRM/Admin/Form/Setting/UpdateConfigBackend.php
@@ -1,9 +1,9 @@
addElement(
'submit', $this->getButtonName('next', 'cleanup'), 'Cleanup Caches',
- array('class' => 'crm-form-submit', 'id' => 'cleanup-cache')
+ ['class' => 'crm-form-submit', 'id' => 'cleanup-cache']
);
$this->addElement(
'submit', $this->getButtonName('next', 'resetpaths'), 'Reset Paths',
- array('class' => 'crm-form-submit', 'id' => 'resetpaths')
+ ['class' => 'crm-form-submit', 'id' => 'resetpaths']
);
//parent::buildQuickForm();
@@ -65,6 +65,7 @@ public function postProcess() {
// clear all caches
CRM_Core_Config::clearDBCache();
+ Civi::cache('session')->clear();
CRM_Utils_System::flushCache();
parent::rebuildMenu();
diff --git a/CRM/Admin/Form/Setting/Url.php b/CRM/Admin/Form/Setting/Url.php
index b629a2b6d6c5..9d6a62245553 100644
--- a/CRM/Admin/Form/Setting/Url.php
+++ b/CRM/Admin/Form/Setting/Url.php
@@ -1,9 +1,9 @@
CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'userFrameworkResourceURL' => CRM_Core_BAO_Setting::URL_PREFERENCES_NAME,
'imageUploadURL' => CRM_Core_BAO_Setting::URL_PREFERENCES_NAME,
'customCSSURL' => CRM_Core_BAO_Setting::URL_PREFERENCES_NAME,
'extensionsURL' => CRM_Core_BAO_Setting::URL_PREFERENCES_NAME,
- );
+ ];
/**
* Build the form object.
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Settings - Resource URLs'));
- $settingFields = civicrm_api('setting', 'getfields', array(
+ $settingFields = civicrm_api('setting', 'getfields', [
'version' => 3,
- ));
+ ]);
$this->addYesNo('enableSSL', ts('Force Secure URLs (SSL)'));
$this->addYesNo('verifySSL', ts('Verify SSL Certs'));
// FIXME: verifySSL should use $_settings instead of manually adding fields
$this->assign('verifySSL_description', $settingFields['values']['verifySSL']['description']);
- $this->addFormRule(array('CRM_Admin_Form_Setting_Url', 'formRule'));
+ $this->addFormRule(['CRM_Admin_Form_Setting_Url', 'formRule']);
parent::buildQuickForm();
}
@@ -78,9 +78,9 @@ public static function formRule($fields) {
)
);
if (!CRM_Utils_System::checkURL($url, TRUE)) {
- $errors = array(
+ $errors = [
'enableSSL' => ts('You need to set up a secure server before you can use the Force Secure URLs option'),
- );
+ ];
return $errors;
}
}
diff --git a/CRM/Admin/Form/SettingTrait.php b/CRM/Admin/Form/SettingTrait.php
new file mode 100644
index 000000000000..f22470803fe6
--- /dev/null
+++ b/CRM/Admin/Form/SettingTrait.php
@@ -0,0 +1,343 @@
+_settings.
+ *
+ * @return array
+ */
+ protected function getSettingsMetaData() {
+ if (empty($this->settingsMetadata)) {
+ $allSettingMetaData = civicrm_api3('setting', 'getfields', []);
+ $this->settingsMetadata = array_intersect_key($allSettingMetaData['values'], $this->_settings);
+ // This array_merge re-orders to the key order of $this->_settings.
+ $this->settingsMetadata = array_merge($this->_settings, $this->settingsMetadata);
+ }
+ return $this->settingsMetadata;
+ }
+
+ /**
+ * Get the settings which can be stored based on metadata.
+ *
+ * @param array $params
+ * @return array
+ */
+ protected function getSettingsToSetByMetadata($params) {
+ $setValues = array_intersect_key($params, $this->_settings);
+ // Checkboxes will be unset rather than empty so we need to add them back in.
+ // Handle quickform hateability just once, right here right now.
+ $unsetValues = array_diff_key($this->_settings, $params);
+ foreach ($unsetValues as $key => $unsetValue) {
+ if ($this->getQuickFormType($this->getSettingMetadata($key)) === 'CheckBox') {
+ $setValues[$key] = [$key => 0];
+ }
+ }
+ return $setValues;
+ }
+
+ /**
+ * @param $params
+ */
+ protected function filterParamsSetByMetadata(&$params) {
+ foreach ($this->getSettingsToSetByMetadata($params) as $setting => $settingGroup) {
+ //@todo array_diff this
+ unset($params[$setting]);
+ }
+ }
+
+ /**
+ * Get the metadata for a particular field.
+ *
+ * @param $setting
+ * @return mixed
+ */
+ protected function getSettingMetadata($setting) {
+ return $this->getSettingsMetaData()[$setting];
+ }
+
+ /**
+ * Get the metadata for a particular field for a particular item.
+ *
+ * e.g get 'serialize' key, if exists, for a field.
+ *
+ * @param $setting
+ * @param $item
+ * @return mixed
+ */
+ protected function getSettingMetadataItem($setting, $item) {
+ return CRM_Utils_Array::value($item, $this->getSettingsMetaData()[$setting]);
+ }
+
+ /**
+ * @return string
+ */
+ protected function getSettingPageFilter() {
+ if (!isset($this->_filter)) {
+ // Get the last URL component without modifying the urlPath property.
+ $urlPath = array_values($this->urlPath);
+ $this->_filter = end($urlPath);
+ }
+ return $this->_filter;
+ }
+
+ /**
+ * Returns a re-keyed copy of the settings, ordered by weight.
+ *
+ * @return array
+ */
+ protected function getSettingsOrderedByWeight() {
+ $settingMetaData = $this->getSettingsMetaData();
+ $filter = $this->getSettingPageFilter();
+
+ usort($settingMetaData, function ($a, $b) use ($filter) {
+ // Handle cases in which a comparison is impossible. Such will be considered ties.
+ if (
+ // A comparison can't be made unless both setting weights are declared.
+ !isset($a['settings_pages'][$filter]['weight'], $b['settings_pages'][$filter]['weight'])
+ // A pair of settings might actually have the same weight.
+ || $a['settings_pages'][$filter]['weight'] === $b['settings_pages'][$filter]['weight']
+ ) {
+ return 0;
+ }
+
+ return $a['settings_pages'][$filter]['weight'] > $b['settings_pages'][$filter]['weight'] ? 1 : -1;
+ });
+
+ return $settingMetaData;
+ }
+
+ /**
+ * Add fields in the metadata to the template.
+ */
+ protected function addFieldsDefinedInSettingsMetadata() {
+ $settingMetaData = $this->getSettingsMetaData();
+ $descriptions = [];
+ foreach ($settingMetaData as $setting => $props) {
+ $quickFormType = $this->getQuickFormType($props);
+ if (isset($quickFormType)) {
+ $options = CRM_Utils_Array::value('options', $props);
+ if (isset($props['pseudoconstant'])) {
+ $options = civicrm_api3('Setting', 'getoptions', [
+ 'field' => $setting,
+ ])['values'];
+ if ($props['html_type'] === 'Select' && isset($props['is_required']) && $props['is_required'] === FALSE && !isset($options[''])) {
+ // If the spec specifies the field is not required add a null option.
+ // Why not if empty($props['is_required']) - basically this has been added to the spec & might not be set to TRUE
+ // when it is true.
+ $options = ['' => ts('None')] + $options;
+ }
+ }
+ if ($props['type'] === 'Boolean') {
+ $options = [$props['title'] => $props['name']];
+ }
+
+ //Load input as readonly whose values are overridden in civicrm.settings.php.
+ if (Civi::settings()->getMandatory($setting)) {
+ $props['html_attributes']['readonly'] = TRUE;
+ $this->includesReadOnlyFields = TRUE;
+ }
+
+ $add = 'add' . $quickFormType;
+ if ($add == 'addElement') {
+ $this->$add(
+ $props['html_type'],
+ $setting,
+ ts($props['title']),
+ ($options !== NULL) ? $options : CRM_Utils_Array::value('html_attributes', $props, []),
+ ($options !== NULL) ? CRM_Utils_Array::value('html_attributes', $props, []) : NULL
+ );
+ }
+ elseif ($add == 'addSelect') {
+ $this->addElement('select', $setting, ts($props['title']), $options, CRM_Utils_Array::value('html_attributes', $props));
+ }
+ elseif ($add == 'addCheckBox') {
+ $this->addCheckBox($setting, '', $options, NULL, CRM_Utils_Array::value('html_attributes', $props), NULL, NULL, [' ']);
+ }
+ elseif ($add == 'addCheckBoxes') {
+ $options = array_flip($options);
+ $newOptions = [];
+ foreach ($options as $key => $val) {
+ $newOptions[$key] = $val;
+ }
+ $this->addCheckBox($setting,
+ $props['title'],
+ $newOptions,
+ NULL, NULL, NULL, NULL,
+ [' ', ' ', ' ']
+ );
+ }
+ elseif ($add == 'addChainSelect') {
+ $this->addChainSelect($setting, [
+ 'label' => ts($props['title']),
+ ]);
+ }
+ elseif ($add == 'addMonthDay') {
+ $this->add('date', $setting, ts($props['title']), CRM_Core_SelectValues::date(NULL, 'M d'));
+ }
+ elseif ($add === 'addEntityRef') {
+ $this->$add($setting, ts($props['title']), $props['entity_reference_options']);
+ }
+ elseif ($add === 'addYesNo' && ($props['type'] === 'Boolean')) {
+ $this->addRadio($setting, ts($props['title']), [1 => 'Yes', 0 => 'No'], NULL, ' ');
+ }
+ elseif ($add === 'add') {
+ $this->add($props['html_type'], $setting, ts($props['title']), $options);
+ }
+ else {
+ $this->$add($setting, ts($props['title']), $options);
+ }
+ // Migrate to using an array as easier in smart...
+ $description = CRM_Utils_Array::value('description', $props);
+ $descriptions[$setting] = $description;
+ $this->assign("{$setting}_description", $description);
+ if ($setting == 'max_attachments') {
+ //temp hack @todo fix to get from metadata
+ $this->addRule('max_attachments', ts('Value should be a positive number'), 'positiveInteger');
+ }
+ if ($setting == 'maxFileSize') {
+ //temp hack
+ $this->addRule('maxFileSize', ts('Value should be a positive number'), 'positiveInteger');
+ }
+
+ }
+ }
+ // setting_description should be deprecated - see Mail.tpl for metadata based tpl.
+ $this->assign('setting_descriptions', $descriptions);
+ $this->assign('settings_fields', $settingMetaData);
+ $this->assign('fields', $this->getSettingsOrderedByWeight());
+ }
+
+ /**
+ * Get the quickform type for the given html type.
+ *
+ * @param array $spec
+ *
+ * @return string
+ */
+ protected function getQuickFormType($spec) {
+ if (isset($spec['quick_form_type']) &&
+ !($spec['quick_form_type'] === 'Element' && !empty($spec['html_type']))) {
+ // This is kinda transitional
+ return $spec['quick_form_type'];
+ }
+
+ // The spec for settings has been updated for consistency - we provide deprecation notices for sites that have
+ // not made this change.
+ $htmlType = $spec['html_type'];
+ if ($htmlType !== strtolower($htmlType)) {
+ CRM_Core_Error::deprecatedFunctionWarning(ts('Settings fields html_type should be lower case - see https://docs.civicrm.org/dev/en/latest/framework/setting/ - this needs to be fixed for ' . $spec['name']));
+ $htmlType = strtolower($spec['html_type']);
+ }
+ $mapping = [
+ 'checkboxes' => 'CheckBoxes',
+ 'checkbox' => 'CheckBox',
+ 'radio' => 'Radio',
+ 'select' => 'Select',
+ 'textarea' => 'Element',
+ 'text' => 'Element',
+ 'entity_reference' => 'EntityRef',
+ 'advmultiselect' => 'Element',
+ ];
+ $mapping += array_fill_keys(CRM_Core_Form::$html5Types, '');
+ return $mapping[$htmlType];
+ }
+
+ /**
+ * Get the defaults for all fields defined in the metadata.
+ *
+ * All others are pending conversion.
+ */
+ protected function setDefaultsForMetadataDefinedFields() {
+ CRM_Core_BAO_ConfigSetting::retrieve($this->_defaults);
+ foreach (array_keys($this->_settings) as $setting) {
+ $this->_defaults[$setting] = civicrm_api3('setting', 'getvalue', ['name' => $setting]);
+ $spec = $this->getSettingsMetadata()[$setting];
+ if (!empty($spec['serialize'])) {
+ $this->_defaults[$setting] = CRM_Core_DAO::unSerializeField($this->_defaults[$setting], $spec['serialize']);
+ }
+ if ($this->getQuickFormType($spec) === 'CheckBoxes') {
+ $this->_defaults[$setting] = array_fill_keys($this->_defaults[$setting], 1);
+ }
+ if ($this->getQuickFormType($spec) === 'CheckBox') {
+ $this->_defaults[$setting] = [$setting => $this->_defaults[$setting]];
+ }
+ }
+ }
+
+ /**
+ * @param $params
+ *
+ */
+ protected function saveMetadataDefinedSettings($params) {
+ $settings = $this->getSettingsToSetByMetadata($params);
+ foreach ($settings as $setting => $settingValue) {
+ if ($this->getQuickFormType($this->getSettingMetadata($setting)) === 'CheckBoxes') {
+ $settings[$setting] = array_keys($settingValue);
+ }
+ if ($this->getQuickFormType($this->getSettingMetadata($setting)) === 'CheckBox') {
+ // This will be an array with one value.
+ $settings[$setting] = (int) reset($settings[$setting]);
+ }
+ }
+ civicrm_api3('setting', 'create', $settings);
+ }
+
+}
diff --git a/CRM/Admin/Form/WordReplacements.php b/CRM/Admin/Form/WordReplacements.php
index 11c4bfbf8da5..7213107cf547 100644
--- a/CRM/Admin/Form/WordReplacements.php
+++ b/CRM/Admin/Form/WordReplacements.php
@@ -1,9 +1,9 @@
_defaults;
}
- $this->_defaults = array();
+ $this->_defaults = [];
$config = CRM_Core_Config::singleton();
$values = CRM_Core_BAO_WordReplacement::getLocaleCustomStrings($config->lcMessages);
$i = 1;
- $enableDisable = array(
+ $enableDisable = [
1 => 'enabled',
0 => 'disabled',
- );
+ ];
- $cardMatch = array('wildcardMatch', 'exactMatch');
+ $cardMatch = ['wildcardMatch', 'exactMatch'];
foreach ($enableDisable as $key => $val) {
foreach ($cardMatch as $kc => $vc) {
@@ -112,9 +112,9 @@ public function buildQuickForm() {
}
$soInstances = range(1, $this->_numStrings, 1);
- $stringOverrideInstances = array();
+ $stringOverrideInstances = [];
if ($this->_soInstance) {
- $soInstances = array($this->_soInstance);
+ $soInstances = [$this->_soInstance];
}
elseif (!empty($_POST['old'])) {
$soInstances = $stringOverrideInstances = array_keys($_POST['old']);
@@ -127,8 +127,8 @@ public function buildQuickForm() {
}
foreach ($soInstances as $instance) {
$this->addElement('checkbox', "enabled[$instance]");
- $this->add('textarea', "old[$instance]", NULL, array('rows' => 1, 'cols' => 40));
- $this->add('textarea', "new[$instance]", NULL, array('rows' => 1, 'cols' => 40));
+ $this->add('text', "old[$instance]", NULL);
+ $this->add('text', "new[$instance]", NULL);
$this->addElement('checkbox', "cb[$instance]");
}
$this->assign('numStrings', $this->_numStrings);
@@ -138,19 +138,18 @@ public function buildQuickForm() {
$this->assign('stringOverrideInstances', empty($stringOverrideInstances) ? FALSE : $stringOverrideInstances);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
- $this->addFormRule(array('CRM_Admin_Form_WordReplacements', 'formRule'), $this);
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+ $this->addFormRule(['CRM_Admin_Form_WordReplacements', 'formRule'], $this);
}
/**
@@ -163,7 +162,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values) {
- $errors = array();
+ $errors = [];
$oldValues = CRM_Utils_Array::value('old', $values);
$newValues = CRM_Utils_Array::value('new', $values);
@@ -195,32 +194,32 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$this->_numStrings = count($params['old']);
- $enabled['exactMatch'] = $enabled['wildcardMatch'] = $disabled['exactMatch'] = $disabled['wildcardMatch'] = array();
+ $enabled['exactMatch'] = $enabled['wildcardMatch'] = $disabled['exactMatch'] = $disabled['wildcardMatch'] = [];
for ($i = 1; $i <= $this->_numStrings; $i++) {
if (!empty($params['new'][$i]) && !empty($params['old'][$i])) {
if (isset($params['enabled']) && !empty($params['enabled'][$i])) {
if (!empty($params['cb']) && !empty($params['cb'][$i])) {
- $enabled['exactMatch'] += array($params['old'][$i] => $params['new'][$i]);
+ $enabled['exactMatch'] += [$params['old'][$i] => $params['new'][$i]];
}
else {
- $enabled['wildcardMatch'] += array($params['old'][$i] => $params['new'][$i]);
+ $enabled['wildcardMatch'] += [$params['old'][$i] => $params['new'][$i]];
}
}
else {
if (isset($params['cb']) && is_array($params['cb']) && array_key_exists($i, $params['cb'])) {
- $disabled['exactMatch'] += array($params['old'][$i] => $params['new'][$i]);
+ $disabled['exactMatch'] += [$params['old'][$i] => $params['new'][$i]];
}
else {
- $disabled['wildcardMatch'] += array($params['old'][$i] => $params['new'][$i]);
+ $disabled['wildcardMatch'] += [$params['old'][$i] => $params['new'][$i]];
}
}
}
}
- $overrides = array(
+ $overrides = [
'enabled' => $enabled,
'disabled' => $disabled,
- );
+ ];
$config = CRM_Core_Config::singleton();
CRM_Core_BAO_WordReplacement::setLocaleCustomStrings($config->lcMessages, $overrides);
diff --git a/CRM/Admin/Page/AJAX.php b/CRM/Admin/Page/AJAX.php
index 1aa2d5c0ad23..f782de942853 100644
--- a/CRM/Admin/Page/AJAX.php
+++ b/CRM/Admin/Page/AJAX.php
@@ -1,9 +1,9 @@
get('userID');
- if ($contactID) {
- CRM_Core_Page_AJAX::setJsHeaders();
- $smarty = CRM_Core_Smarty::singleton();
- $smarty->assign('includeEmail', civicrm_api3('setting', 'getvalue', array('name' => 'includeEmailInName', 'group' => 'Search Preferences')));
- print $smarty->fetchWith('CRM/common/navigation.js.tpl', array(
- 'navigation' => CRM_Core_BAO_Navigation::createNavigation($contactID),
- ));
+ public static function navMenu() {
+ if (CRM_Core_Session::getLoggedInContactID()) {
+
+ $menu = CRM_Core_BAO_Navigation::buildNavigationTree();
+ CRM_Core_BAO_Navigation::buildHomeMenu($menu);
+ CRM_Utils_Hook::navigationMenu($menu);
+ CRM_Core_BAO_Navigation::fixNavigationMenu($menu);
+ CRM_Core_BAO_Navigation::orderByWeight($menu);
+ CRM_Core_BAO_Navigation::filterByPermission($menu);
+ self::formatMenuItems($menu);
+
+ $output = [
+ 'menu' => $menu,
+ 'search' => CRM_Utils_Array::makeNonAssociative(self::getSearchOptions()),
+ ];
+ // Encourage browsers to cache for a long time - 1 year
+ $ttl = 60 * 60 * 24 * 364;
+ CRM_Utils_System::setHttpHeader('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + $ttl));
+ CRM_Utils_System::setHttpHeader('Cache-Control', "max-age=$ttl, public");
+ CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
+ print (json_encode($output));
}
CRM_Utils_System::civiExit();
}
+ /**
+ * @param array $menu
+ */
+ public static function formatMenuItems(&$menu) {
+ foreach ($menu as $key => &$item) {
+ $props = $item['attributes'];
+ unset($item['attributes']);
+ if (!empty($props['separator'])) {
+ $item['separator'] = ($props['separator'] == 1 ? 'bottom' : 'top');
+ }
+ if (!empty($props['icon'])) {
+ $item['icon'] = $props['icon'];
+ }
+ if (!empty($props['attr'])) {
+ $item['attr'] = $props['attr'];
+ }
+ if (!empty($props['url'])) {
+ $item['url'] = CRM_Utils_System::evalUrl(CRM_Core_BAO_Navigation::makeFullyFormedUrl($props['url']));
+ }
+ if (!empty($props['label'])) {
+ $item['label'] = ts($props['label'], ['context' => 'menu']);
+ }
+ $item['name'] = !empty($props['name']) ? $props['name'] : CRM_Utils_String::munge(CRM_Utils_Array::value('label', $props));
+ if (!empty($item['child'])) {
+ self::formatMenuItems($item['child']);
+ }
+ }
+ $menu = array_values($menu);
+ }
+
+ public static function getSearchOptions() {
+ $searchOptions = array_merge(['sort_name'], Civi::settings()->get('quicksearch_options'));
+ $labels = CRM_Core_SelectValues::quicksearchOptions();
+ $result = [];
+ foreach ($searchOptions as $key) {
+ $label = $labels[$key];
+ if (strpos($key, 'custom_') === 0) {
+ $key = 'custom_' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', substr($key, 7), 'id', 'name');
+ $label = array_slice(explode(': ', $label, 2), -1);
+ }
+ $result[$key] = $label;
+ }
+ return $result;
+ }
+
/**
* Process drag/move action for menu tree.
*/
@@ -68,16 +123,16 @@ public static function getStatusMsg() {
require_once 'api/v3/utils.php';
$recordID = CRM_Utils_Type::escape($_GET['id'], 'Integer');
$entity = CRM_Utils_Type::escape($_GET['entity'], 'String');
- $ret = array();
+ $ret = [];
if ($recordID && $entity && $recordBAO = _civicrm_api3_get_BAO($entity)) {
switch ($recordBAO) {
case 'CRM_Core_BAO_UFGroup':
$method = 'getUFJoinRecord';
- $result = array($recordBAO, $method);
- $ufJoin = call_user_func_array(($result), array($recordID, TRUE));
+ $result = [$recordBAO, $method];
+ $ufJoin = call_user_func_array(($result), [$recordID, TRUE]);
if (!empty($ufJoin)) {
- $ret['content'] = ts('This profile is currently used for %1.', array(1 => implode(', ', $ufJoin))) . '
' . ts('If you disable the profile - it will be removed from these forms and/or modules. Do you want to continue?');
+ $ret['content'] = ts('This profile is currently used for %1.', [1 => implode(', ', $ufJoin)]) . '
' . ts('If you disable the profile - it will be removed from these forms and/or modules. Do you want to continue?');
}
else {
$ret['content'] = ts('Are you sure you want to disable this profile?');
@@ -91,12 +146,12 @@ public static function getStatusMsg() {
if (!CRM_Utils_System::isNull($usedBy)) {
$template = CRM_Core_Smarty::singleton();
$template->assign('usedBy', $usedBy);
- $comps = array(
+ $comps = [
'Event' => 'civicrm_event',
'Contribution' => 'civicrm_contribution_page',
'EventTemplate' => 'civicrm_event_template',
- );
- $contexts = array();
+ ];
+ $contexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$contexts[] = $name;
@@ -106,12 +161,12 @@ public static function getStatusMsg() {
$ret['illegal'] = TRUE;
$table = $template->fetch('CRM/Price/Page/table.tpl');
- $ret['content'] = ts('Unable to disable the \'%1\' price set - it is currently in use by one or more active events, contribution pages or contributions.', array(
- 1 => $priceSet,
- )) . " $table";
+ $ret['content'] = ts('Unable to disable the \'%1\' price set - it is currently in use by one or more active events, contribution pages or contributions.', [
+ 1 => $priceSet,
+ ]) . " $table";
}
else {
- $ret['content'] = ts('Are you sure you want to disable \'%1\' Price Set?', array(1 => $priceSet));
+ $ret['content'] = ts('Are you sure you want to disable \'%1\' Price Set?', [1 => $priceSet]);
}
break;
@@ -123,7 +178,7 @@ public static function getStatusMsg() {
$ret['content'] = ts('Are you sure you want to disable this CiviCRM Profile field?');
break;
- case 'CRM_Contribute_BAO_ManagePremiums':
+ case 'CRM_Contribute_BAO_Product':
$ret['content'] = ts('Are you sure you want to disable this premium? This action will remove the premium from any contribution pages that currently offer it. However it will not delete the premium record - so you can re-enable it and add it back to your contribution page(s) at a later time.');
break;
@@ -165,7 +220,7 @@ public static function getStatusMsg() {
$ret['content'] = ts('Are you sure you want to disable this Participant Status?') . '
' . ts('Users will no longer be able to select this value when adding or editing Participant Status.');
break;
- case 'CRM_Mailing_BAO_Component':
+ case 'CRM_Mailing_BAO_MailingComponent':
$ret['content'] = ts('Are you sure you want to disable this component?');
break;
@@ -203,6 +258,7 @@ public static function getStatusMsg() {
case 'CRM_Contact_BAO_Group':
$ret['content'] = ts('Are you sure you want to disable this Group?');
+ $ret['content'] .= '
' . ts('WARNING - Disabling this group will disable all the child groups associated if any.') . '';
break;
case 'CRM_Core_BAO_OptionGroup':
@@ -215,7 +271,7 @@ public static function getStatusMsg() {
case 'CRM_Core_BAO_OptionValue':
$label = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $recordID, 'label');
- $ret['content'] = ts('Are you sure you want to disable the \'%1\' option ?', array(1 => $label));
+ $ret['content'] = ts('Are you sure you want to disable the \'%1\' option ?', [1 => $label]);
$ret['content'] .= '
';
- $value['class'] = array_diff($value['class'], array('crm-row-parent'));
+ $value['class'] = array_diff($value['class'], ['crm-row-parent']);
}
$group['DT_RowId'] = 'row_' . $value['id'];
if (empty($params['parentsOnly'])) {
@@ -805,7 +797,7 @@ static public function getGroupListSelector(&$params) {
}
}
$group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
- $group['DT_RowAttr'] = array();
+ $group['DT_RowAttr'] = [];
$group['DT_RowAttr']['data-id'] = $value['id'];
$group['DT_RowAttr']['data-entity'] = 'group';
@@ -828,7 +820,7 @@ static public function getGroupListSelector(&$params) {
array_push($groupList, $group);
}
- $groupsDT = array();
+ $groupsDT = [];
$groupsDT['data'] = $groupList;
$groupsDT['recordsTotal'] = !empty($params['total']) ? $params['total'] : NULL;
$groupsDT['recordsFiltered'] = !empty($params['total']) ? $params['total'] : NULL;
@@ -898,7 +890,7 @@ public static function getGroupList(&$params) {
//FIXME CRM-4418, now we are handling delete separately
//if we introduce 'delete for group' make sure to handle here.
- $groupPermissions = array(CRM_Core_Permission::VIEW);
+ $groupPermissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit groups')) {
$groupPermissions[] = CRM_Core_Permission::EDIT;
$groupPermissions[] = CRM_Core_Permission::DELETE;
@@ -907,19 +899,19 @@ public static function getGroupList(&$params) {
// CRM-9936
$reservedPermission = CRM_Core_Permission::check('administer reserved groups');
- $links = self::actionLinks();
+ $links = self::actionLinks($params);
$allTypes = CRM_Core_OptionGroup::values('group_type');
- $values = array();
+ $values = [];
$visibility = CRM_Core_SelectValues::ufVisibility();
while ($object->fetch()) {
$newLinks = $links;
- $values[$object->id] = array(
- 'class' => array(),
+ $values[$object->id] = [
+ 'class' => [],
'count' => '0',
- );
+ ];
CRM_Core_DAO::storeValues($object, $values[$object->id]);
if ($object->saved_search_id) {
@@ -968,24 +960,26 @@ public static function getGroupList(&$params) {
$groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
substr($values[$object->id]['group_type'], 1, -1)
);
- $types = array();
+ $types = [];
foreach ($groupTypes as $type) {
$types[] = CRM_Utils_Array::value($type, $allTypes);
}
$values[$object->id]['group_type'] = implode(', ', $types);
}
- $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
- $action,
- array(
- 'id' => $object->id,
- 'ssid' => $object->saved_search_id,
- ),
- ts('more'),
- FALSE,
- 'group.selector.row',
- 'Group',
- $object->id
- );
+ if ($action) {
+ $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
+ $action,
+ [
+ 'id' => $object->id,
+ 'ssid' => $object->saved_search_id,
+ ],
+ ts('more'),
+ FALSE,
+ 'group.selector.row',
+ 'Group',
+ $object->id
+ );
+ }
// If group has children, add class for link to view children
$values[$object->id]['is_parent'] = FALSE;
@@ -1005,11 +999,13 @@ public static function getGroupList(&$params) {
$values[$object->id]['org_info'] = "{$object->org_name}";
}
else {
- $values[$object->id]['org_info'] = ''; // Empty cell
+ // Empty cell
+ $values[$object->id]['org_info'] = '';
}
}
else {
- $values[$object->id]['org_info'] = NULL; // Collapsed column if all cells are NULL
+ // Collapsed column if all cells are NULL
+ $values[$object->id]['org_info'] = NULL;
}
if ($object->created_id) {
$contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
@@ -1024,7 +1020,7 @@ public static function getGroupList(&$params) {
$values[$object->id]['count'] = ts('unknown');
}
else {
- $values[$object->id]['count'] = civicrm_api3('Contact', 'getcount', array('group' => $object->id));
+ $values[$object->id]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id]);
}
}
@@ -1061,7 +1057,7 @@ public static function getGroupsHierarchy(
$titleOnly = FALSE
) {
if (empty($groupIDs)) {
- return array();
+ return [];
}
$groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
@@ -1073,18 +1069,18 @@ public static function getGroupsHierarchy(
// separators in front of the name to give it a visual offset.
// Instead of recursively making mysql queries, we'll make one big
// query and build the hierarchy with the algorithm below.
- $groups = array();
- $args = array(1 => array($groupIdString, 'String'));
+ $groups = [];
+ $args = [1 => [$groupIdString, 'String']];
$query = "
SELECT id, title, description, visibility, parents
FROM civicrm_group
WHERE id IN $groupIdString
";
if ($parents) {
- // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
+ // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
$parentArray = explode(',', $parents);
- $parent = $parentArray[0];
- $args[2] = array($parent, 'Integer');
+ $parent = self::filterActiveGroups($parentArray);
+ $args[2] = [$parent, 'Integer'];
$query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
}
$query .= " ORDER BY title";
@@ -1094,31 +1090,30 @@ public static function getGroupsHierarchy(
// $roots represent the current leaf nodes that need to be checked for
// children. $rows represent the unplaced nodes
// $tree contains the child nodes based on their parent_id.
- $roots = array();
- $tree = array();
+ $roots = [];
+ $tree = [];
while ($dao->fetch()) {
if ($dao->parents) {
$parentArray = explode(',', $dao->parents);
- $parent = $parentArray[0];
- $tree[$parent][] = array(
+ $parent = self::filterActiveGroups($parentArray);
+ $tree[$parent][] = [
'id' => $dao->id,
'title' => $dao->title,
'visibility' => $dao->visibility,
'description' => $dao->description,
- );
+ ];
}
else {
- $roots[] = array(
+ $roots[] = [
'id' => $dao->id,
'title' => $dao->title,
'visibility' => $dao->visibility,
'description' => $dao->description,
- );
+ ];
}
}
- $dao->free();
- $hierarchy = array();
+ $hierarchy = [];
for ($i = 0; $i < count($roots); $i++) {
self::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
}
@@ -1144,11 +1139,11 @@ private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOn
$hierarchy[$group['id']] = $spaces . $group['title'];
}
else {
- $hierarchy[$group['id']] = array(
+ $hierarchy[$group['id']] = [
'title' => $spaces . $group['title'],
'description' => $group['description'],
'visibility' => $group['visibility'],
- );
+ ];
}
// For performance reasons we use a for loop rather than a foreach.
@@ -1191,15 +1186,15 @@ public static function getGroupCount(&$params) {
* @return string
*/
public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
- $values = array();
+ $values = [];
$title = CRM_Utils_Array::value('title', $params);
if ($title) {
$clauses[] = "groups.title LIKE %1";
if (strpos($title, '%') !== FALSE) {
- $params[1] = array($title, 'String', FALSE);
+ $params[1] = [$title, 'String', FALSE];
}
else {
- $params[1] = array($title, 'String', TRUE);
+ $params[1] = [$title, 'String', TRUE];
}
}
@@ -1209,14 +1204,14 @@ public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TR
if (!empty($types)) {
$clauses[] = 'groups.group_type LIKE %2';
$typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR;
- $params[2] = array($typeString, 'String', TRUE);
+ $params[2] = [$typeString, 'String', TRUE];
}
}
$visibility = CRM_Utils_Array::value('visibility', $params);
if ($visibility) {
$clauses[] = 'groups.visibility = %3';
- $params[3] = array($visibility, 'String');
+ $params[3] = [$visibility, 'String'];
}
$groupStatus = CRM_Utils_Array::value('status', $params);
@@ -1224,12 +1219,12 @@ public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TR
switch ($groupStatus) {
case 1:
$clauses[] = 'groups.is_active = 1';
- $params[4] = array($groupStatus, 'Integer');
+ $params[4] = [$groupStatus, 'Integer'];
break;
case 2:
$clauses[] = 'groups.is_active = 0';
- $params[4] = array($groupStatus, 'Integer');
+ $params[4] = [$groupStatus, 'Integer'];
break;
case 3:
@@ -1247,16 +1242,16 @@ public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TR
$parent_id = CRM_Utils_Array::value('parent_id', $params);
if ($parent_id) {
$clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
- $params[5] = array($parent_id, 'Integer');
+ $params[5] = [$parent_id, 'Integer'];
}
if ($createdBy = CRM_Utils_Array::value('created_by', $params)) {
$clauses[] = "createdBy.sort_name LIKE %6";
if (strpos($createdBy, '%') !== FALSE) {
- $params[6] = array($createdBy, 'String', FALSE);
+ $params[6] = [$createdBy, 'String', FALSE];
}
else {
- $params[6] = array($createdBy, 'String', TRUE);
+ $params[6] = [$createdBy, 'String', TRUE];
}
}
@@ -1279,37 +1274,42 @@ public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TR
* @return array
* array of action links
*/
- public static function actionLinks() {
- $links = array(
- CRM_Core_Action::VIEW => array(
- 'name' => ts('Contacts'),
+ public static function actionLinks($params) {
+ // If component_mode is set we change the "View" link to match the requested component type
+ if (!isset($params['component_mode'])) {
+ $params['component_mode'] = CRM_Contact_BAO_Query::MODE_CONTACTS;
+ }
+ $modeValue = CRM_Contact_Form_Search::getModeValue($params['component_mode']);
+ $links = [
+ CRM_Core_Action::VIEW => [
+ 'name' => $modeValue['selectorLabel'],
'url' => 'civicrm/group/search',
- 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
+ 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
'title' => ts('Group Contacts'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Settings'),
'url' => 'civicrm/group',
'qs' => 'reset=1&action=update&id=%%id%%',
'title' => ts('Edit Group'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Group'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Group'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/group',
'qs' => 'reset=1&action=delete&id=%%id%%',
'title' => ts('Delete Group'),
- ),
- );
+ ],
+ ];
return $links;
}
@@ -1357,12 +1357,12 @@ protected function assignTestValue($fieldName, &$fieldDef, $counter) {
* @return array
*/
public static function getChildGroupIds($regularGroupIDs) {
- $childGroupIDs = array();
+ $childGroupIDs = [];
- foreach ($regularGroupIDs as $regularGroupID) {
+ foreach ((array) $regularGroupIDs as $regularGroupID) {
// temporary store the child group ID(s) of regular group identified by $id,
// later merge with main child group array
- $tempChildGroupIDs = array();
+ $tempChildGroupIDs = [];
// check that the regular group has any child group, if not then continue
if ($childrenFound = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
$tempChildGroupIDs[] = $childrenFound;
@@ -1386,4 +1386,30 @@ public static function getChildGroupIds($regularGroupIDs) {
return $childGroupIDs;
}
+ /**
+ * Check parent groups and filter out the disabled ones.
+ *
+ * @param array $parentArray
+ * Array of group Ids.
+ *
+ * @return int
+ */
+ public static function filterActiveGroups($parentArray) {
+ if (count($parentArray) > 1) {
+ $result = civicrm_api3('Group', 'get', [
+ 'id' => ['IN' => $parentArray],
+ 'is_active' => TRUE,
+ 'return' => 'id',
+ ]);
+ $activeParentGroupIDs = CRM_Utils_Array::collect('id', $result['values']);
+ foreach ($parentArray as $key => $groupID) {
+ if (!array_key_exists($groupID, $activeParentGroupIDs)) {
+ unset($parentArray[$key]);
+ }
+ }
+ }
+
+ return reset($parentArray);
+ }
+
}
diff --git a/CRM/Contact/BAO/GroupContact.php b/CRM/Contact/BAO/GroupContact.php
index 73bf59b76b8a..c4540d79d53f 100644
--- a/CRM/Contact/BAO/GroupContact.php
+++ b/CRM/Contact/BAO/GroupContact.php
@@ -1,9 +1,9 @@
copyValues($params);
- CRM_Contact_BAO_SubscriptionHistory::create($params);
$groupContact->save();
+
+ // Lookup existing info for the sake of subscription history
+ if (!empty($params['id'])) {
+ $groupContact->find(TRUE);
+ $params = $groupContact->toArray();
+ }
+ CRM_Contact_BAO_SubscriptionHistory::create($params);
+
+ CRM_Utils_Hook::post($hook, 'GroupContact', $groupContact->id, $groupContact);
+
return $groupContact;
}
@@ -74,12 +84,7 @@ public static function add(&$params) {
* @return bool
*/
public static function dataExists(&$params) {
- // return if no data present
- if ($params['group_id'] == 0) {
- return FALSE;
- }
-
- return TRUE;
+ return (!empty($params['id']) || (!empty($params['group_id']) && !empty($params['contact_id'])));
}
/**
@@ -135,7 +140,7 @@ public static function addContactsToGroup(
$tracking = NULL
) {
if (empty($contactIds) || empty($groupId)) {
- return array();
+ return [];
}
CRM_Utils_Hook::pre('create', 'GroupContact', $groupId, $contactIds);
@@ -147,7 +152,7 @@ public static function addContactsToGroup(
CRM_Utils_Hook::post('create', 'GroupContact', $groupId, $contactIds);
- return array(count($contactIds), $numContactsAdded, $numContactsNotAdded);
+ return [count($contactIds), $numContactsAdded, $numContactsNotAdded];
}
/**
@@ -173,7 +178,7 @@ public static function removeContactsFromGroup(
$tracking = NULL
) {
if (!is_array($contactIds)) {
- return array(0, 0, 0);
+ return [0, 0, 0];
}
if ($status == 'Removed' || $status == 'Deleted') {
@@ -197,14 +202,14 @@ public static function removeContactsFromGroup(
if ($status == 'Deleted') {
$query = "DELETE FROM civicrm_group_contact WHERE contact_id=$contactId AND group_id=$groupId";
$dao = CRM_Core_DAO::executeQuery($query);
- $historyParams = array(
+ $historyParams = [
'group_id' => $groupId,
'contact_id' => $contactId,
'status' => $status,
'method' => $method,
'date' => $date,
'tracking' => $tracking,
- );
+ ];
CRM_Contact_BAO_SubscriptionHistory::create($historyParams);
}
else {
@@ -223,14 +228,14 @@ public static function removeContactsFromGroup(
}
//now we grant the negative membership to contact if not member. CRM-3711
- $historyParams = array(
+ $historyParams = [
'group_id' => $groupId,
'contact_id' => $contactId,
'status' => $status,
'method' => $method,
'date' => $date,
'tracking' => $tracking,
- );
+ ];
CRM_Contact_BAO_SubscriptionHistory::create($historyParams);
$groupContact->status = $status;
$groupContact->save();
@@ -241,7 +246,7 @@ public static function removeContactsFromGroup(
CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds);
- return array(count($contactIds), $numContactsRemoved, $numContactsNotRemoved);
+ return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
}
/**
@@ -280,7 +285,7 @@ public static function getGroupList($contactId = 0, $visibility = FALSE) {
$group->query($sql);
- $values = array();
+ $values = [];
while ($group->fetch()) {
$values[$group->id] = $group->title;
}
@@ -313,7 +318,7 @@ public static function getGroupList($contactId = 0, $visibility = FALSE) {
* @param bool $includeSmartGroups
* Include or Exclude Smart Group(s)
*
- * @return array|int $values
+ * @return array|int
* the relevant data object values for the contact or the total count when $count is TRUE
*/
public static function getContactGroup(
@@ -349,21 +354,21 @@ public static function getContactGroup(
if ($excludeHidden) {
$where .= " AND civicrm_group.is_hidden = 0 ";
}
- $params = array(1 => array($contactId, 'Integer'));
+ $params = [1 => [$contactId, 'Integer']];
if (!empty($status)) {
$where .= ' AND civicrm_group_contact.status = %2';
- $params[2] = array($status, 'String');
+ $params[2] = [$status, 'String'];
}
if (!empty($groupId)) {
$where .= " AND civicrm_group.id = %3 ";
- $params[3] = array($groupId, 'Integer');
+ $params[3] = [$groupId, 'Integer'];
}
- $tables = array(
+ $tables = [
'civicrm_group_contact' => 1,
'civicrm_group' => 1,
'civicrm_subscription_history' => 1,
- );
- $whereTables = array();
+ ];
+ $whereTables = [];
if ($ignorePermission) {
$permission = ' ( 1 ) ';
}
@@ -396,7 +401,7 @@ public static function getContactGroup(
}
else {
$dao = CRM_Core_DAO::executeQuery($sql, $params);
- $values = array();
+ $values = [];
while ($dao->fetch()) {
$id = $dao->civicrm_group_contact_id;
$values[$id]['id'] = $id;
@@ -465,10 +470,10 @@ public static function getMembershipDetail($contactId, $groupID, $method = 'Emai
$orderBy
";
- $params = array(
- 1 => array($contactId, 'Integer'),
- 2 => array($groupID, 'Integer'),
- );
+ $params = [
+ 1 => [$contactId, 'Integer'],
+ 2 => [$groupID, 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$dao->fetch();
return $dao;
@@ -504,7 +509,7 @@ public static function getGroupId($groupContactID) {
* @param string $method
*/
public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin') {
- $contactIds = array();
+ $contactIds = [];
$contactIds[] = $contactId;
//if $visibility is true we are coming in via profile mean $method = 'Web'
@@ -530,12 +535,12 @@ public static function create(&$params, $contactId, $visibility = FALSE, $method
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($params)) {
- $params = array();
+ $params = [];
}
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!isset($contactGroup) || !is_array($contactGroup)) {
- $contactGroup = array();
+ $contactGroup = [];
}
// check which values has to be add/remove contact from group
@@ -564,11 +569,11 @@ public static function isContactInGroup($contactID, $groupID) {
return FALSE;
}
- $params = array(
- array('group', 'IN', array($groupID), 0, 0),
- array('contact_id', '=', $contactID, 0, 0),
- );
- list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, array('contact_id'));
+ $params = [
+ ['group', 'IN', [$groupID], 0, 0],
+ ['contact_id', '=', $contactID, 0, 0],
+ ];
+ list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, ['contact_id']);
if (!empty($contacts)) {
return TRUE;
@@ -590,10 +595,10 @@ public static function isContactInGroup($contactID, $groupID) {
* TODO: use the 3rd $sqls param to append sql statements rather than executing them here
*/
public static function mergeGroupContact($mainContactId, $otherContactId) {
- $params = array(
- 1 => array($mainContactId, 'Integer'),
- 2 => array($otherContactId, 'Integer'),
- );
+ $params = [
+ 1 => [$mainContactId, 'Integer'],
+ 2 => [$otherContactId, 'Integer'],
+ ];
// find all groups that are in otherContactID but not in mainContactID, copy them over
$sql = "
@@ -605,7 +610,7 @@ public static function mergeGroupContact($mainContactId, $otherContactId) {
";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
- $otherGroupIDs = array();
+ $otherGroupIDs = [];
while ($dao->fetch()) {
$otherGroupIDs[] = $dao->group_id;
}
@@ -640,7 +645,7 @@ public static function mergeGroupContact($mainContactId, $otherContactId) {
";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
- $groupIDs = array();
+ $groupIDs = [];
while ($dao->fetch()) {
// only copy it over if it has added status and migrate the history
if ($dao->group_status == 'Added') {
@@ -733,19 +738,19 @@ public static function bulkAddContactsToGroup(
AND status = %2
AND contact_id IN ( $contactStr )
";
- $params = array(
- 1 => array($groupID, 'Integer'),
- 2 => array($status, 'String'),
- );
+ $params = [
+ 1 => [$groupID, 'Integer'],
+ 2 => [$status, 'String'],
+ ];
- $presentIDs = array();
+ $presentIDs = [];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$presentIDs = explode(',', $dao->contactStr);
$presentIDs = array_flip($presentIDs);
}
- $gcValues = $shValues = array();
+ $gcValues = $shValues = [];
foreach ($input as $cid) {
if (isset($presentIDs[$cid])) {
$numContactsNotAdded++;
@@ -766,7 +771,7 @@ public static function bulkAddContactsToGroup(
}
}
- return array($numContactsAdded, $numContactsNotAdded);
+ return [$numContactsAdded, $numContactsNotAdded];
}
/**
@@ -781,10 +786,9 @@ public static function bulkAddContactsToGroup(
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
- $params = array();
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
- $options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
+ $options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $props, $context);
// Sort group list by hierarchy
// TODO: This will only work when api.entity is "group_contact". What about others?
diff --git a/CRM/Contact/BAO/GroupContactCache.php b/CRM/Contact/BAO/GroupContactCache.php
index 8b661fcda55b..a54dcdeb43fc 100644
--- a/CRM/Contact/BAO/GroupContactCache.php
+++ b/CRM/Contact/BAO/GroupContactCache.php
@@ -1,9 +1,9 @@
ts('Opportunistic Flush'),
// Flush expired caches via background cron jobs.
'deterministic' => ts('Cron Flush'),
- );
+ ];
}
/**
@@ -122,7 +122,7 @@ public static function groupRefreshedClause($groupIDClause = NULL, $includeHidde
*/
public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) {
$query = self::groupRefreshedClause("g.id = %1", $includeHiddenGroups);
- $params = array(1 => array($groupID, 'Integer'));
+ $params = [1 => [$groupID, 'Integer']];
// if the query returns the group ID, it means the group is a valid candidate for refreshing
return CRM_Core_DAO::singleValueQuery($query, $params);
@@ -146,11 +146,11 @@ public static function loadAll($groupIDs = NULL, $limit = 0) {
// this function is expensive and should be sparingly used if groupIDs is empty
if (empty($groupIDs)) {
$groupIDClause = NULL;
- $groupIDs = array();
+ $groupIDs = [];
}
else {
if (!is_array($groupIDs)) {
- $groupIDs = array($groupIDs);
+ $groupIDs = [$groupIDs];
}
// note escapeString is a must here and we can't send the imploded value as second argument to
@@ -175,7 +175,7 @@ public static function loadAll($groupIDs = NULL, $limit = 0) {
";
$dao = CRM_Core_DAO::executeQuery($query);
- $processGroupIDs = array();
+ $processGroupIDs = [];
$refreshGroupIDs = $groupIDs;
while ($dao->fetch()) {
$processGroupIDs[] = $dao->id;
@@ -221,9 +221,9 @@ public static function add($groupIDs) {
foreach ($groupIDs as $groupID) {
// first delete the current cache
self::clearGroupContactCache($groupID);
- $params = array(array('group', 'IN', array($groupID), 0, 0));
+ $params = [['group', 'IN', [$groupID], 0, 0]];
// the below call updates the cache table as a byproduct of the query
- CRM_Contact_BAO_Query::apiQuery($params, array('contact_id'), NULL, NULL, 0, 0, FALSE);
+ CRM_Contact_BAO_Query::apiQuery($params, ['contact_id'], NULL, NULL, 0, 0, FALSE);
}
}
@@ -295,7 +295,7 @@ public static function updateCacheTime($groupID, $processed) {
*/
public static function remove() {
Civi::log()
- ->warning('Deprecated code. This function should not be called without groupIDs. Extensions can use the api job.group_cache_flush for a hard flush or add an api option for soft flush', array('civi.tag' => 'deprecated'));
+ ->warning('Deprecated code. This function should not be called without groupIDs. Extensions can use the api job.group_cache_flush for a hard flush or add an api option for soft flush', ['civi.tag' => 'deprecated']);
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
}
@@ -318,9 +318,9 @@ public static function clearGroupContactCache($groupID) {
SET cache_date = null, refresh_date = null
WHERE id = %1 ";
- $params = array(
- 1 => array($groupID, 'Integer'),
- );
+ $params = [
+ 1 => [$groupID, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($query, $params);
// also update the cache_date for these groups
@@ -346,7 +346,7 @@ protected static function flushCaches() {
// Someone else is kindly doing the refresh for us right now.
return;
}
- $params = array(1 => array(self::getCacheInvalidDateTime(), 'String'));
+ $params = [1 => [self::getCacheInvalidDateTime(), 'String']];
// @todo this is consistent with previous behaviour but as the first query could take several seconds the second
// could become inaccurate. It seems to make more sense to fetch them first & delete from an array (which would
// also reduce joins). If we do this we should also consider how best to iterate the groups. If we do them one at
@@ -394,7 +394,7 @@ protected static function flushCaches() {
*/
protected static function getLockForRefresh() {
if (!isset(Civi::$statics[__CLASS__]['is_refresh_init'])) {
- Civi::$statics[__CLASS__] = array('is_refresh_init' => FALSE);
+ Civi::$statics[__CLASS__] = ['is_refresh_init' => FALSE];
}
if (Civi::$statics[__CLASS__]['is_refresh_init']) {
@@ -448,7 +448,7 @@ public static function deterministicCacheFlush() {
* TRUE if successful.
*/
public static function removeContact($cid, $groupId = NULL) {
- $cids = array();
+ $cids = [];
// sanitize input
foreach ((array) $cid as $c) {
$cids[] = CRM_Utils_Type::escape($c, 'Integer');
@@ -514,7 +514,7 @@ public static function load(&$group, $force = FALSE) {
CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
}
- $returnProperties = array();
+ $returnProperties = [];
if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) {
$fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
$returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv);
@@ -555,15 +555,12 @@ public static function load(&$group, $force = FALSE) {
);
$query->_useDistinct = FALSE;
$query->_useGroupBy = FALSE;
- $searchSQL
- = $query->searchQuery(
+ $sqlParts = $query->getSearchSQLParts(
0, 0, NULL,
FALSE, FALSE,
- FALSE, TRUE,
- TRUE,
- NULL, NULL, NULL,
- TRUE
+ FALSE, TRUE
);
+ $searchSQL = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
}
$groupID = CRM_Utils_Type::escape($groupID, 'Integer');
$sql = $searchSQL . " AND contact_a.id NOT IN (
@@ -588,7 +585,7 @@ public static function load(&$group, $force = FALSE) {
$processed = FALSE;
$tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000);
- foreach (array($sql, $sqlB) as $selectSql) {
+ foreach ([$sql, $sqlB] as $selectSql) {
if (!$selectSql) {
continue;
}
@@ -602,7 +599,7 @@ public static function load(&$group, $force = FALSE) {
CRM_Core_DAO::executeQuery(" DROP TEMPORARY TABLE $tempTable");
}
- self::updateCacheTime(array($groupID), $processed);
+ self::updateCacheTime([$groupID], $processed);
if ($group->children) {
@@ -613,7 +610,7 @@ public static function load(&$group, $force = FALSE) {
WHERE civicrm_group_contact.status = 'Removed'
AND civicrm_group_contact.group_id = $groupID ";
$dao = CRM_Core_DAO::executeQuery($sql);
- $removed_contacts = array();
+ $removed_contacts = [];
while ($dao->fetch()) {
$removed_contacts[] = $dao->contact_id;
}
@@ -625,12 +622,12 @@ public static function load(&$group, $force = FALSE) {
foreach ($removed_contacts as $removed_contact) {
unset($contactIDs[$removed_contact]);
}
- $values = array();
+ $values = [];
foreach ($contactIDs as $contactID => $dontCare) {
$values[] = "({$groupID},{$contactID})";
}
- self::store(array($groupID), $values);
+ self::store([$groupID], $values);
}
}
@@ -682,7 +679,7 @@ public static function contactGroup($contactID, $showHidden = FALSE) {
$contactIDs = $contactID;
}
else {
- $contactIDs = array($contactID);
+ $contactIDs = [$contactID];
}
self::loadAll();
@@ -703,7 +700,7 @@ public static function contactGroup($contactID, $showHidden = FALSE) {
";
$dao = CRM_Core_DAO::executeQuery($sql);
- $contactGroup = array();
+ $contactGroup = [];
$prevContactID = NULL;
while ($dao->fetch()) {
if (
@@ -715,16 +712,16 @@ public static function contactGroup($contactID, $showHidden = FALSE) {
$prevContactID = $dao->contact_id;
if (!array_key_exists($dao->contact_id, $contactGroup)) {
$contactGroup[$dao->contact_id]
- = array('group' => array(), 'groupTitle' => array());
+ = ['group' => [], 'groupTitle' => []];
}
$contactGroup[$dao->contact_id]['group'][]
- = array(
+ = [
'id' => $dao->group_id,
'title' => $dao->title,
'description' => $dao->description,
'children' => $dao->children,
- );
+ ];
$contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
}
diff --git a/CRM/Contact/BAO/GroupNesting.php b/CRM/Contact/BAO/GroupNesting.php
index 284aa3a1bf40..dae7b4a3fd2e 100644
--- a/CRM/Contact/BAO/GroupNesting.php
+++ b/CRM/Contact/BAO/GroupNesting.php
@@ -1,7 +1,7 @@
copyValues($params);
+ if (empty($params['id'])) {
+ $dao->find(TRUE);
+ }
+ $dao->save();
+ CRM_Utils_Hook::post($hook, 'GroupNesting', $dao->id, $dao);
+ return $dao;
+ }
+
/**
* Adds a new group nesting record.
*
@@ -124,12 +146,12 @@ public static function hasParentGroups($groupId) {
*/
public static function getChildGroupIds($groupIds) {
if (!is_array($groupIds)) {
- $groupIds = array($groupIds);
+ $groupIds = [$groupIds];
}
$dao = new CRM_Contact_DAO_GroupNesting();
$query = "SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id IN (" . implode(',', $groupIds) . ")";
$dao->query($query);
- $childGroupIds = array();
+ $childGroupIds = [];
while ($dao->fetch()) {
$childGroupIds[] = $dao->child_group_id;
}
@@ -147,12 +169,12 @@ public static function getChildGroupIds($groupIds) {
*/
public static function getParentGroupIds($groupIds) {
if (!is_array($groupIds)) {
- $groupIds = array($groupIds);
+ $groupIds = [$groupIds];
}
$dao = new CRM_Contact_DAO_GroupNesting();
$query = "SELECT parent_group_id FROM civicrm_group_nesting WHERE child_group_id IN (" . implode(',', $groupIds) . ")";
$dao->query($query);
- $parentGroupIds = array();
+ $parentGroupIds = [];
while ($dao->fetch()) {
$parentGroupIds[] = $dao->parent_group_id;
}
@@ -172,13 +194,13 @@ public static function getParentGroupIds($groupIds) {
*/
public static function getDescendentGroupIds($groupIds, $includeSelf = TRUE) {
if (!is_array($groupIds)) {
- $groupIds = array($groupIds);
+ $groupIds = [$groupIds];
}
$dao = new CRM_Contact_DAO_GroupNesting();
$query = "SELECT child_group_id, parent_group_id FROM civicrm_group_nesting WHERE parent_group_id IN (" . implode(',', $groupIds) . ")";
$dao->query($query);
- $tmpGroupIds = array();
- $childGroupIds = array();
+ $tmpGroupIds = [];
+ $childGroupIds = [];
if ($includeSelf) {
$childGroupIds = $groupIds;
}
diff --git a/CRM/Contact/BAO/GroupNestingCache.php b/CRM/Contact/BAO/GroupNestingCache.php
index 2014ed146cbe..e48d988b9023 100644
--- a/CRM/Contact/BAO/GroupNestingCache.php
+++ b/CRM/Contact/BAO/GroupNestingCache.php
@@ -1,9 +1,9 @@
fetch()) {
if (!array_key_exists($dao->child, $tree)) {
- $tree[$dao->child] = array(
- 'children' => array(),
- 'parents' => array(),
- );
+ $tree[$dao->child] = [
+ 'children' => [],
+ 'parents' => [],
+ ];
}
if (!array_key_exists($dao->parent, $tree)) {
- $tree[$dao->parent] = array(
- 'children' => array(),
- 'parents' => array(),
- );
+ $tree[$dao->parent] = [
+ 'children' => [],
+ 'parents' => [],
+ ];
}
$tree[$dao->child]['parents'][] = $dao->parent;
@@ -84,7 +84,7 @@ static public function update() {
";
CRM_Core_DAO::executeQuery($sql);
- $values = array();
+ $values = [];
foreach (array_keys($tree) as $id) {
$parents = implode(',', $tree[$id]['parents']);
$children = implode(',', $tree[$id]['children']);
@@ -129,7 +129,7 @@ public static function checkCyclicGraph(&$tree) {
* @return bool
*/
public static function isCyclic(&$tree, $id) {
- $parents = $children = array();
+ $parents = $children = [];
self::getAll($parent, $tree, $id, 'parents');
self::getAll($child, $tree, $id, 'children');
@@ -232,7 +232,7 @@ public static function json() {
foreach ($groups as $id => $name) {
$string = "id:'$id', name:'$name'";
if (isset($tree[$id])) {
- $children = array();
+ $children = [];
if (!empty($tree[$id]['children'])) {
foreach ($tree[$id]['children'] as $child) {
$children[] = "{_reference:'$child'}";
diff --git a/CRM/Contact/BAO/GroupOrganization.php b/CRM/Contact/BAO/GroupOrganization.php
index da6d27008a93..f57814da249c 100644
--- a/CRM/Contact/BAO/GroupOrganization.php
+++ b/CRM/Contact/BAO/GroupOrganization.php
@@ -1,9 +1,9 @@
copyValues($formattedValues);
- // we have ensured we have group_id & organization_id so we can do a find knowing that
- // this can only find a matching record
- $groupOrganization->find(TRUE);
+ $groupOrganization->copyValues($params);
+ if (!isset($params['id'])) {
+ // we have ensured we have group_id & organization_id so we can do a find knowing that
+ // this can only find a matching record
+ $groupOrganization->find(TRUE);
+ }
$groupOrganization->save();
return $groupOrganization;
}
- /**
- * Format the params.
- *
- * @param array $params
- * (reference ) an assoc array of name/value pairs.
- * @param array $formatedValues
- * (reference ) an assoc array of name/value pairs.
- */
- public static function formatValues(&$params, &$formatedValues) {
- if (!empty($params['group_organization'])) {
- $formatedValues['id'] = $params['group_organization'];
- }
-
- if (!empty($params['group_id'])) {
- $formatedValues['group_id'] = $params['group_id'];
- }
-
- if (!empty($params['organization_id'])) {
- $formatedValues['organization_id'] = $params['organization_id'];
- }
- }
-
/**
* Check if there is data to create the object.
*
diff --git a/CRM/Contact/BAO/Household.php b/CRM/Contact/BAO/Household.php
index 62109f0b33ef..523849e72327 100644
--- a/CRM/Contact/BAO/Household.php
+++ b/CRM/Contact/BAO/Household.php
@@ -1,9 +1,9 @@
$dbName;
@@ -105,7 +105,7 @@ public static function format(&$params, &$contact) {
}
}
- foreach (array('prefix', 'suffix') as $name) {
+ foreach (['prefix', 'suffix'] as $name) {
$dbName = "{$name}_id";
$value = $individual->$dbName;
if ($value && !empty($params['preserveDBName'])) {
@@ -122,7 +122,7 @@ public static function format(&$params, &$contact) {
//2. lets get value from param if exists.
//3. if not in params, lets get from db.
- foreach (array('last', 'middle', 'first', 'nick') as $name) {
+ foreach (['last', 'middle', 'first', 'nick'] as $name) {
$phpName = "{$name}Name";
$dbName = "{$name}_name";
$value = $individual->$dbName;
@@ -139,7 +139,7 @@ public static function format(&$params, &$contact) {
}
}
- foreach (array('prefix', 'suffix') as $name) {
+ foreach (['prefix', 'suffix'] as $name) {
$dbName = "{$name}_id";
$value = $individual->$dbName;
@@ -179,14 +179,14 @@ public static function format(&$params, &$contact) {
}
//first trim before further processing.
- foreach (array('lastName', 'firstName', 'middleName') as $fld) {
+ foreach (['lastName', 'firstName', 'middleName'] as $fld) {
$$fld = trim($$fld);
}
if ($lastName || $firstName || $middleName) {
// make sure we have values for all the name fields.
$formatted = $params;
- $nameParams = array(
+ $nameParams = [
'first_name' => $firstName,
'middle_name' => $middleName,
'last_name' => $lastName,
@@ -196,7 +196,7 @@ public static function format(&$params, &$contact) {
'prefix_id' => $prefix_id,
'suffix_id' => $suffix_id,
'formal_title' => $formalTitle,
- );
+ ];
// make sure we have all the name fields.
foreach ($nameParams as $name => $value) {
if (empty($formatted[$name]) && $value) {
@@ -204,9 +204,9 @@ public static function format(&$params, &$contact) {
}
}
- $tokens = array();
+ $tokens = [];
CRM_Utils_Hook::tokens($tokens);
- $tokenFields = array();
+ $tokenFields = [];
foreach ($tokens as $catTokens) {
foreach ($catTokens as $token => $label) {
$tokenFields[] = $token;
@@ -216,14 +216,14 @@ public static function format(&$params, &$contact) {
//build the sort name.
$format = Civi::settings()->get('sort_name_format');
$sortName = CRM_Utils_Address::format($formatted, $format,
- FALSE, FALSE, TRUE, $tokenFields
+ FALSE, FALSE, $tokenFields
);
$sortName = trim($sortName);
//build the display name.
$format = Civi::settings()->get('display_name_format');
$displayName = CRM_Utils_Address::format($formatted, $format,
- FALSE, FALSE, TRUE, $tokenFields
+ FALSE, FALSE, $tokenFields
);
$displayName = trim($displayName);
}
@@ -248,7 +248,7 @@ public static function format(&$params, &$contact) {
}
//now set the names.
- $names = array('displayName' => 'display_name', 'sortName' => 'sort_name');
+ $names = ['displayName' => 'display_name', 'sortName' => 'sort_name'];
foreach ($names as $value => $name) {
if (empty($$value)) {
if ($email) {
@@ -273,29 +273,29 @@ public static function format(&$params, &$contact) {
$format = CRM_Utils_Date::getDateFormat('birth');
if ($date = CRM_Utils_Array::value('birth_date', $params)) {
- if (in_array($format, array(
+ if (in_array($format, [
'dd-mm',
'mm/dd',
- ))) {
+ ])) {
$separator = '/';
if ($format == 'dd-mm') {
$separator = '-';
}
$date = $date . $separator . '1902';
}
- elseif (in_array($format, array(
+ elseif (in_array($format, [
'yy-mm',
- ))) {
+ ])) {
$date = $date . '-01';
}
- elseif (in_array($format, array(
+ elseif (in_array($format, [
'M yy',
- ))) {
+ ])) {
$date = $date . '-01';
}
- elseif (in_array($format, array(
+ elseif (in_array($format, [
'yy',
- ))) {
+ ])) {
$date = $date . '-01-01';
}
$contact->birth_date = CRM_Utils_Date::processDate($date);
@@ -305,29 +305,29 @@ public static function format(&$params, &$contact) {
}
if ($date = CRM_Utils_Array::value('deceased_date', $params)) {
- if (in_array($format, array(
+ if (in_array($format, [
'dd-mm',
'mm/dd',
- ))) {
+ ])) {
$separator = '/';
if ($format == 'dd-mm') {
$separator = '-';
}
$date = $date . $separator . '1902';
}
- elseif (in_array($format, array(
+ elseif (in_array($format, [
'yy-mm',
- ))) {
+ ])) {
$date = $date . '-01';
}
- elseif (in_array($format, array(
+ elseif (in_array($format, [
'M yy',
- ))) {
+ ])) {
$date = $date . '-01';
}
- elseif (in_array($format, array(
+ elseif (in_array($format, [
'yy',
- ))) {
+ ])) {
$date = $date . '-01-01';
}
diff --git a/CRM/Contact/BAO/ProximityQuery.php b/CRM/Contact/BAO/ProximityQuery.php
index 0418f5ab2ea4..c1e72783b872 100644
--- a/CRM/Contact/BAO/ProximityQuery.php
+++ b/CRM/Contact/BAO/ProximityQuery.php
@@ -1,9 +1,9 @@
= $minLatitude ";
}
@@ -264,7 +267,7 @@ public static function process(&$query, &$values) {
list($name, $op, $distance, $grouping, $wildcard) = $values;
// also get values array for all address related info
- $proximityVars = array(
+ $proximityVars = [
'street_address' => 1,
'city' => 1,
'postal_code' => 1,
@@ -273,10 +276,12 @@ public static function process(&$query, &$values) {
'state_province' => 0,
'country' => 0,
'distance_unit' => 0,
- );
+ 'geo_code_1' => 0,
+ 'geo_code_2' => 0,
+ ];
- $proximityAddress = array();
- $qill = array();
+ $proximityAddress = [];
+ $qill = [];
foreach ($proximityVars as $var => $recordQill) {
$proximityValues = $query->getWhereValues("prox_{$var}", $grouping);
if (!empty($proximityValues) &&
@@ -327,21 +332,20 @@ public static function process(&$query, &$values) {
}
$qill = ts('Proximity search to a distance of %1 from %2',
- array(
+ [
1 => $qillUnits,
2 => implode(', ', $qill),
- )
+ ]
);
- $fnName = isset($config->geocodeMethod) ? $config->geocodeMethod : NULL;
- if (empty($fnName)) {
- CRM_Core_Error::fatal(ts('Proximity searching requires you to set a valid geocoding provider'));
- }
-
$query->_tables['civicrm_address'] = $query->_whereTables['civicrm_address'] = 1;
- require_once str_replace('_', DIRECTORY_SEPARATOR, $fnName) . '.php';
- $fnName::format($proximityAddress);
+ if (empty($proximityAddress['geo_code_1']) || empty($proximityAddress['geo_code_2'])) {
+ if (!CRM_Core_BAO_Address::addGeocoderData($proximityAddress)) {
+ throw new CRM_Core_Exception(ts('Proximity searching requires you to set a valid geocoding provider'));
+ }
+ }
+
if (
!is_numeric(CRM_Utils_Array::value('geo_code_1', $proximityAddress)) ||
!is_numeric(CRM_Utils_Array::value('geo_code_2', $proximityAddress))
@@ -373,7 +377,7 @@ public static function fixInputParams(&$input) {
foreach ($input as $param) {
if (CRM_Utils_Array::value('0', $param) == 'prox_distance') {
// add prox_ prefix to these
- $param_alter = array('street_address', 'city', 'postal_code', 'state_province', 'country');
+ $param_alter = ['street_address', 'city', 'postal_code', 'state_province', 'country'];
foreach ($input as $key => $_param) {
if (in_array($_param[0], $param_alter)) {
diff --git a/CRM/Contact/BAO/Query.php b/CRM/Contact/BAO/Query.php
index ab28ca3de959..0e08cb5ed921 100644
--- a/CRM/Contact/BAO/Query.php
+++ b/CRM/Contact/BAO/Query.php
@@ -1,9 +1,9 @@
1,
'civicrm_country' => 1,
'civicrm_county' => 1,
'civicrm_address' => 1,
'civicrm_location_type' => 1,
- );
+ ];
/**
* List of location specific fields.
+ * @var array
*/
- static $_locationSpecificFields = array(
+ public static $_locationSpecificFields = [
'street_address',
'street_number',
'street_name',
@@ -383,13 +393,14 @@ class CRM_Contact_BAO_Query {
'im',
'address_name',
'master_id',
- );
+ ];
/**
* Remember if we handle either end of a number or date range
* so we can skip the other
+ * @var array
*/
- protected $_rangeCache = array();
+ protected $_rangeCache = [];
/**
* Set to true when $this->relationship is run to avoid adding twice
* @var Boolean
@@ -400,9 +411,12 @@ class CRM_Contact_BAO_Query {
* Set to the name of the temp table if one has been created
* @var String
*/
- static $_relationshipTempTable = NULL;
+ public static $_relationshipTempTable = NULL;
- public $_pseudoConstantsSelect = array();
+ public $_pseudoConstantsSelect = [];
+
+ public $_groupUniqueKey = NULL;
+ public $_groupKeys = [];
/**
* Class constructor which also does all the work.
@@ -437,11 +451,11 @@ public function __construct(
$this->_primaryLocation = $primaryLocationOnly;
$this->_params = &$params;
if ($this->_params == NULL) {
- $this->_params = array();
+ $this->_params = [];
}
if ($returnProperties === self::NO_RETURN_PROPERTIES) {
- $this->_returnProperties = array();
+ $this->_returnProperties = [];
}
elseif (empty($returnProperties)) {
$this->_returnProperties = self::defaultReturnProperties($mode);
@@ -491,16 +505,16 @@ public function __construct(
* This sort-of duplicates $mode in a confusing way. Probably not by design.
*/
public function initialize($apiEntity = NULL) {
- $this->_select = array();
- $this->_element = array();
- $this->_tables = array();
- $this->_whereTables = array();
- $this->_where = array();
- $this->_qill = array();
- $this->_options = array();
- $this->_cfIDs = array();
- $this->_paramLookup = array();
- $this->_having = array();
+ $this->_select = [];
+ $this->_element = [];
+ $this->_tables = [];
+ $this->_whereTables = [];
+ $this->_where = [];
+ $this->_qill = [];
+ $this->_options = [];
+ $this->_cfIDs = [];
+ $this->_paramLookup = [];
+ $this->_having = [];
$this->_customQuery = NULL;
@@ -527,7 +541,8 @@ public function initialize($apiEntity = NULL) {
if (array_key_exists('civicrm_membership', $this->_whereTables)) {
$component = 'membership';
}
- if (isset($component)) {
+ if (isset($component) && !$this->_skipPermission) {
+ // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
CRM_Financial_BAO_FinancialType::buildPermissionedClause($this->_whereClause, $component);
}
@@ -556,7 +571,7 @@ public function initialize($apiEntity = NULL) {
*/
public function buildParamsLookup() {
$trashParamExists = FALSE;
- $paramByGroup = array();
+ $paramByGroup = [];
foreach ($this->_params as $k => $param) {
if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
$trashParamExists = TRUE;
@@ -572,16 +587,16 @@ public function buildParamsLookup() {
//cycle through group sets and explicitly add trash param if not set
foreach ($paramByGroup as $setID => $set) {
if (
- !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params) &&
- !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params)
+ !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params) &&
+ !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params)
) {
- $this->_params[] = array(
+ $this->_params[] = [
'contact_is_deleted',
'=',
'0',
$setID,
'0',
- );
+ ];
}
}
}
@@ -593,7 +608,7 @@ public function buildParamsLookup() {
$cfID = CRM_Core_BAO_CustomField::getKeyID($value[0]);
if ($cfID) {
if (!array_key_exists($cfID, $this->_cfIDs)) {
- $this->_cfIDs[$cfID] = array();
+ $this->_cfIDs[$cfID] = [];
}
// Set wildcard value based on "and/or" selection
foreach ($this->_params as $key => $param) {
@@ -606,7 +621,7 @@ public function buildParamsLookup() {
}
if (!array_key_exists($value[0], $this->_paramLookup)) {
- $this->_paramLookup[$value[0]] = array();
+ $this->_paramLookup[$value[0]] = [];
}
if ($value[0] !== 'group') {
// Just trying to unravel how group interacts here! This whole function is weird.
@@ -623,7 +638,7 @@ public function buildParamsLookup() {
* This sort-of duplicates $mode in a confusing way. Probably not by design.
*/
public function addSpecialFields($apiEntity) {
- static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
+ static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
// if get called via Contact.get API having address_id as return parameter
if ($apiEntity == 'Contact') {
$special[] = 'address_id';
@@ -693,7 +708,7 @@ public function selectClause($apiEntity = NULL) {
$makeException = FALSE;
//special handling for groups/tags
- if (in_array($name, array('groups', 'tags', 'notes'))
+ if (in_array($name, ['groups', 'tags', 'notes'])
&& isset($this->_returnProperties[substr($name, 0, -1)])
) {
// @todo instead of setting make exception to get us into
@@ -705,7 +720,7 @@ public function selectClause($apiEntity = NULL) {
// since note has 3 different options we need special handling
// note / note_subject / note_body
if ($name == 'notes') {
- foreach (array('note', 'note_subject', 'note_body') as $noteField) {
+ foreach (['note', 'note_subject', 'note_body'] as $noteField) {
if (isset($this->_returnProperties[$noteField])) {
$makeException = TRUE;
break;
@@ -717,13 +732,13 @@ public function selectClause($apiEntity = NULL) {
if (
!empty($this->_paramLookup[$name])
|| !empty($this->_returnProperties[$name])
- || $this->pseudoConstantNameIsInReturnProperties($field)
+ || $this->pseudoConstantNameIsInReturnProperties($field, $name)
|| $makeException
) {
if ($cfID) {
// add to cfIDs array if not present
if (!array_key_exists($cfID, $this->_cfIDs)) {
- $this->_cfIDs[$cfID] = array();
+ $this->_cfIDs[$cfID] = [];
}
}
elseif (isset($field['where'])) {
@@ -743,10 +758,10 @@ public function selectClause($apiEntity = NULL) {
}
if (in_array($tableName,
- array('email_greeting', 'postal_greeting', 'addressee'))) {
+ ['email_greeting', 'postal_greeting', 'addressee'])) {
$this->_element["{$name}_id"] = 1;
$this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
- $this->_pseudoConstantsSelect[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
+ $this->_pseudoConstantsSelect[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
$this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as $name";
$this->_pseudoConstantsSelect[$name]['element'] = $name;
@@ -784,37 +799,37 @@ public function selectClause($apiEntity = NULL) {
}
}
else {
- if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
+ if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
$this->_tables[$tableName] = 1;
}
// also get the id of the tableName
$tName = substr($tableName, 8);
- if (in_array($tName, array('country', 'state_province', 'county'))) {
+ if (in_array($tName, ['country', 'state_province', 'county'])) {
if ($tName == 'state_province') {
- $this->_pseudoConstantsSelect['state_province_name'] = array(
+ $this->_pseudoConstantsSelect['state_province_name'] = [
'pseudoField' => "{$tName}",
'idCol' => "{$tName}_id",
'bao' => 'CRM_Core_BAO_Address',
'table' => "civicrm_{$tName}",
'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
- );
+ ];
- $this->_pseudoConstantsSelect[$tName] = array(
+ $this->_pseudoConstantsSelect[$tName] = [
'pseudoField' => 'state_province_abbreviation',
'idCol' => "{$tName}_id",
'table' => "civicrm_{$tName}",
'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
- );
+ ];
}
else {
- $this->_pseudoConstantsSelect[$name] = array(
+ $this->_pseudoConstantsSelect[$name] = [
'pseudoField' => "{$tName}_id",
'idCol' => "{$tName}_id",
'bao' => 'CRM_Core_BAO_Address',
'table' => "civicrm_{$tName}",
'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
- );
+ ];
}
$this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
@@ -845,7 +860,7 @@ public function selectClause($apiEntity = NULL) {
elseif ($tName == 'contact' && $fieldName === 'id') {
// Handled elsewhere, explicitly ignore. Possibly for all tables...
}
- elseif (in_array($tName, array('country', 'county'))) {
+ elseif (in_array($tName, ['country', 'county'])) {
$this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`";
$this->_pseudoConstantsSelect[$name]['element'] = $name;
}
@@ -858,25 +873,13 @@ public function selectClause($apiEntity = NULL) {
$this->_select[$name] = "{$field['where']} as `$name`";
}
}
+ elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
+ $this->addPseudoconstantFieldToSelect($name);
+ }
else {
- // If we have an option group defined then rather than joining the option value table in
- // (which is an unindexed join) we render the option value on output.
- // @todo - extend this to other pseudoconstants.
- if ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
- $pseudoFieldName = $field['pseudoconstant']['optionGroupName'];
- $this->_pseudoConstantsSelect[$pseudoFieldName] = array(
- 'pseudoField' => $field['name'],
- 'idCol' => $name,
- 'field_name' => $field['name'],
- 'bao' => $field['bao'],
- 'pseudoconstant' => $field['pseudoconstant'],
- );
- $this->_tables[$tableName] = 1;
- $this->_element[$pseudoFieldName] = 1;
- }
$this->_select[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
}
- if (!in_array($tName, array('state_province', 'country', 'county'))) {
+ if (!in_array($tName, ['state_province', 'country', 'county'])) {
$this->_element[$name] = 1;
}
}
@@ -903,10 +906,10 @@ public function selectClause($apiEntity = NULL) {
$this->_element[$name] = 1;
$this->_tables['civicrm_group_contact'] = 1;
$this->_tables['civicrm_group_contact_cache'] = 1;
- $this->_pseudoConstantsSelect["{$name}"] = array(
+ $this->_pseudoConstantsSelect["{$name}"] = [
'pseudoField' => "groups",
'idCol' => "groups",
- );
+ ];
}
elseif ($name === 'notes') {
//@todo move this handling outside the big IF & ditch $makeException
@@ -931,7 +934,7 @@ public function selectClause($apiEntity = NULL) {
// this is a custom field with range search enabled, so we better check for two/from values
if (!empty($this->_paramLookup[$name . '_from'])) {
if (!array_key_exists($cfID, $this->_cfIDs)) {
- $this->_cfIDs[$cfID] = array();
+ $this->_cfIDs[$cfID] = [];
}
foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
// search in the cdID array for the same grouping
@@ -943,14 +946,14 @@ public function selectClause($apiEntity = NULL) {
}
}
if (!$fnd) {
- $p[2] = array('from' => $p[2]);
+ $p[2] = ['from' => $p[2]];
$this->_cfIDs[$cfID][] = $p;
}
}
}
if (!empty($this->_paramLookup[$name . '_to'])) {
if (!array_key_exists($cfID, $this->_cfIDs)) {
- $this->_cfIDs[$cfID] = array();
+ $this->_cfIDs[$cfID] = [];
}
foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) {
// search in the cdID array for the same grouping
@@ -962,7 +965,7 @@ public function selectClause($apiEntity = NULL) {
}
}
if (!$fnd) {
- $p[2] = array('to' => $p[2]);
+ $p[2] = ['to' => $p[2]];
$this->_cfIDs[$cfID][] = $p;
}
}
@@ -1005,18 +1008,18 @@ public function addHierarchicalElements() {
return;
}
- $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
- $processed = array();
+ $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
+ $processed = [];
$index = 0;
$addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
- $addressCustomFieldIds = array();
+ $addressCustomFieldIds = [];
foreach ($this->_returnProperties['location'] as $name => $elements) {
$lCond = self::getPrimaryCondition($name);
+ $locationTypeId = is_numeric($name) ? NULL : array_search($name, $locationTypes);
if (!$lCond) {
- $locationTypeId = array_search($name, $locationTypes);
if ($locationTypeId === FALSE) {
continue;
}
@@ -1028,7 +1031,6 @@ public function addHierarchicalElements() {
}
$name = str_replace(' ', '_', $name);
-
$tName = "$name-location_type";
$ltName = "`$name-location_type`";
$this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
@@ -1037,9 +1039,8 @@ public function addHierarchicalElements() {
$this->_element["{$tName}"] = 1;
$locationTypeName = $tName;
- $locationTypeJoin = array();
+ $locationTypeJoin = [];
- $addAddress = FALSE;
$addWhereCount = 0;
foreach ($elements as $elementFullName => $dontCare) {
$index++;
@@ -1054,20 +1055,14 @@ public function addHierarchicalElements() {
$addressCustomFieldIds[$cfID][$name] = 1;
}
}
- //add address table only once
+ // add address table - doesn't matter if we do it mutliple times - it's the same data
+ // @todo ditch the double processing of addressJoin
if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds))
- && !$addAddress
- && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
+ && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
) {
- $tName = "$name-address";
- $aName = "`$name-address`";
- $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
- $this->_element["{$tName}_id"] = 1;
- $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
- $this->_tables[$tName] = $addressJoin;
+ list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
$locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
$processed[$aName] = 1;
- $addAddress = TRUE;
}
$cond = $elementType = '';
@@ -1108,7 +1103,7 @@ public function addHierarchicalElements() {
}
elseif (is_numeric($name)) {
//this for phone type to work
- if (in_array($elementName, array('phone', 'phone_ext'))) {
+ if (in_array($elementName, ['phone', 'phone_ext'])) {
$field = CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields);
}
else {
@@ -1117,7 +1112,7 @@ public function addHierarchicalElements() {
}
else {
//this is for phone type to work for profile edit
- if (in_array($elementName, array('phone', 'phone_ext'))) {
+ if (in_array($elementName, ['phone', 'phone_ext'])) {
$field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
}
else {
@@ -1139,7 +1134,7 @@ public function addHierarchicalElements() {
foreach ($this->_params as $id => $values) {
if ((is_array($values) && $values[0] == $nm) ||
- (in_array($elementName, array('phone', 'im'))
+ (in_array($elementName, ['phone', 'im'])
&& (strpos($values[0], $nm) !== FALSE)
)
) {
@@ -1168,18 +1163,18 @@ public function addHierarchicalElements() {
$a = Civi::settings()->get('address_format');
if (substr_count($a, 'state_province_name') > 0) {
- $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array(
+ $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = [
'pseudoField' => "{$pf}_id",
'idCol' => "{$tName}_id",
'bao' => 'CRM_Core_BAO_Address',
- );
+ ];
$this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
}
else {
- $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array(
+ $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = [
'pseudoField' => 'state_province_abbreviation',
'idCol' => "{$tName}_id",
- );
+ ];
$this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
}
}
@@ -1190,11 +1185,11 @@ public function addHierarchicalElements() {
$this->_element[$provider] = 1;
}
if ($pf == 'country' || $pf == 'county') {
- $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array(
+ $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = [
'pseudoField' => "{$pf}_id",
'idCol' => "{$tName}_id",
'bao' => 'CRM_Core_BAO_Address',
- );
+ ];
$this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
}
else {
@@ -1202,7 +1197,7 @@ public function addHierarchicalElements() {
}
}
- if (in_array($pf, array('state_province', 'country', 'county'))) {
+ if (in_array($pf, ['state_province', 'country', 'county'])) {
$this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
}
else {
@@ -1292,7 +1287,7 @@ public function addHierarchicalElements() {
// table should be present in $this->_whereTables,
// to add its condition in location type join, CRM-3939.
if ($addWhereCount) {
- $locClause = array();
+ $locClause = [];
foreach ($this->_whereTables as $tableName => $clause) {
if (!empty($locationTypeJoin[$tableName])) {
$locClause[] = $locationTypeJoin[$tableName];
@@ -1309,7 +1304,7 @@ public function addHierarchicalElements() {
$customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
foreach ($locTypeName as $name => $dnc) {
- $this->_locationSpecificCustomFields[$cfID] = array($name, array_search($name, $locationTypes));
+ $this->_locationSpecificCustomFields[$cfID] = [$name, array_search($name, $locationTypes)];
$fieldName = "$name-custom_{$cfID}";
$tName = "$name-address-custom-{$cfID}";
$aName = "`$name-address-custom-{$cfID}`";
@@ -1384,7 +1379,9 @@ public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALS
}
}
elseif ($sortByChar) {
- $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
+ // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
+ // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
+ $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
$from = $this->_simpleFromClause;
}
elseif ($groupContacts) {
@@ -1419,13 +1416,13 @@ public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALS
$group->find(TRUE);
if (!isset($group->saved_search_id)) {
- $tbName = "`civicrm_group_contact-{$groupId}`";
+ $tbName = "civicrm_group_contact";
// CRM-17254 don't retrieve extra fields if contact_id is specifically requested
// as this will add load to an intentionally light query.
// ideally this code would be removed as it appears to be to support CRM-1203
// and passing in the required returnProperties from the url would
// make more sense that globally applying the requirements of one form.
- if (($this->_returnProperties != array('contact_id'))) {
+ if (($this->_returnProperties != ['contact_id'])) {
$this->_select['group_contact_id'] = "$tbName.id as group_contact_id";
$this->_element['group_contact_id'] = 1;
$this->_select['status'] = "$tbName.status as status";
@@ -1444,11 +1441,7 @@ public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALS
}
}
- $select = "SELECT ";
- if (isset($this->_distinctComponentClause)) {
- $select .= "{$this->_distinctComponentClause}, ";
- }
- $select .= implode(', ', $this->_select);
+ $select = $this->getSelect();
$from = $this->_fromClause;
}
@@ -1482,7 +1475,7 @@ public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALS
$this->filterRelatedContacts($from, $where, $having);
}
- return array($select, $from, $where, $having);
+ return [$select, $from, $where, $having];
}
/**
@@ -1551,19 +1544,51 @@ public static function fixDateValues($relative, &$from, &$to) {
* @return array
*/
public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
- $entityReferenceFields = array()) {
- $params = array();
+ $entityReferenceFields = []) {
+ $params = [];
if (empty($formValues)) {
return $params;
}
self::filterCountryFromValuesIfStateExists($formValues);
- foreach ($formValues as $id => &$val) {
- // CRM-19374 - we don't want to change $val in $formValues.
- // Assign it to a temp variable which operates while iteration.
- $values = $val;
+ // Handle relative dates first
+ foreach (array_keys($formValues) as $id) {
+ if (preg_match('/_date_relative$/', $id) ||
+ $id == 'event_relative' ||
+ $id == 'case_from_relative' ||
+ $id == 'case_to_relative' ||
+ $id == 'participant_relative'
+ ) {
+ if ($id == 'event_relative') {
+ $fromRange = 'event_start_date_low';
+ $toRange = 'event_end_date_high';
+ }
+ elseif ($id == 'participant_relative') {
+ $fromRange = 'participant_register_date_low';
+ $toRange = 'participant_register_date_high';
+ }
+ elseif ($id == 'case_from_relative') {
+ $fromRange = 'case_from_start_date_low';
+ $toRange = 'case_from_start_date_high';
+ }
+ elseif ($id == 'case_to_relative') {
+ $fromRange = 'case_to_end_date_low';
+ $toRange = 'case_to_end_date_high';
+ }
+ else {
+ $dateComponent = explode('_date_relative', $id);
+ $fromRange = "{$dateComponent[0]}_date_low";
+ $toRange = "{$dateComponent[0]}_date_high";
+ }
+
+ if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
+ CRM_Contact_BAO_Query::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
+ }
+ }
+ }
+ foreach ($formValues as $id => $values) {
if (self::isAlreadyProcessedForQueryFormat($values)) {
$params[] = $values;
continue;
@@ -1573,19 +1598,19 @@ public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals
// The form uses 1 field to represent two db fields
if ($id == 'contact_type' && $values && (!is_array($values) || !array_intersect(array_keys($values), CRM_Core_DAO::acceptedSQLOperators()))) {
- $contactType = array();
- $subType = array();
+ $contactType = [];
+ $subType = [];
foreach ((array) $values as $key => $type) {
- $types = explode('__', is_numeric($type) ? $key : $type);
+ $types = explode('__', is_numeric($type) ? $key : $type, 2);
$contactType[$types[0]] = $types[0];
// Add sub-type if specified
if (!empty($types[1])) {
$subType[$types[1]] = $types[1];
}
}
- $params[] = array('contact_type', 'IN', $contactType, 0, 0);
+ $params[] = ['contact_type', 'IN', $contactType, 0, 0];
if ($subType) {
- $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
+ $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
}
}
elseif ($id == 'privacy') {
@@ -1593,14 +1618,22 @@ public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals
$op = !empty($formValues['privacy']['do_not_toggle']) ? '=' : '!=';
foreach ($formValues['privacy'] as $key => $value) {
if ($value) {
- $params[] = array($key, $op, $value, 0, 0);
+ $params[] = [$key, $op, $value, 0, 0];
}
}
}
}
elseif ($id == 'email_on_hold') {
- if ($formValues['email_on_hold']['on_hold']) {
- $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
+ if ($onHoldValue = CRM_Utils_Array::value('email_on_hold', $formValues)) {
+ // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
+ // so in 5.11 we have an extra if that should become redundant over time.
+ // https://lab.civicrm.org/dev/core/issues/745
+ // @todo this renaming of email_on_hold to on_hold needs revisiting
+ // it preceeds recent changes but causes the default not to reload.
+ $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
+ if (!empty($onHoldValue)) {
+ $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
+ }
}
}
elseif (substr($id, 0, 7) == 'custom_'
@@ -1618,43 +1651,12 @@ public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals
$id == 'case_to_relative' ||
$id == 'participant_relative'
) {
- if ($id == 'event_relative') {
- $fromRange = 'event_start_date_low';
- $toRange = 'event_end_date_high';
- }
- elseif ($id == 'participant_relative') {
- $fromRange = 'participant_register_date_low';
- $toRange = 'participant_register_date_high';
- }
- elseif ($id == 'case_from_relative') {
- $fromRange = 'case_from_start_date_low';
- $toRange = 'case_from_start_date_high';
- }
- elseif ($id == 'case_to_relative') {
- $fromRange = 'case_to_end_date_low';
- $toRange = 'case_to_end_date_high';
- }
- else {
- $dateComponent = explode('_date_relative', $id);
- $fromRange = "{$dateComponent[0]}_date_low";
- $toRange = "{$dateComponent[0]}_date_high";
- }
-
- if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
- // relative dates are not processed correctly as lower date value were ignored,
- // to ensure both high and low date value got added IF there is relative date,
- // we need to reset $formValues by unset and then adding again via CRM_Contact_BAO_Query::fixDateValues(...)
- if (!empty($formValues[$id])) {
- unset($formValues[$fromRange]);
- unset($formValues[$toRange]);
- }
- CRM_Contact_BAO_Query::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
- continue;
- }
+ // Already handled in previous loop
+ continue;
}
elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
FALSE)) {
- $params[] = array($id, 'IN', explode(',', $values), 0, 0);
+ $params[] = [$id, 'IN', explode(',', $values), 0, 0];
}
else {
$values = CRM_Contact_BAO_Query::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
@@ -1676,14 +1678,14 @@ public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals
*
*/
public static function legacyConvertFormValues($id, &$values) {
- $legacyElements = array(
+ $legacyElements = [
'group',
'tag',
'contact_tags',
'contact_type',
'membership_type_id',
'membership_status_id',
- );
+ ];
if (in_array($id, $legacyElements) && is_array($values)) {
// prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
// as per the recent Search fixes $values need to be in standard array(id1, id2) format
@@ -1718,7 +1720,7 @@ public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals =
}
if (!$skipWhere) {
- $skipWhere = array(
+ $skipWhere = [
'task',
'radio_ts',
'uf_group_id',
@@ -1726,7 +1728,7 @@ public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals =
'qfKey',
'operator',
'display_relationship_type',
- );
+ ];
}
if (in_array($id, $skipWhere) ||
@@ -1745,7 +1747,7 @@ public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals =
}
if (!$likeNames) {
- $likeNames = array('sort_name', 'email', 'note', 'display_name');
+ $likeNames = ['sort_name', 'email', 'note', 'display_name'];
}
// email comes in via advanced search
@@ -1755,18 +1757,18 @@ public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals =
}
if (!$useEquals && in_array($id, $likeNames)) {
- $result = array($id, 'LIKE', $values, 0, 1);
+ $result = [$id, 'LIKE', $values, 0, 1];
}
elseif (is_string($values) && strpos($values, '%') !== FALSE) {
- $result = array($id, 'LIKE', $values, 0, 0);
+ $result = [$id, 'LIKE', $values, 0, 0];
}
elseif ($id == 'contact_type' ||
(!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO::acceptedSQLOperators(), TRUE))
) {
- $result = array($id, 'IN', $values, 0, $wildcard);
+ $result = [$id, 'IN', $values, 0, $wildcard];
}
else {
- $result = array($id, '=', $values, 0, $wildcard);
+ $result = [$id, '=', $values, 0, $wildcard];
}
return $result;
@@ -1779,6 +1781,11 @@ public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals =
* @param string $apiEntity
*/
public function whereClauseSingle(&$values, $apiEntity = NULL) {
+ if ($this->isARelativeDateField($values[0])) {
+ $this->buildRelativeDateQuery($values);
+ return;
+ }
+
// do not process custom fields or prefixed contact ids or component params
if (CRM_Core_BAO_CustomField::getKeyID($values[0]) ||
(substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) ||
@@ -1901,6 +1908,8 @@ public function whereClauseSingle(&$values, $apiEntity = NULL) {
case 'activity_date':
case 'activity_date_low':
case 'activity_date_high':
+ case 'activity_date_time_low':
+ case 'activity_date_time_high':
case 'activity_role':
case 'activity_status_id':
case 'activity_status':
@@ -2002,6 +2011,8 @@ public function whereClauseSingle(&$values, $apiEntity = NULL) {
case 'prox_postal_code':
case 'prox_state_province_id':
case 'prox_country_id':
+ case 'prox_geo_code_1':
+ case 'prox_geo_code_2':
// handled by the proximity_distance clause
return;
@@ -2019,8 +2030,8 @@ public function whereClauseSingle(&$values, $apiEntity = NULL) {
* @return string
*/
public function whereClause($apiEntity = NULL) {
- $this->_where[0] = array();
- $this->_qill[0] = array();
+ $this->_where[0] = [];
+ $this->_qill[0] = [];
$this->includeContactIds();
if (!empty($this->_params)) {
@@ -2031,6 +2042,18 @@ public function whereClause($apiEntity = NULL) {
// check for both id and contact_id
if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
$this->_where[0][] = self::buildClause("contact_a.id", $this->_params[$id][1], $this->_params[$id][2]);
+ $field = CRM_Utils_Array::value('id', $this->_fields);
+ list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(
+ 'CRM_Contact_BAO_Contact',
+ "contact_a.id",
+ $this->_params[$id][2],
+ $this->_params[$id][1]
+ );
+ $this->_qill[0][] = ts("%1 %2 %3", [
+ 1 => $field['title'],
+ 2 => $qillop,
+ 3 => $qillVal,
+ ]);
}
else {
$this->whereClauseSingle($this->_params[$id], $apiEntity);
@@ -2052,8 +2075,8 @@ public function whereClause($apiEntity = NULL) {
$this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
}
- $clauses = array();
- $andClauses = array();
+ $clauses = [];
+ $andClauses = [];
$validClauses = 0;
if (!empty($this->_where)) {
@@ -2094,10 +2117,10 @@ public function restWhere(&$values) {
$wildcard = CRM_Utils_Array::value(4, $values);
if (isset($grouping) && empty($this->_where[$grouping])) {
- $this->_where[$grouping] = array();
+ $this->_where[$grouping] = [];
}
- $multipleFields = array('url');
+ $multipleFields = ['url'];
//check if the location type exists for fields
$lType = '';
@@ -2122,8 +2145,7 @@ public function restWhere(&$values) {
$setTables = TRUE;
- $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
- $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
+ $locationType = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
if (isset($locType[1]) && is_numeric($locType[1])) {
$lType = $locationType[$locType[1]];
}
@@ -2142,8 +2164,9 @@ public function restWhere(&$values) {
}
$this->_where[$grouping][] = self::buildClause($where, $op, $value);
+ $this->_tables[$aName] = $this->_whereTables[$aName] = 1;
list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
}
elseif (!empty($field['pseudoconstant'])) {
$this->optionValueQuery(
@@ -2170,9 +2193,10 @@ public function restWhere(&$values) {
}
$this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
+ $this->_tables[$aName] = $this->_whereTables[$aName] = 1;
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
}
elseif ($name === 'world_region') {
$this->optionValueQuery(
@@ -2203,14 +2227,15 @@ public function restWhere(&$values) {
}
}
elseif ($name === 'name') {
- $value = $strtolower(CRM_Core_DAO::escapeString($value));
+ $value = CRM_Core_DAO::escapeString($value);
if ($wildcard) {
$op = 'LIKE';
$value = self::getWildCardedValue($wildcard, $op, $value);
}
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
- $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'");
+ CRM_Core_Error::deprecatedFunctionWarning('Untested code path');
+ // @todo it's likely this code path is obsolete / never called. It is definitely not
+ // passed through in our test suite.
+ $this->_where[$grouping][] = self::buildClause($field['where'], $op, "'$value'");
$this->_qill[$grouping][] = "$field[title] $op \"$value\"";
}
elseif ($name === 'current_employer') {
@@ -2226,7 +2251,8 @@ public function restWhere(&$values) {
$this->_qill[$grouping][] = "$field[title] $op \"$value\"";
}
elseif ($name === 'email_greeting') {
- $filterCondition = array('greeting_type' => 'email_greeting');
+ CRM_Core_Error::deprecatedFunctionWarning('pass in email_greeting_id or email_greeting_display');
+ $filterCondition = ['greeting_type' => 'email_greeting'];
$this->optionValueQuery(
$name, $op, $value, $grouping,
CRM_Core_PseudoConstant::greeting($filterCondition),
@@ -2235,7 +2261,8 @@ public function restWhere(&$values) {
);
}
elseif ($name === 'postal_greeting') {
- $filterCondition = array('greeting_type' => 'postal_greeting');
+ CRM_Core_Error::deprecatedFunctionWarning('pass in postal_greeting_id or postal_greeting_display');
+ $filterCondition = ['greeting_type' => 'postal_greeting'];
$this->optionValueQuery(
$name, $op, $value, $grouping,
CRM_Core_PseudoConstant::greeting($filterCondition),
@@ -2244,7 +2271,8 @@ public function restWhere(&$values) {
);
}
elseif ($name === 'addressee') {
- $filterCondition = array('greeting_type' => 'addressee');
+ CRM_Core_Error::deprecatedFunctionWarning('pass in addressee_id or addressee_display');
+ $filterCondition = ['greeting_type' => 'addressee'];
$this->optionValueQuery(
$name, $op, $value, $grouping,
CRM_Core_PseudoConstant::greeting($filterCondition),
@@ -2255,7 +2283,7 @@ public function restWhere(&$values) {
elseif (substr($name, 0, 4) === 'url-') {
$tName = 'civicrm_website';
$this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
- $value = $strtolower(CRM_Core_DAO::escapeString($value));
+ $value = CRM_Core_DAO::escapeString($value);
if ($wildcard) {
$op = 'LIKE';
$value = self::getWildCardedValue($wildcard, $op, $value);
@@ -2282,8 +2310,7 @@ public function restWhere(&$values) {
//get the location name
list($tName, $fldName) = self::getLocationTableName($field['where'], $locType);
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $fieldName = "LOWER(`$tName`.$fldName)";
+ $fieldName = "`$tName`.$fldName";
// we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
$this->_tables[$tName] = $this->_whereTables[$tName] = 1;
@@ -2294,21 +2321,16 @@ public function restWhere(&$values) {
$fieldName = "contact_a.{$fieldName}";
}
else {
- if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $fieldName = "LOWER({$field['where']})";
- }
- else {
- $fieldName = "{$field['where']}";
- }
+ $fieldName = $field['where'];
}
}
list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, $field['title'], $value, $op);
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [
1 => $field['title'],
2 => $qillop,
- 3 => (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) ? $qillVal : "'$qillVal'"));
+ 3 => (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) ? $qillVal : "'$qillVal'",
+ ]);
if (is_array($value)) {
// traditionally an array being passed has been a fatal error. We can take advantage of this to add support
@@ -2321,20 +2343,17 @@ public function restWhere(&$values) {
//Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
//so this condition will satisfy the search for now
if (strpos($op, 'IN') !== FALSE) {
- $value = array($op => $value);
+ $value = [$op => $value];
}
// we don't know when this might happen
else {
- CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
+ CRM_Core_Error::fatal(ts("%1 is not a valid operator", [1 => $operator]));
}
}
}
$this->_where[$grouping][] = CRM_Core_DAO::createSQLFilter($fieldName, $value, $type);
}
else {
- if (!strpos($op, 'IN')) {
- $value = $strtolower($value);
- }
if ($wildcard) {
$op = 'LIKE';
$value = self::getWildCardedValue($wildcard, $op, $value);
@@ -2365,8 +2384,8 @@ public static function getLocationTableName(&$where, &$locType) {
list($tbName, $fldName) = explode(".", $where);
//get the location name
- $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
- $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
+ $locationType = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
+ $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
if (in_array($locType[0], $specialFields)) {
//hack to fix / special handing for phone_ext
if ($locType[0] == 'phone_ext') {
@@ -2380,7 +2399,7 @@ public static function getLocationTableName(&$where, &$locType) {
}
}
elseif (in_array($locType[0],
- array(
+ [
'address_name',
'street_address',
'street_name',
@@ -2395,18 +2414,18 @@ public static function getLocationTableName(&$where, &$locType) {
'geo_code_1',
'geo_code_2',
'master_id',
- )
+ ]
)) {
//fix for search by profile with address fields.
$tName = "{$locationType[$locType[1]]}-address";
}
elseif (in_array($locType[0],
- array(
+ [
'on_hold',
'signature_html',
'signature_text',
'is_bulkmail',
- )
+ ]
)) {
$tName = "{$locationType[$locType[1]]}-email";
}
@@ -2420,7 +2439,7 @@ public static function getLocationTableName(&$where, &$locType) {
$tName = "{$locationType[$locType[1]]}-{$locType[0]}";
}
$tName = str_replace(' ', '_', $tName);
- return array($tName, $fldName);
+ return [$tName, $fldName];
}
CRM_Core_Error::fatal();
}
@@ -2434,7 +2453,7 @@ public static function getLocationTableName(&$where, &$locType) {
* values for this query
*/
public function store($dao) {
- $value = array();
+ $value = [];
foreach ($this->_element as $key => $dontCare) {
if (property_exists($dao, $key)) {
@@ -2446,7 +2465,7 @@ public function store($dao) {
$count = 1;
foreach ($values as $v) {
if (!array_key_exists($v, $current)) {
- $current[$v] = array();
+ $current[$v] = [];
}
//bad hack for im_provider
if ($lastElement == 'provider_id') {
@@ -2554,24 +2573,22 @@ public static function fromClause(&$tables, $inner = NULL, $right = NULL, $prima
}
if (!empty($tables['civicrm_worldregion'])) {
- $tables = array_merge(array('civicrm_country' => 1), $tables);
+ $tables = array_merge(['civicrm_country' => 1], $tables);
}
if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) ||
- CRM_Utils_Array::value('civicrm_county', $tables)
- ) && empty($tables['civicrm_address'])
- ) {
- $tables = array_merge(array('civicrm_address' => 1),
+ CRM_Utils_Array::value('civicrm_county', $tables)) && empty($tables['civicrm_address'])) {
+ $tables = array_merge(['civicrm_address' => 1],
$tables
);
}
// add group_contact and group table is subscription history is present
if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
- $tables = array_merge(array(
- 'civicrm_group' => 1,
- 'civicrm_group_contact' => 1,
- ),
+ $tables = array_merge([
+ 'civicrm_group' => 1,
+ 'civicrm_group_contact' => 1,
+ ],
$tables
);
}
@@ -2605,7 +2622,7 @@ public static function fromClause(&$tables, $inner = NULL, $right = NULL, $prima
$tempTable[$k . ".$key"] = $key;
}
ksort($tempTable);
- $newTables = array();
+ $newTables = [];
foreach ($tempTable as $key) {
$newTables[$key] = $tables[$key];
}
@@ -2638,176 +2655,180 @@ public static function fromClause(&$tables, $inner = NULL, $right = NULL, $prima
continue;
}
- $limitToPrimaryClause = $primaryLocation ? "AND {$name}.is_primary = 1" : '';
-
- switch ($name) {
- case 'civicrm_address':
- //CRM-14263 further handling of address joins further down...
- $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
- continue;
-
- case 'civicrm_phone':
- $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
- continue;
+ $from .= self::getEntitySpecificJoins($name, $mode, $side, $primaryLocation);
+ }
+ return $from;
+ }
- case 'civicrm_email':
- $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
- continue;
+ /**
+ * Get join statements for the from clause depending on entity type
+ *
+ * @param string $name
+ * @param int $mode
+ * @param string $side
+ * @param string $primaryLocation
+ * @return string
+ */
+ protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
+ $limitToPrimaryClause = $primaryLocation ? "AND {$name}.is_primary = 1" : '';
+ switch ($name) {
+ case 'civicrm_address':
+ //CRM-14263 further handling of address joins further down...
+ return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
- case 'civicrm_im':
- $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
- continue;
+ case 'civicrm_state_province':
+ // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
+ // but that will have been implied-in by the calling function.
+ // test cover in testContactIDQuery
+ return " $side JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
- case 'im_provider':
- $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
- $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
- $from .= " $side JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)";
- continue;
+ case 'civicrm_country':
+ // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
+ // but that will have been implied-in by the calling function.
+ // test cover in testContactIDQuery
+ return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
- case 'civicrm_openid':
- $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
- continue;
+ case 'civicrm_phone':
+ return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
- case 'civicrm_worldregion':
- $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
- $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
- continue;
+ case 'civicrm_email':
+ return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
- case 'civicrm_location_type':
- $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
- continue;
+ case 'civicrm_im':
+ return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
- case 'civicrm_group':
- $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
- continue;
+ case 'im_provider':
+ $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
+ $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
+ $from .= " $side JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)";
+ return $from;
- case 'civicrm_group_contact':
- $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
- continue;
+ case 'civicrm_openid':
+ return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
- case 'civicrm_group_contact_cache':
- $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
- continue;
+ case 'civicrm_worldregion':
+ // We can be sure from the calling function that country will already be joined in.
+ // we really don't need world_region - we could use a pseudoconstant for it.
+ return "$side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
- case 'civicrm_activity':
- case 'civicrm_activity_tag':
- case 'activity_type':
- case 'activity_status':
- case 'parent_id':
- case 'civicrm_activity_contact':
- case 'source_contact':
- case 'activity_priority':
- $from .= CRM_Activity_BAO_Query::from($name, $mode, $side);
- continue;
+ case 'civicrm_location_type':
+ return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
- case 'civicrm_entity_tag':
- $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
- civicrm_entity_tag.entity_id = contact_a.id ) ";
- continue;
+ case 'civicrm_group':
+ return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
- case 'civicrm_note':
- $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
- contact_a.id = civicrm_note.entity_id ) ";
- continue;
+ case 'civicrm_group_contact':
+ return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
- case 'civicrm_subscription_history':
- $from .= " $side JOIN civicrm_subscription_history
- ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
- AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
- continue;
+ case 'civicrm_group_contact_cache':
+ return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
- case 'civicrm_relationship':
- if (self::$_relType == 'reciprocal') {
- if (self::$_relationshipTempTable) {
- // we have a temptable to join on
- $tbl = self::$_relationshipTempTable;
- $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
- }
- else {
- $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
- $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)";
- }
- }
- elseif (self::$_relType == 'b') {
- $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
- $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
+ case 'civicrm_activity':
+ case 'civicrm_activity_tag':
+ case 'activity_type':
+ case 'activity_status':
+ case 'parent_id':
+ case 'civicrm_activity_contact':
+ case 'source_contact':
+ case 'activity_priority':
+ return CRM_Activity_BAO_Query::from($name, $mode, $side);
+
+ case 'civicrm_entity_tag':
+ $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
+ return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
+
+ case 'civicrm_note':
+ $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
+ return "$from AND contact_a.id = civicrm_note.entity_id ) ";
+
+ case 'civicrm_subscription_history':
+ $from = " $side JOIN civicrm_subscription_history";
+ $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
+ return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
+
+ case 'civicrm_relationship':
+ if (self::$_relType == 'reciprocal') {
+ if (self::$_relationshipTempTable) {
+ // we have a temptable to join on
+ $tbl = self::$_relationshipTempTable;
+ return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
}
else {
- $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
- $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
+ $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
+ $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)";
+ return $from;
}
- continue;
+ }
+ elseif (self::$_relType == 'b') {
+ $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
+ return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
+ }
+ else {
+ $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
+ return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
+ }
- case 'civicrm_log':
- $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
- $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
- continue;
+ case 'civicrm_log':
+ $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
+ return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
- case 'civicrm_tag':
- $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
- continue;
+ case 'civicrm_tag':
+ return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
- case 'civicrm_grant':
- $from .= CRM_Grant_BAO_Query::from($name, $mode, $side);
- continue;
+ case 'civicrm_grant':
+ return CRM_Grant_BAO_Query::from($name, $mode, $side);
- case 'civicrm_campaign':
- //Move to default case if not in either mode.
- if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
- $from .= CRM_Contribute_BAO_Query::from($name, $mode, $side);
- continue;
- }
- elseif ($mode & CRM_Contact_BAO_Query::MODE_MAILING) {
- $from .= CRM_Mailing_BAO_Query::from($name, $mode, $side);
- continue;
- }
- elseif ($mode & CRM_Contact_BAO_Query::MODE_CAMPAIGN) {
- $from .= CRM_Campaign_BAO_Query::from($name, $mode, $side);
- continue;
- }
+ case 'civicrm_website':
+ return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
- case 'civicrm_website':
- $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
- continue;
+ case 'civicrm_campaign':
+ //Move to default case if not in either mode.
+ if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
+ return CRM_Contribute_BAO_Query::from($name, $mode, $side);
+ }
+ elseif ($mode & CRM_Contact_BAO_Query::MODE_MAILING) {
+ return CRM_Mailing_BAO_Query::from($name, $mode, $side);
+ }
+ elseif ($mode & CRM_Contact_BAO_Query::MODE_CAMPAIGN) {
+ return CRM_Campaign_BAO_Query::from($name, $mode, $side);
+ }
- default:
- $locationTypeName = '';
- if (strpos($name, '-address') != 0) {
- $locationTypeName = 'address';
- }
- elseif (strpos($name, '-phone') != 0) {
- $locationTypeName = 'phone';
- }
- elseif (strpos($name, '-email') != 0) {
- $locationTypeName = 'email';
- }
- elseif (strpos($name, '-im') != 0) {
- $locationTypeName = 'im';
- }
- elseif (strpos($name, '-openid') != 0) {
- $locationTypeName = 'openid';
- }
+ default:
+ $locationTypeName = '';
+ if (strpos($name, '-address') != 0) {
+ $locationTypeName = 'address';
+ }
+ elseif (strpos($name, '-phone') != 0) {
+ $locationTypeName = 'phone';
+ }
+ elseif (strpos($name, '-email') != 0) {
+ $locationTypeName = 'email';
+ }
+ elseif (strpos($name, '-im') != 0) {
+ $locationTypeName = 'im';
+ }
+ elseif (strpos($name, '-openid') != 0) {
+ $locationTypeName = 'openid';
+ }
- if ($locationTypeName) {
- //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
- $parts = explode('-', $name);
- $locationTypes = CRM_Core_BAO_Address::buildOptions('location_type_id', 'get');
- foreach ($locationTypes as $locationTypeID => $locationType) {
- if ($parts[0] == str_replace(' ', '_', $locationType)) {
- $locationID = $locationTypeID;
- }
+ if ($locationTypeName) {
+ //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
+ $parts = explode('-', $name);
+ $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
+ foreach ($locationTypes as $locationTypeID => $locationType) {
+ if ($parts[0] == str_replace(' ', '_', $locationType)) {
+ $locationID = $locationTypeID;
}
- $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
}
- else {
- $from .= CRM_Core_Component::from($name, $mode, $side);
- }
- $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
+ $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
+ }
+ else {
+ $from = CRM_Core_Component::from($name, $mode, $side);
+ }
+ $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
- continue;
- }
+ return $from;
}
- return $from;
}
/**
@@ -2831,8 +2852,8 @@ public function deletedContacts($values) {
public function contactType(&$values) {
list($name, $op, $value, $grouping, $wildcard) = $values;
- $subTypes = array();
- $clause = array();
+ $subTypes = [];
+ $clause = [];
// account for search builder mapping multiple values
if (!is_array($value)) {
@@ -2910,7 +2931,7 @@ public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
$value = $value[$op];
}
- $clause = array();
+ $clause = [];
$alias = "contact_a.contact_sub_type";
$qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
@@ -2933,7 +2954,7 @@ public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
if (!empty($clause)) {
$this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )";
}
- $this->_qill[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
+ $this->_qill[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
}
/**
@@ -2957,9 +2978,9 @@ public function group($values) {
$value = NULL;
}
- if (count($value) > 1) {
+ if (is_array($value) && count($value) > 1) {
if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
- CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $op)));
+ CRM_Core_Error::fatal(ts("%1 is not a valid operator", [1 => $op]));
}
$this->_useDistinct = TRUE;
}
@@ -2972,34 +2993,22 @@ public function group($values) {
$value = array_keys($this->getGroupsFromTypeCriteria($value));
}
- $regularGroupIDs = $smartGroupIDs = array();
+ $regularGroupIDs = $smartGroupIDs = [];
foreach ((array) $value as $id) {
if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
$smartGroupIDs[] = $id;
}
else {
- $regularGroupIDs[] = $id;
+ $regularGroupIDs[] = trim($id);
}
}
+ $hasNonSmartGroups = count($regularGroupIDs);
$isNotOp = ($op == 'NOT IN' || $op == '!=');
- $statii = array();
- $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
- if ($gcsValues &&
- is_array($gcsValues[2])
- ) {
- foreach ($gcsValues[2] as $k => $v) {
- if ($v) {
- $statii[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
- }
- }
- }
- else {
- $statii[] = "'Added'";
- }
- $groupClause = array();
- if (count($regularGroupIDs) || empty($value)) {
+ $statusJoinClause = $this->getGroupStatusClause($grouping);
+ $groupClause = [];
+ if ($hasNonSmartGroups || empty($value)) {
// include child groups IDs if any
$childGroupIds = (array) CRM_Contact_BAO_Group::getChildGroupIds($regularGroupIDs);
foreach ($childGroupIds as $key => $id) {
@@ -3012,14 +3021,24 @@ public function group($values) {
$regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
}
+ if (empty($regularGroupIDs)) {
+ $regularGroupIDs = [0];
+ }
+
// if $regularGroupIDs is populated with regular child group IDs
// then change the mysql operator to desired
if (count($regularGroupIDs) > 1) {
$op = strpos($op, 'IN') ? $op : ($op == '!=') ? 'NOT IN' : 'IN';
}
- $groupIds = implode(',', (array) $regularGroupIDs);
- $gcTable = "`civicrm_group_contact-{$groupIds}`";
- $joinClause = array("contact_a.id = {$gcTable}.contact_id");
+ $groupIds = '';
+ if (!empty($regularGroupIDs)) {
+ $groupIds = CRM_Utils_Type::validate(
+ implode(',', (array) $regularGroupIDs),
+ 'CommaSeparatedIntegers'
+ );
+ }
+ $gcTable = "`civicrm_group_contact-" . uniqid() . "`";
+ $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
if (strpos($op, 'IN') !== FALSE) {
$clause = "{$gcTable}.group_id $op ( $groupIds ) ";
@@ -3032,27 +3051,52 @@ public function group($values) {
}
$groupClause[] = "( {$clause} )";
- if ($statii) {
- $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
+ if ($statusJoinClause) {
+ $joinClause[] = "{$gcTable}.$statusJoinClause";
}
$this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
}
//CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
- if (count($smartGroupIDs)) {
- $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
+ $groupContactCacheClause = '';
+ if (count($smartGroupIDs) || empty($value)) {
+ $this->_groupUniqueKey = uniqid();
+ $this->_groupKeys[] = $this->_groupUniqueKey;
+ $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
+ $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
+ if (!empty($groupContactCacheClause)) {
+ if ($isNotOp) {
+ $groupIds = implode(',', (array) $smartGroupIDs);
+ $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
+ $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
+ $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
+ if (strpos($op, 'IN') !== FALSE) {
+ $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
+ }
+ else {
+ $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
+ }
+ }
+ $groupClause[] = " ( {$groupContactCacheClause} ) ";
+ }
}
$and = ($op == 'IS NULL') ? ' AND ' : ' OR ';
- $this->_where[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
+ if (!empty($groupClause)) {
+ $this->_where[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
+ }
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
- $this->_qill[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
+ $this->_qill[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
if (strpos($op, 'NULL') === FALSE) {
- $this->_qill[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
+ $this->_qill[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $this->getSelectedGroupStatuses($grouping))]);
}
}
+ public function getGroupCacheTableKeys() {
+ return $this->_groupKeys;
+ }
+
/**
* Function translates selection of group type into a list of groups.
* @param $value
@@ -3060,7 +3104,7 @@ public function group($values) {
* @return array
*/
public function getGroupsFromTypeCriteria($value) {
- $groupIds = array();
+ $groupIds = [];
foreach ((array) $value as $groupTypeValue) {
$groupList = CRM_Core_PseudoConstant::group($groupTypeValue);
$groupIds = ($groupIds + $groupList);
@@ -3069,24 +3113,33 @@ public function getGroupsFromTypeCriteria($value) {
}
/**
- * @param array $groups
- * @param string $tableAlias
- * @param string $joinTable
- * @param string $op
+ * Prime smart group cache for smart groups in the search, and join
+ * civicrm_group_contact_cache table into the query.
*
- * @return null|string
+ * @param array $groups IDs of groups specified in search criteria.
+ * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
+ * @param string $joinTable Table on which to join civicrm_group_contact_cache
+ * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
+ * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
+ *
+ * @return string WHERE clause component for smart group criteria.
*/
- public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
+ public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
$isNullOp = (strpos($op, 'NULL') !== FALSE);
$groupsIds = $groups;
+
+ $operator = ['=' => 'IN', '!=' => 'NOT IN'];
+ if (!empty($operator[$op]) && is_array($groups)) {
+ $op = $operator[$op];
+ }
if (!$isNullOp && !$groups) {
return NULL;
}
elseif (strpos($op, 'IN') !== FALSE) {
- $groups = array($op => $groups);
+ $groups = [$op => $groups];
}
elseif (is_array($groups) && count($groups)) {
- $groups = array('IN' => $groups);
+ $groups = ['IN' => $groups];
}
// Find all the groups that are part of a saved search.
@@ -3108,16 +3161,15 @@ public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "
CRM_Contact_BAO_GroupContactCache::load($group);
}
}
- if ($group->N == 0) {
+ if ($group->N == 0 && $op != 'NOT IN') {
return NULL;
}
- if (!$tableAlias) {
- $tableAlias = "`civicrm_group_contact_cache_";
- $tableAlias .= ($isNullOp) ? "a`" : implode(',', (array) $groupsIds) . "`";
- }
+ $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
- $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
+ if ($op == 'NOT IN') {
+ return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
+ }
return self::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
}
@@ -3152,12 +3204,13 @@ public function tagSearch(&$values) {
$op = "LIKE";
$value = "%{$value}%";
+ $escapedValue = CRM_Utils_Type::escape("%{$value}%", 'String');
$useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
$tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
- $etTable = "`civicrm_entity_tag-" . $value . "`";
- $tTable = "`civicrm_tag-" . $value . "`";
+ $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
+ $tTable = "`civicrm_tag-" . uniqid() . "`";
if ($useAllTagTypes[2]) {
$this->_tables[$etTable] = $this->_whereTables[$etTable]
@@ -3165,8 +3218,8 @@ public function tagSearch(&$values) {
LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
// search tag in cases
- $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
- $tCaseTable = "`civicrm_case_tag-" . $value . "`";
+ $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
+ $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
$this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
= " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
LEFT JOIN civicrm_case
@@ -3175,8 +3228,8 @@ public function tagSearch(&$values) {
LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
// search tag in activities
- $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
- $tActTable = "`civicrm_act_tag-" . $value . "`";
+ $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
+ $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
@@ -3189,18 +3242,18 @@ public function tagSearch(&$values) {
LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
- $this->_where[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
- $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
+ $this->_where[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
+ $this->_qill[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
}
else {
- $etTable = "`civicrm_entity_tag-" . $value . "`";
- $tTable = "`civicrm_tag-" . $value . "`";
+ $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
+ $tTable = "`civicrm_tag-" . uniqid() . "`";
$this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
{$etTable}.entity_table = 'civicrm_contact' )
LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
$this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String');
- $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
+ $this->_qill[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
}
}
@@ -3212,7 +3265,7 @@ public function tagSearch(&$values) {
public function tag(&$values) {
list($name, $op, $value, $grouping, $wildcard) = $values;
- list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
+ list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
// API/Search Builder format array(operator => array(values))
if (is_array($value)) {
if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
@@ -3222,20 +3275,28 @@ public function tag(&$values) {
if (count($value) > 1) {
$this->_useDistinct = TRUE;
}
- $value = implode(',', (array) $value);
+ }
+
+ // implode array, then remove all spaces
+ $value = str_replace(' ', '', implode(',', (array) $value));
+ if (!empty($value)) {
+ $value = CRM_Utils_Type::validate(
+ $value,
+ 'CommaSeparatedIntegers'
+ );
}
$useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
$tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
- $etTable = "`civicrm_entity_tag-" . $value . "`";
+ $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
if ($useAllTagTypes[2]) {
$this->_tables[$etTable] = $this->_whereTables[$etTable]
= " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
// search tag in cases
- $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
+ $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
@@ -3246,7 +3307,7 @@ public function tag(&$values) {
AND civicrm_case.is_deleted = 0 )
LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
// search tag in activities
- $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
+ $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
$this->_tables[$etActTable] = $this->_whereTables[$etActTable]
= " LEFT JOIN civicrm_activity_contact
ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
@@ -3256,7 +3317,7 @@ public function tag(&$values) {
LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
// CRM-10338
- if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
+ if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
$this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
}
else {
@@ -3268,7 +3329,7 @@ public function tag(&$values) {
= " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
// CRM-10338
- if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
+ if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
// this converts IS (NOT)? EMPTY to IS (NOT)? NULL
$op = str_replace('EMPTY', 'NULL', $op);
$this->_where[$grouping][] = "{$etTable}.tag_id $op";
@@ -3282,7 +3343,7 @@ public function tag(&$values) {
$this->_where[$grouping][] = "{$etTable}.tag_id $op ( $value )";
}
}
- $this->_qill[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
+ $this->_qill[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
}
/**
@@ -3302,9 +3363,8 @@ public function notes(&$values) {
$this->_tables['civicrm_note'] = $this->_whereTables['civicrm_note']
= " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
- $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
$n = trim($value);
- $value = $strtolower(CRM_Core_DAO::escapeString($n));
+ $value = CRM_Core_DAO::escapeString($n);
if ($wildcard) {
if (strpos($value, '%') === FALSE) {
$value = "%$value%";
@@ -3316,7 +3376,7 @@ public function notes(&$values) {
}
$label = NULL;
- $clauses = array();
+ $clauses = [];
if ($noteOption % 2 == 0) {
$clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String');
$label = ts('Note: Body Only');
@@ -3327,7 +3387,7 @@ public function notes(&$values) {
}
$this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
list($qillOp, $qillVal) = self::buildQillForFieldValue(NULL, $name, $n, $op);
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
}
/**
@@ -3381,16 +3441,14 @@ public function sortName(&$values) {
$config = CRM_Core_Config::singleton();
- $sub = array();
+ $sub = [];
//By default, $sub elements should be joined together with OR statements (don't change this variable).
$subGlue = ' OR ';
- $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
-
$firstChar = substr($value, 0, 1);
$lastChar = substr($value, -1, 1);
- $quotes = array("'", '"');
+ $quotes = ["'", '"'];
// If string is quoted, strip quotes and otherwise don't alter it
if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
$value = trim($value, implode('', $quotes));
@@ -3400,22 +3458,19 @@ public function sortName(&$values) {
elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
$value = str_replace(' ', '%', $value);
}
- $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
+ $value = CRM_Core_DAO::escapeString(trim($value));
if (strlen($value)) {
- $fieldsub = array();
+ $fieldsub = [];
$value = "'" . self::getWildCardedValue($wildcard, $op, $value) . "'";
if ($fieldName == 'sort_name') {
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
+ $wc = "contact_a.sort_name";
}
else {
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
+ $wc = "contact_a.display_name";
}
$fieldsub[] = " ( $wc $op $value )";
if ($config->includeNickNameInName) {
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
+ $wc = "contact_a.nick_name";
$fieldsub[] = " ( $wc $op $value )";
}
if ($config->includeEmailInName) {
@@ -3446,7 +3501,7 @@ public function greetings(&$values) {
$name .= '_display';
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
- $this->_qill[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
+ $this->_qill[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
$this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value, 'String');
}
@@ -3474,7 +3529,7 @@ protected function email(&$values, $apiEntity) {
return;
}
- $n = strtolower(trim($value));
+ $n = trim($value);
if ($n) {
if (substr($n, 0, 1) == '"' &&
substr($n, -1, 1) == '"'
@@ -3536,7 +3591,7 @@ public function phone_option_group($values) {
* @param array $values
*/
public function street_address(&$values) {
- list($name, $op, $value, $grouping, $wildcard) = $values;
+ list($name, $op, $value, $grouping) = $values;
if (!$op) {
$op = 'LIKE';
@@ -3545,14 +3600,12 @@ public function street_address(&$values) {
$n = trim($value);
if ($n) {
- $value = strtolower($n);
if (strpos($value, '%') === FALSE) {
// only add wild card if not there
$value = "%{$value}%";
}
$op = 'LIKE';
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
+ $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, $value, 'String');
$this->_qill[$grouping][] = ts('Street') . " $op '$n'";
}
else {
@@ -3586,10 +3639,8 @@ public function street_number(&$values) {
$this->_qill[$grouping][] = ts('Street Number is even');
}
else {
- $value = strtolower($n);
-
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
+ $value = $n;
+ $this->_where[$grouping][] = self::buildClause('civicrm_address.street_number', $op, $value, 'String');
$this->_qill[$grouping][] = ts('Street Number') . " $op '$n'";
}
@@ -3605,9 +3656,9 @@ public function sortByCharacter(&$values) {
list($name, $op, $value, $grouping, $wildcard) = $values;
$name = trim($value);
- $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($name)) . "%'";
+ $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO::escapeWildCardString($name) . "%'";
$this->_where[$grouping][] = $cond;
- $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
+ $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
}
/**
@@ -3618,7 +3669,7 @@ public function includeContactIDs() {
return;
}
- $contactIds = array();
+ $contactIds = [];
foreach ($this->_params as $id => $values) {
if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
$contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN);
@@ -3668,11 +3719,11 @@ public function postalCode(&$values) {
}
elseif ($name == 'postal_code_low') {
$this->_where[$grouping][] = " ( $field >= '$val' ) ";
- $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
+ $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
}
elseif ($name == 'postal_code_high') {
$this->_where[$grouping][] = " ( $field <= '$val' ) ";
- $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
+ $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
}
}
@@ -3693,7 +3744,7 @@ public function locationType(&$values, $status = NULL) {
$this->_whereTables['civicrm_address'] = 1;
$locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
- $names = array();
+ $names = [];
foreach ($value as $id) {
$names[] = $locationType[$id];
}
@@ -3728,13 +3779,13 @@ public function country(&$values, $fromStateProvince = TRUE) {
}
$countryClause = $countryQill = NULL;
- if ($values && !empty($value)) {
+ if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) || ($values && !empty($value))) {
$this->_tables['civicrm_address'] = 1;
$this->_whereTables['civicrm_address'] = 1;
$countryClause = self::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, 'country_id', $value, $op);
- $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
+ $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
if (!$fromStateProvince) {
$this->_where[$grouping][] = $countryClause;
@@ -3744,13 +3795,13 @@ public function country(&$values, $fromStateProvince = TRUE) {
if ($fromStateProvince) {
if (!empty($countryClause)) {
- return array(
+ return [
$countryClause,
" ...AND... " . $countryQill,
- );
+ ];
}
else {
- return array(NULL, NULL);
+ return [NULL, NULL];
}
}
}
@@ -3768,7 +3819,7 @@ public function county(&$values, $status = NULL) {
if (!is_array($value)) {
// force the county to be an array
- $value = array($value);
+ $value = [$value];
}
// check if the values are ids OR names of the counties
@@ -3779,7 +3830,7 @@ public function county(&$values, $status = NULL) {
break;
}
}
- $names = array();
+ $names = [];
if ($op == '=') {
$op = 'IN';
}
@@ -3791,7 +3842,7 @@ public function county(&$values, $status = NULL) {
$op = str_replace('EMPTY', 'NULL', $op);
}
- if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
+ if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
$clause = "civicrm_address.county_id $op";
}
elseif ($inputFormat == 'id') {
@@ -3803,7 +3854,7 @@ public function county(&$values, $status = NULL) {
}
}
else {
- $inputClause = array();
+ $inputClause = [];
$county = CRM_Core_PseudoConstant::county();
foreach ($value as $name) {
$name = trim($name);
@@ -3851,7 +3902,7 @@ public function stateProvince(&$values, $status = NULL) {
$this->_where[$grouping][] = $clause;
list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
if (!$status) {
- $this->_qill[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
+ $this->_qill[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
}
else {
return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
@@ -3872,11 +3923,25 @@ public function changeLog(&$values) {
}
$name = trim($targetName[2]);
- $name = strtolower(CRM_Core_DAO::escapeString($name));
+ $name = CRM_Core_DAO::escapeString($name);
$name = $targetName[4] ? "%$name%" : $name;
$this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
$this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1;
- $this->_qill[$grouping][] = ts('Modified By') . " $name";
+ $fieldTitle = ts('Added By');
+ foreach ($this->_params as $params) {
+ if ($params[0] == 'log_date') {
+ if ($params[2] == 2) {
+ $fieldTitle = ts('Modified By');
+ }
+ break;
+ }
+ }
+ list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
+ $this->_qill[$grouping][] = ts("%1 %2 '%3'", [
+ 1 => $fieldTitle,
+ 2 => $qillop,
+ 3 => $qillVal,
+ ]);
}
/**
@@ -3933,7 +3998,7 @@ public function demographics(&$values) {
* @param $values
*/
public function privacy(&$values) {
- list($name, $op, $value, $grouping, $wildcard) = $values;
+ list($name, $op, $value, $grouping) = $values;
//fixed for profile search listing CRM-4633
if (strpbrk($value, "[")) {
$value = "'{$value}'";
@@ -3965,6 +4030,7 @@ public function privacyOptions($values) {
if ($opValues &&
strtolower($opValues[2] == 'AND')
) {
+ // @todo this line is logially unreachable
$operator = 'AND';
}
@@ -3976,8 +4042,8 @@ public function privacyOptions($values) {
$compareOP = '';
}
- $clauses = array();
- $qill = array();
+ $clauses = [];
+ $qill = [];
foreach ($value as $dontCare => $pOption) {
$clauses[] = " ( contact_a.{$pOption} = 1 ) ";
$field = CRM_Utils_Array::value($pOption, $this->_fields);
@@ -3996,7 +4062,7 @@ public function preferredCommunication(&$values) {
list($name, $op, $value, $grouping, $wildcard) = $values;
if (!is_array($value)) {
- $value = str_replace(array('(', ')'), '', explode(",", $value));
+ $value = str_replace(['(', ')'], '', explode(",", $value));
}
elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
@@ -4011,7 +4077,7 @@ public function preferredCommunication(&$values) {
}
$this->_where[$grouping][] = self::buildClause("contact_a.preferred_communication_method", $op, $value);
- $this->_qill[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
+ $this->_qill[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
}
/**
@@ -4029,7 +4095,6 @@ public function relationship(&$values) {
$relationType = $this->getWhereValues('relation_type_id', $grouping);
$targetName = $this->getWhereValues('relation_target_name', $grouping);
$relStatus = $this->getWhereValues('relation_status', $grouping);
- $relPermission = $this->getWhereValues('relation_permission', $grouping);
$targetGroup = $this->getWhereValues('relation_target_group', $grouping);
$nameClause = $name = NULL;
@@ -4039,48 +4104,65 @@ public function relationship(&$values) {
substr($name, -1, 1) == '"'
) {
$name = substr($name, 1, -1);
- $name = strtolower(CRM_Core_DAO::escapeString($name));
+ $name = CRM_Core_DAO::escapeString($name);
$nameClause = "= '$name'";
}
else {
- $name = strtolower(CRM_Core_DAO::escapeString($name));
+ $name = CRM_Core_DAO::escapeString($name);
$nameClause = "LIKE '%{$name}%'";
}
}
- $rTypeValues = array();
+ $relTypes = $relTypesIds = [];
if (!empty($relationType)) {
- $rel = explode('_', $relationType[2]);
- self::$_relType = $rel[1];
- $params = array('id' => $rel[0]);
- $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues);
- }
- if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
- // if we don't know which end of the relationship we are dealing with we'll create a temp table
- //@todo unless we are dealing with a target group
- self::$_relType = 'reciprocal';
+ $relationType[2] = (array) $relationType[2];
+ foreach ($relationType[2] as $relType) {
+ $rel = explode('_', $relType);
+ self::$_relType = $rel[1];
+ $params = ['id' => $rel[0]];
+ $typeValues = [];
+ $rTypeValue = CRM_Contact_BAO_RelationshipType::retrieve($params, $typeValues);
+ if (!empty($rTypeValue)) {
+ if ($rTypeValue->name_a_b == $rTypeValue->name_b_a) {
+ // if we don't know which end of the relationship we are dealing with we'll create a temp table
+ self::$_relType = 'reciprocal';
+ }
+ $relTypesIds[] = $rel[0];
+ $relTypes[] = $relType;
+ }
+ }
}
+
// if we are creating a temp table we build our own where for the relationship table
$relationshipTempTable = NULL;
- if (self::$_relType == 'reciprocal' && empty($targetGroup)) {
- $where = array();
+ if (self::$_relType == 'reciprocal') {
+ $where = [];
self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel');
if ($nameClause) {
$where[$grouping][] = " sort_name $nameClause ";
}
+ $groupJoinTable = "civicrm_relationship";
+ $groupJoinColumn = "contact_id_alt";
}
else {
$where = &$this->_where;
if ($nameClause) {
$where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
}
+ $groupJoinTable = "contact_b";
+ $groupJoinColumn = "id";
}
-
$allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
-
if ($nameClause || !$targetGroup) {
if (!empty($relationType)) {
- $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
+ $relQill = '';
+ foreach ($relTypes as $rel) {
+ if (!empty($relQill)) {
+ $relQill .= ' OR ';
+ }
+ $relQill .= $allRelationshipType[$rel];
+ }
+ $this->_qill[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
}
else {
$this->_qill[$grouping][] = $name;
@@ -4091,12 +4173,12 @@ public function relationship(&$values) {
if ($targetGroup) {
//add contacts from static groups
$this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact']
- = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'";
+ = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = {$groupJoinTable}.{$groupJoinColumn} AND civicrm_relationship_group_contact.status = 'Added'";
$groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
implode(",", $targetGroup[2]) . ") ) ";
//add contacts from saved searches
- $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
+ $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
//set the group where clause
if ($ssWhere) {
@@ -4106,14 +4188,21 @@ public function relationship(&$values) {
//Get the names of the target groups for the qill
$groupNames = CRM_Core_PseudoConstant::group();
- $qillNames = array();
+ $qillNames = [];
foreach ($targetGroup[2] as $groupId) {
if (array_key_exists($groupId, $groupNames)) {
$qillNames[] = $groupNames[$groupId];
}
}
if (!empty($relationType)) {
- $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
+ $relQill = '';
+ foreach ($relTypes as $rel) {
+ if (!empty($relQill)) {
+ $relQill .= ' OR ';
+ }
+ $relQill .= CRM_Utils_Array::value($rel, $allRelationshipType);
+ }
+ $this->_qill[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
}
else {
$this->_qill[$grouping][] = implode(", ", $qillNames);
@@ -4141,39 +4230,22 @@ public function relationship(&$values) {
}
$onlyDeleted = 0;
- if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params)) {
+ if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params)) {
$onlyDeleted = 1;
}
$where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
- //check for permissioned, non-permissioned and all permissioned relations
- if ($relPermission[2] == 1) {
- $where[$grouping][] = "(
-civicrm_relationship.is_permission_a_b = 1
-)";
- $this->_qill[$grouping][] = ts('Relationship - Permissioned');
- }
- elseif ($relPermission[2] == 2) {
- //non-allowed permission relationship.
- $where[$grouping][] = "(
-civicrm_relationship.is_permission_a_b = 0
-)";
- $this->_qill[$grouping][] = ts('Relationship - Non-permissioned');
- }
-
+ $this->addRelationshipPermissionClauses($grouping, $where);
$this->addRelationshipDateClauses($grouping, $where);
$this->addRelationshipActivePeriodClauses($grouping, $where);
- if (!empty($relationType) && !empty($rType) && isset($rType->id)) {
- $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id;
+ if (!empty($relTypes)) {
+ $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
}
$this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
$this->_useDistinct = TRUE;
$this->_relationshipValuesAdded = TRUE;
// it could be a or b, using an OR creates an unindexed join - better to create a temp table &
// join on that,
- // @todo creating a temp table could be expanded to group filter
- // as even creating a temp table of all relationships is much much more efficient than
- // an OR in the join
if ($relationshipTempTable) {
$whereClause = '';
if (!empty($where[$grouping])) {
@@ -4182,19 +4254,47 @@ public function relationship(&$values) {
}
$sql = "
CREATE TEMPORARY TABLE {$relationshipTempTable}
- (SELECT contact_id_b as contact_id, civicrm_relationship.id
+ (
+ `contact_id` int(10) unsigned NOT NULL DEFAULT '0',
+ `contact_id_alt` int(10) unsigned NOT NULL DEFAULT '0',
+ KEY `contact_id` (`contact_id`),
+ KEY `contact_id_alt` (`contact_id_alt`)
+ )
+ (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
FROM civicrm_relationship
INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
$whereClause )
UNION
- (SELECT contact_id_a as contact_id, civicrm_relationship.id
+ (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
FROM civicrm_relationship
INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
$whereClause )
";
CRM_Core_DAO::executeQuery($sql);
}
+ }
+
+ /**
+ * Add relationship permission criteria to where clause.
+ *
+ * @param string $grouping
+ * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
+ * Not the main query.
+ */
+ public function addRelationshipPermissionClauses($grouping, &$where) {
+ $relPermission = $this->getWhereValues('relation_permission', $grouping);
+ if ($relPermission) {
+ if (!is_array($relPermission[2])) {
+ // this form value was scalar in previous versions of Civi
+ $relPermission[2] = [$relPermission[2]];
+ }
+ $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
+ $allRelationshipPermissions = CRM_Contact_BAO_Relationship::buildOptions('is_permission_a_b');
+
+ $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
+ $this->_qill[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
+ }
}
/**
@@ -4205,11 +4305,11 @@ public function relationship(&$values) {
* not the main query.
*/
public function addRelationshipDateClauses($grouping, &$where) {
- $dateValues = array();
- $dateTypes = array(
+ $dateValues = [];
+ $dateTypes = [
'start_date',
'end_date',
- );
+ ];
foreach ($dateTypes as $dateField) {
$dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
@@ -4235,7 +4335,7 @@ public function addRelationshipDateClauses($grouping, &$where) {
* not the main query.
*/
public function addRelationshipActivePeriodClauses($grouping, &$where) {
- $dateValues = array();
+ $dateValues = [];
$dateField = 'active_period_date';
$dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
@@ -4295,7 +4395,7 @@ public static function getRelationshipActivePeriodClauses($from, $to, $forceTabl
*/
public static function &defaultReturnProperties($mode = 1) {
if (!isset(self::$_defaultReturnProperties)) {
- self::$_defaultReturnProperties = array();
+ self::$_defaultReturnProperties = [];
}
if (!isset(self::$_defaultReturnProperties[$mode])) {
@@ -4308,7 +4408,7 @@ public static function &defaultReturnProperties($mode = 1) {
}
if (empty(self::$_defaultReturnProperties[$mode])) {
- self::$_defaultReturnProperties[$mode] = array(
+ self::$_defaultReturnProperties[$mode] = [
'home_URL' => 1,
'image_URL' => 1,
'legal_identifier' => 1,
@@ -4362,7 +4462,7 @@ public static function &defaultReturnProperties($mode = 1) {
'contact_is_deleted' => 1,
'preferred_communication_method' => 1,
'preferred_language' => 1,
- );
+ ];
}
}
return self::$_defaultReturnProperties[$mode];
@@ -4498,12 +4598,11 @@ public static function apiQuery(
// @todo derive this from the component class rather than hard-code two options.
$entityIDField = ($mode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) ? 'contribution_id' : 'contact_id';
- $values = array();
+ $values = [];
while ($dao->fetch()) {
if ($count) {
$noRows = $dao->rowCount;
- $dao->free();
- return array($noRows, NULL);
+ return [$noRows, NULL];
}
$val = $query->store($dao);
$convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
@@ -4513,8 +4612,7 @@ public static function apiQuery(
}
$values[$dao->$entityIDField] = $val;
}
- $dao->free();
- return array($values, $options);
+ return [$values, $options];
}
/**
@@ -4585,22 +4683,22 @@ protected static function convertCustomRelativeFields(&$formValues, &$params, $v
if ($from) {
if ($to) {
- $relativeFunction = array('BETWEEN' => array($from, $to));
+ $relativeFunction = ['BETWEEN' => [$from, $to]];
}
else {
- $relativeFunction = array('>=' => $from);
+ $relativeFunction = ['>=' => $from];
}
}
else {
- $relativeFunction = array('<=' => $to);
+ $relativeFunction = ['<=' => $to];
}
- $params[] = array(
+ $params[] = [
$customFieldName,
'=',
$relativeFunction,
0,
0,
- );
+ ];
}
/**
@@ -4614,7 +4712,7 @@ public static function isCustomDateField($fieldName) {
if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName)) == FALSE) {
return FALSE;
}
- if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
+ if ('Date' == civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type'])) {
return TRUE;
}
return FALSE;
@@ -4674,27 +4772,21 @@ public static function filterCountryFromValuesIfStateExists(&$formValues) {
*
* @param array $selectClauses
* @param array $groupBy - Columns already included in GROUP By clause.
+ * @param string $aggregateFunction
*
* @return string
*/
- public static function appendAnyValueToSelect($selectClauses, $groupBy) {
- $mysqlVersion = CRM_Core_DAO::singleValueQuery('SELECT VERSION()');
- $sqlMode = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode'));
-
- // Disable only_full_group_by mode for lower sql versions.
- if (version_compare($mysqlVersion, '5.7', '<') || (!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
- $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
- unset($sqlMode[$key]);
- CRM_Core_DAO::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
- }
- else {
+ public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
+ if (!CRM_Utils_SQL::disableFullGroupByMode()) {
$groupBy = array_map('trim', (array) $groupBy);
- $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
+ $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
foreach ($selectClauses as $key => &$val) {
list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
// append ANY_VALUE() keyword
if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
- $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val);
+ $val = ($aggregateFunction == 'GROUP_CONCAT') ?
+ str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
+ str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
}
}
}
@@ -4702,6 +4794,28 @@ public static function appendAnyValueToSelect($selectClauses, $groupBy) {
return "SELECT " . implode(', ', $selectClauses) . " ";
}
+ /**
+ * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
+ * on full_group_by mode, then append the those missing columns to GROUP BY clause
+ * keyword to select fields not present in groupBy
+ *
+ * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
+ * @param array $orderBys - ORDER BY sub-clauses
+ *
+ */
+ public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
+ if (!CRM_Utils_SQL::disableFullGroupByMode()) {
+ foreach ($orderBys as $orderBy) {
+ // remove sort syntax from ORDER BY clauses if present
+ $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
+ // if ORDER BY column is not present in GROUP BY then append it to end
+ if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
+ $groupBy .= ", {$orderBy}";
+ }
+ }
+ }
+ }
+
/**
* Include Select columns in groupBy clause.
*
@@ -4716,8 +4830,8 @@ public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NU
$sqlMode = CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode');
//return if ONLY_FULL_GROUP_BY is not enabled.
- if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
- $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
+ if (CRM_Utils_SQL::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
+ $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
foreach ($selectClauses as $key => $val) {
$aliasArray = preg_split('/ as /i', $val);
// if more than 1 alias we need to split by ','.
@@ -4793,89 +4907,7 @@ public function searchQuery(
$additionalFromClause = NULL, $skipOrderAndLimit = FALSE
) {
- if ($includeContactIds) {
- $this->_includeContactIds = TRUE;
- $this->_whereClause = $this->whereClause();
- }
-
- $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
-
- // if we’re explicitly looking for a certain contact’s contribs, events, etc.
- // and that contact happens to be deleted, set $onlyDeleted to true
- foreach ($this->_params as $values) {
- $name = CRM_Utils_Array::value(0, $values);
- $op = CRM_Utils_Array::value(1, $values);
- $value = CRM_Utils_Array::value(2, $values);
- if ($name == 'contact_id' and $op == '=') {
- if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
- $onlyDeleted = TRUE;
- }
- break;
- }
- }
-
- // building the query string
- $groupBy = $groupByCol = NULL;
- if (!$count) {
- if (isset($this->_groupByComponentClause)) {
- $groupBy = $this->_groupByComponentClause;
- $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause));
- $groupByCol = explode(', ', $groupCols);
- }
- elseif ($this->_useGroupBy) {
- $groupByCol = 'contact_a.id';
- $groupBy = ' GROUP BY contact_a.id';
- }
- }
- if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
- $groupByCol = 'civicrm_activity.id';
- $groupBy = 'GROUP BY civicrm_activity.id ';
- }
-
- $order = $orderBy = $limit = '';
- if (!$count) {
- list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
-
- if ($rowCount > 0 && $offset >= 0) {
- $offset = CRM_Utils_Type::escape($offset, 'Int');
- $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
- $limit = " LIMIT $offset, $rowCount ";
- }
- }
-
- // CRM-15231
- $this->_sort = $sort;
-
- //CRM-15967
- $this->includePseudoFieldsJoin($sort);
-
- list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
-
- if (!empty($groupByCol)) {
- $groupBy = self::getGroupByFromSelectColumns($this->_select, $groupByCol);
- }
-
- if ($additionalWhereClause) {
- $where = $where . ' AND ' . $additionalWhereClause;
- }
-
- //additional from clause should be w/ proper joins.
- if ($additionalFromClause) {
- $from .= "\n" . $additionalFromClause;
- }
-
- // if we are doing a transform, do it here
- // use the $from, $where and $having to get the contact ID
- if ($this->_displayRelationshipType) {
- $this->filterRelatedContacts($from, $where, $having);
- }
-
- if ($skipOrderAndLimit) {
- $query = "$select $from $where $having $groupBy";
- }
- else {
- $query = "$select $from $where $having $groupBy $order $limit";
- }
+ $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
if ($returnQuery) {
return $query;
@@ -4885,12 +4917,15 @@ public function searchQuery(
}
$dao = CRM_Core_DAO::executeQuery($query);
+
+ // We can always call this - it will only re-enable if it was originally enabled.
+ CRM_Core_DAO::reenableFullGroupByMode();
+
if ($groupContacts) {
- $ids = array();
+ $ids = [];
while ($dao->fetch()) {
$ids[] = $dao->id;
}
- $dao->free();
return implode(',', $ids);
}
@@ -4898,28 +4933,64 @@ public function searchQuery(
}
/**
- * Fetch a list of contacts from the prev/next cache for displaying a search results page
+ * Create and query the db for the list of all first letters used by contacts
*
- * @param string $cacheKey
- * @param int $offset
- * @param int $rowCount
+ * @return CRM_Core_DAO
+ */
+ public function alphabetQuery() {
+ $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
+ {$this->_simpleFromClause}
+ {$sqlParts['where']}
+ {$sqlParts['having']}
+ GROUP BY sort_name
+ ORDER BY sort_name asc";
+ $dao = CRM_Core_DAO::executeQuery($query);
+ return $dao;
+ }
+
+ /**
+ * Fetch a list of contacts for displaying a search results page
+ *
+ * @param array $cids
+ * List of contact IDs
* @param bool $includeContactIds
* @return CRM_Core_DAO
*/
- public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
+ public function getCachedContacts($cids, $includeContactIds) {
+ CRM_Utils_Type::validateAll($cids, 'Positive');
$this->_includeContactIds = $includeContactIds;
- $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
+ $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params);
list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
- $from = " FROM civicrm_prevnext_cache pnc INNER JOIN civicrm_contact contact_a ON contact_a.id = pnc.entity_id1 AND pnc.cacheKey = '$cacheKey' " . substr($from, 31);
- $order = " ORDER BY pnc.id";
- $groupByCol = array('contact_a.id', 'pnc.id');
- $groupBy = self::getGroupByFromSelectColumns($this->_select, $groupByCol);
- $limit = " LIMIT $offset, $rowCount";
+ $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
+ $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
+ $order = 'ORDER BY _wgt';
+ $groupBy = $this->_useGroupBy ? ' GROUP BY contact_a.id' : '';
+ $limit = '';
$query = "$select $from $where $groupBy $order $limit";
return CRM_Core_DAO::executeQuery($query);
}
+ /**
+ * Construct a SQL CASE expression.
+ *
+ * @param string $idCol
+ * The name of a column with ID's (eg 'contact_a.id').
+ * @param array $cids
+ * Array(int $weight => int $id).
+ * @return string
+ * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
+ */
+ private function createSqlCase($idCol, $cids) {
+ $buf = "CASE\n";
+ foreach ($cids as $weight => $cid) {
+ $buf .= " WHEN $idCol = $cid THEN $weight \n";
+ }
+ $buf .= "END\n";
+ return $buf;
+ }
+
/**
* Populate $this->_permissionWhereClause with permission related clause and update other
* query related properties.
@@ -4985,159 +5056,49 @@ public function setSkipPermission($val) {
*
* @return array
*/
- public function &summaryContribution($context = NULL) {
+ public function summaryContribution($context = NULL) {
list($innerselect, $from, $where, $having) = $this->query(TRUE);
-
- // hack $select
- $select = "
-SELECT COUNT( conts.total_amount ) as total_count,
- SUM( conts.total_amount ) as total_amount,
- AVG( conts.total_amount ) as total_avg,
- conts.currency as currency";
if ($this->_permissionWhereClause) {
$where .= " AND " . $this->_permissionWhereClause;
}
if ($context == 'search') {
$where .= " AND contact_a.is_deleted = 0 ";
}
- CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
- if (!empty($financialTypes)) {
- $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
- $from .= " LEFT JOIN civicrm_line_item li
- ON civicrm_contribution.id = li.contribution_id AND
- li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
- }
- else {
- $where .= " AND civicrm_contribution.financial_type_id IN (0)";
- }
-
- // make sure contribution is completed - CRM-4989
- $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
-
- $summary = array();
- $summary['total'] = array();
- $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
- $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
- civicrm_contribution.currency $from $completedWhere";
- $query = "$select FROM (
- $innerQuery GROUP BY civicrm_contribution.id
- ) as conts
- GROUP BY currency";
-
- $dao = CRM_Core_DAO::executeQuery($query);
-
- $summary['total']['count'] = 0;
- $summary['total']['amount'] = $summary['total']['avg'] = array();
- while ($dao->fetch()) {
- $summary['total']['count'] += $dao->total_count;
- $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
- $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
- }
- $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
- $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
- $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
- ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
- MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
- FROM ($innerQuery
- $groupBy $orderBy) as conts
- GROUP BY currency";
-
- $summary['total']['mode'] = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL);
+ $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
- $medianSQL = "{$from} {$completedWhere}";
- $summary['total']['median'] = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, 'civicrm_contribution');
- $summary['total']['currencyCount'] = count($summary['total']['median']);
-
- if (!empty($summary['total']['amount'])) {
- $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
- $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
- $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
- $summary['total']['median'] = implode(', ', $summary['total']['median']);
- }
- else {
- $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
- }
+ $summary = ['total' => []];
+ $this->addBasicStatsToSummary($summary, $where, $from);
- // soft credit summary
if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
- $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
- $query = "
- $select FROM (
- SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
- GROUP BY civicrm_contribution_soft.id
- ) as conts
- GROUP BY currency";
- $dao = CRM_Core_DAO::executeQuery($query);
- $summary['soft_credit']['count'] = 0;
- $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
- while ($dao->fetch()) {
- $summary['soft_credit']['count'] += $dao->total_count;
- $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
- $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
- }
- if (!empty($summary['soft_credit']['amount'])) {
- $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
- $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
- }
- else {
- $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
- }
- }
-
- // hack $select
- //@todo - this could be one query using the IF in mysql - eg
- // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
- // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
- // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
- // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
- // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
- // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
- // FROM civicrm_contact contact_a
- // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
- // WHERE ( ... where clause....
- // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
- // ) as conts
-
- $select = "
-SELECT COUNT( conts.total_amount ) as cancel_count,
- SUM( conts.total_amount ) as cancel_amount,
- AVG( conts.total_amount ) as cancel_avg,
- conts.currency as currency";
-
- $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
- if ($context == 'search') {
- $where .= " AND contact_a.is_deleted = 0 ";
+ $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
}
- $query = "$select FROM (
- SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
- GROUP BY civicrm_contribution.id
- ) as conts
- GROUP BY currency";
+ $this->addBasicCancelStatsToSummary($summary, $where, $from);
- $dao = CRM_Core_DAO::executeQuery($query);
+ return $summary;
+ }
- if ($dao->N <= 1) {
- if ($dao->fetch()) {
- $summary['cancel']['count'] = $dao->cancel_count;
- $summary['cancel']['amount'] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
- $summary['cancel']['avg'] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
- }
+ /**
+ * Append financial ACL limits to the query from & where clauses, if applicable.
+ *
+ * @param string $where
+ * @param string $from
+ */
+ public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
+ if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
+ return;
+ }
+ CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
+ if (!empty($financialTypes)) {
+ $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
+ $from .= " LEFT JOIN civicrm_line_item li
+ ON civicrm_contribution.id = li.contribution_id AND
+ li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
}
else {
- $summary['cancel']['count'] = 0;
- $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
- while ($dao->fetch()) {
- $summary['cancel']['count'] += $dao->cancel_count;
- $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
- $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
- }
- $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
- $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
+ $where .= " AND civicrm_contribution.financial_type_id IN (0)";
}
-
- return $summary;
}
/**
@@ -5156,7 +5117,7 @@ public function qill() {
*/
public static function &defaultHierReturnProperties() {
if (!isset(self::$_defaultHierReturnProperties)) {
- self::$_defaultHierReturnProperties = array(
+ self::$_defaultHierReturnProperties = [
'home_URL' => 1,
'image_URL' => 1,
'legal_identifier' => 1,
@@ -5184,8 +5145,8 @@ public static function &defaultHierReturnProperties() {
'do_not_mail' => 1,
'do_not_sms' => 1,
'do_not_trade' => 1,
- 'location' => array(
- '1' => array(
+ 'location' => [
+ '1' => [
'location_type' => 1,
'street_address' => 1,
'city' => 1,
@@ -5205,8 +5166,8 @@ public static function &defaultHierReturnProperties() {
'email-1' => 1,
'email-2' => 1,
'email-3' => 1,
- ),
- '2' => array(
+ ],
+ '2' => [
'location_type' => 1,
'street_address' => 1,
'city' => 1,
@@ -5225,9 +5186,9 @@ public static function &defaultHierReturnProperties() {
'email-1' => 1,
'email-2' => 1,
'email-3' => 1,
- ),
- ),
- );
+ ],
+ ],
+ ];
}
return self::$_defaultHierReturnProperties;
}
@@ -5331,7 +5292,7 @@ public function dateQueryBuilder(
$date = $format = NULL;
if (strstr($op, 'IN')) {
- $format = array();
+ $format = [];
foreach ($value as &$date) {
$date = CRM_Utils_Date::processDate($date, NULL, FALSE, $dateFormat);
if (!$appendTimeStamp) {
@@ -5447,7 +5408,6 @@ public function numberRangeBuilder(
}
}
-
/**
* @param $values
* @param string $tableName
@@ -5465,7 +5425,8 @@ public function ageRangeQueryBuilder(
list($name, $op, $value, $grouping, $wildcard) = $values;
$asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
- $asofDate = NULL; // will be treated as current day
+ // will be treated as current day
+ $asofDate = NULL;
if ($asofDateValues) {
$asofDate = CRM_Utils_Date::processDate($asofDateValues[2]);
$asofDateFormat = CRM_Utils_Date::customFormat(substr($asofDate, 0, 8));
@@ -5581,22 +5542,25 @@ public static function buildClause($field, $op, $value = NULL, $dataType = NULL)
return $clause;
case 'IS EMPTY':
- $clause = " (NULLIF($field, '') IS NULL) ";
+ $clause = ($dataType == 'Date') ? " $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
return $clause;
case 'IS NOT EMPTY':
- $clause = " (NULLIF($field, '') IS NOT NULL) ";
+ $clause = ($dataType == 'Date') ? " $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
return $clause;
+ case 'RLIKE':
+ return " {$clause} BINARY '{$value}' ";
+
case 'IN':
case 'NOT IN':
// I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
if (!empty($value) && (!is_array($value) || !array_key_exists($op, $value))) {
- $value = array($op => (array) $value);
+ $value = [$op => (array) $value];
}
default:
- if (empty($dataType)) {
+ if (empty($dataType) || $dataType == 'Date') {
$dataType = 'String';
}
if (is_array($value)) {
@@ -5607,32 +5571,19 @@ public static function buildClause($field, $op, $value = NULL, $dataType = NULL)
return $queryString;
}
-
- // This is the here-be-dragons zone. We have no other hopes left for an array so lets assume it 'should' be array('IN' => array(2,5))
- // but we got only array(2,5) from the form.
- // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
- // people have to de-slopify it.
- if (!empty($value[0])) {
- if ($op != 'BETWEEN') {
- $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
- }
- if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
- return $queryString;
- }
- }
- else {
- $op = 'IN';
- $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
- if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
+ if (!empty($value[0]) && $op === 'BETWEEN') {
+ CRM_Core_Error::deprecatedFunctionWarning('Fix search input params');
+ if (($queryString = CRM_Core_DAO::createSqlFilter($field, [$op => $value], $dataType)) != FALSE) {
return $queryString;
}
}
+ throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
}
$value = CRM_Utils_Type::escape($value, $dataType);
// if we don't have a dataType we should assume
if ($dataType == 'String' || $dataType == 'Text') {
- $value = "'" . strtolower($value) . "'";
+ $value = "'" . $value . "'";
}
return "$clause $value";
}
@@ -5649,7 +5600,7 @@ public function openedSearchPanes($reset = FALSE) {
}
// pane name to table mapper
- $panesMapper = array(
+ $panesMapper = [
ts('Contributions') => 'civicrm_contribution',
ts('Memberships') => 'civicrm_membership',
ts('Events') => 'civicrm_participant',
@@ -5662,7 +5613,7 @@ public function openedSearchPanes($reset = FALSE) {
ts('Notes') => 'civicrm_note',
ts('Change Log') => 'civicrm_log',
ts('Mailings') => 'civicrm_mailing',
- );
+ ];
CRM_Contact_BAO_Query_Hook::singleton()->getPanesMapper($panesMapper);
foreach (array_keys($this->_whereTables) as $table) {
@@ -5678,7 +5629,7 @@ public function openedSearchPanes($reset = FALSE) {
* @param $operator
*/
public function setOperator($operator) {
- $validOperators = array('AND', 'OR');
+ $validOperators = ['AND', 'OR'];
if (!in_array($operator, $validOperators)) {
$operator = 'AND';
}
@@ -5698,15 +5649,28 @@ public function getOperator() {
* @param $having
*/
public function filterRelatedContacts(&$from, &$where, &$having) {
- static $_rTypeProcessed = NULL;
- static $_rTypeFrom = NULL;
- static $_rTypeWhere = NULL;
-
- if (!$_rTypeProcessed) {
- $_rTypeProcessed = TRUE;
-
+ if (!isset(Civi::$statics[__CLASS__]['related_contacts_filter'])) {
+ Civi::$statics[__CLASS__]['related_contacts_filter'] = [];
+ }
+ $_rTempCache =& Civi::$statics[__CLASS__]['related_contacts_filter'];
+ // since there only can be one instance of this filter in every query
+ // skip if filter has already applied
+ foreach ($_rTempCache as $acache) {
+ foreach ($acache['queries'] as $aqcache) {
+ if (strpos($from, $aqcache['from']) !== FALSE) {
+ $having = NULL;
+ return;
+ }
+ }
+ }
+ $arg_sig = sha1("$from $where $having");
+ if (isset($_rTempCache[$arg_sig])) {
+ $cache = $_rTempCache[$arg_sig];
+ }
+ else {
// create temp table with contact ids
$tableName = CRM_Core_DAO::createTempTableName('civicrm_transform', TRUE);
+
$sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
CRM_Core_DAO::executeQuery($sql);
@@ -5719,16 +5683,27 @@ public function filterRelatedContacts(&$from, &$where, &$having) {
";
CRM_Core_DAO::executeQuery($sql);
- $qillMessage = ts('Contacts with a Relationship Type of: ');
+ $cache = ['tableName' => $tableName, 'queries' => []];
+ $_rTempCache[$arg_sig] = $cache;
+ }
+ // upsert the query depending on relationship type
+ if (isset($cache['queries'][$this->_displayRelationshipType])) {
+ $qcache = $cache['queries'][$this->_displayRelationshipType];
+ }
+ else {
+ $tableName = $cache['tableName'];
+ $qcache = [
+ "from" => "",
+ "where" => "",
+ ];
$rTypes = CRM_Core_PseudoConstant::relationshipType();
-
if (is_numeric($this->_displayRelationshipType)) {
$relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b'];
- $_rTypeFrom = "
+ $qcache['from'] = "
INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
";
- $_rTypeWhere = "
+ $qcache['where'] = "
WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
AND displayRelType.is_active = 1
";
@@ -5737,36 +5712,40 @@ public function filterRelatedContacts(&$from, &$where, &$having) {
list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType);
if ($dirOne == 'a') {
$relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
- $_rTypeFrom .= "
+ $qcache['from'] .= "
INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
";
}
else {
$relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
- $_rTypeFrom .= "
+ $qcache['from'] .= "
INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
";
}
- $_rTypeWhere = "
+ $qcache['where'] = "
WHERE displayRelType.relationship_type_id = $relType
AND displayRelType.is_active = 1
";
}
- $this->_qill[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
+ $qcache['relTypeLabel'] = $relationshipTypeLabel;
+ $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType] = $qcache;
}
-
- if (!empty($this->_permissionWhereClause)) {
- $_rTypeWhere .= "AND $this->_permissionWhereClause";
+ $qillMessage = ts('Contacts with a Relationship Type of: ');
+ $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
+ if (!is_array($this->_qill[0]) || !in_array($iqill, $this->_qill[0])) {
+ $this->_qill[0][] = $iqill;
}
-
- if (strpos($from, $_rTypeFrom) === FALSE) {
+ if (strpos($from, $qcache['from']) === FALSE) {
// lets replace all the INNER JOIN's in the $from so we dont exclude other data
// this happens when we have an event_type in the quert (CRM-7969)
$from = str_replace("INNER JOIN", "LEFT JOIN", $from);
- $from .= $_rTypeFrom;
- $where = $_rTypeWhere;
+ $from .= $qcache['from'];
+ $where = $qcache['where'];
+ if (!empty($this->_permissionWhereClause)) {
+ $where .= "AND $this->_permissionWhereClause";
+ }
}
$having = NULL;
@@ -5780,8 +5759,7 @@ public function filterRelatedContacts(&$from, &$where, &$having) {
* @return bool
*/
public static function caseImportant($op) {
- return
- in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ? FALSE : TRUE;
+ return in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ? FALSE : TRUE;
}
/**
@@ -5832,7 +5810,7 @@ public function optionValueQuery(
$useIDsOnly = FALSE
) {
- $pseudoFields = array(
+ $pseudoFields = [
'email_greeting',
'postal_greeting',
'addressee',
@@ -5840,7 +5818,7 @@ public function optionValueQuery(
'prefix_id',
'suffix_id',
'communication_style_id',
- );
+ ];
if ($useIDsOnly) {
list($tableName, $fieldName) = explode('.', $field['where'], 2);
@@ -5848,15 +5826,23 @@ public function optionValueQuery(
$wc = "contact_a.$fieldName";
}
else {
- $wc = "$tableName.id";
+ // Special handling for on_hold, so that we actually use the 'where'
+ // property in order to limit the query by the on_hold status of the email,
+ // instead of using email.id which would be nonsensical.
+ if ($field['name'] == 'on_hold') {
+ $wc = "{$field['where']}";
+ }
+ else {
+ $wc = "$tableName.id";
+ }
}
}
else {
- // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
- $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
+ CRM_Core_Error::deprecatedFunctionWarning('pass $ids to this method');
+ $wc = "{$field['where']}";
}
if (in_array($name, $pseudoFields)) {
- if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
+ if (!in_array($name, ['gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'])) {
$wc = "contact_a.{$name}_id";
}
$dataType = 'Positive';
@@ -5867,7 +5853,7 @@ public function optionValueQuery(
}
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($daoName, $field['name'], $value, $op);
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
$this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType);
}
@@ -5887,7 +5873,7 @@ public function optionValueQuery(
public static function parseSearchBuilderString($string, $dataType = 'Integer') {
$string = trim($string);
if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') {
- Return FALSE;
+ return FALSE;
}
$string = substr($string, 1, -1);
@@ -5896,7 +5882,7 @@ public static function parseSearchBuilderString($string, $dataType = 'Integer')
return FALSE;
}
- $returnValues = array();
+ $returnValues = [];
foreach ($values as $v) {
if ($dataType == 'Integer' && !is_numeric($v)) {
return FALSE;
@@ -5927,7 +5913,7 @@ public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE
if (empty($this->_pseudoConstantsSelect)) {
return NULL;
}
- $values = array();
+ $values = [];
foreach ($this->_pseudoConstantsSelect as $key => $value) {
if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) {
continue;
@@ -5987,7 +5973,7 @@ public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE
$dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
}
// @todo handle this in the section above for pseudoconstants.
- elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
+ elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
// @todo define bao on this & merge into the above condition.
$viewValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $val);
@@ -6012,7 +5998,7 @@ public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE
$lastElement = array_pop($keyVal);
foreach ($keyVal as $v) {
if (!array_key_exists($v, $current)) {
- $current[$v] = array();
+ $current[$v] = [];
}
$current = &$current[$v];
}
@@ -6025,12 +6011,12 @@ public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE
}
}
if (!$usedForAPI) {
- foreach (array(
- 'gender_id' => 'gender',
- 'prefix_id' => 'individual_prefix',
- 'suffix_id' => 'individual_suffix',
- 'communication_style_id' => 'communication_style',
- ) as $realField => $labelField) {
+ foreach ([
+ 'gender_id' => 'gender',
+ 'prefix_id' => 'individual_prefix',
+ 'suffix_id' => 'individual_suffix',
+ 'communication_style_id' => 'communication_style',
+ ] as $realField => $labelField) {
// This is a temporary routine for handling these fields while
// we figure out how to handled them based on metadata in
/// export and search builder. CRM-19815, CRM-19830.
@@ -6053,7 +6039,7 @@ public function includePseudoFieldsJoin($sort) {
return NULL;
}
$sort = is_string($sort) ? $sort : $sort->orderBy();
- $present = array();
+ $present = [];
foreach ($this->_pseudoConstantsSelect as $name => $value) {
if (!empty($value['table'])) {
@@ -6090,7 +6076,7 @@ public function includePseudoFieldsJoin($sort) {
$this->_fromClause = $this->_fromClause . $presentClause;
$this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause;
- return array($presentClause, $presentSimpleFromClause);
+ return [$presentClause, $presentSimpleFromClause];
}
/**
@@ -6113,7 +6099,7 @@ public static function buildQillForFieldValue(
$fieldName,
$fieldValue,
$op,
- $pseudoExtraParam = array(),
+ $pseudoExtraParam = [],
$type = CRM_Utils_Type::T_STRING
) {
$qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
@@ -6127,7 +6113,7 @@ public static function buildQillForFieldValue(
// if Operator chosen is NULL/EMPTY then
if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
- return array(CRM_Utils_Array::value($op, $qillOperators, $op), '');
+ return [CRM_Utils_Array::value($op, $qillOperators, $op), ''];
}
if ($fieldName == 'activity_type_id') {
@@ -6160,7 +6146,7 @@ public static function buildQillForFieldValue(
}
if (is_array($fieldValue)) {
- $qillString = array();
+ $qillString = [];
if (!empty($pseudoOptions)) {
foreach ((array) $fieldValue as $val) {
$qillString[] = CRM_Utils_Array::value($val, $pseudoOptions, $val);
@@ -6190,7 +6176,7 @@ public static function buildQillForFieldValue(
$fieldValue = CRM_Utils_Date::customFormat($fieldValue);
}
- return array(CRM_Utils_Array::value($op, $qillOperators, $op), $fieldValue);
+ return [CRM_Utils_Array::value($op, $qillOperators, $op), $fieldValue];
}
/**
@@ -6232,9 +6218,9 @@ public static function getWildCardedValue($wildcard, $op, $value) {
* @param array $changeNames
* Array of fields whose name should be changed
*/
- public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
+ public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
// Array of special fields whose value are considered only for NULL or EMPTY operators
- $nullableFields = array('contribution_batch_id');
+ $nullableFields = ['contribution_batch_id'];
foreach ($specialFields as $element) {
$value = CRM_Utils_Array::value($element, $formValues);
@@ -6244,15 +6230,15 @@ public static function processSpecialFormValue(&$formValues, $specialFields, $ch
unset($formValues[$element]);
$element = $changeNames[$element];
}
- $formValues[$element] = array('IN' => $value);
+ $formValues[$element] = ['IN' => $value];
}
- elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
- $formValues[$element] = array($value => 1);
+ elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
+ $formValues[$element] = [$value => 1];
}
elseif (!in_array($element, $nullableFields)) {
// if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
$isWilcard = strstr($value, '%') ? FALSE : CRM_Core_Config::singleton()->includeWildCardInName;
- $formValues[$element] = array('LIKE' => self::getWildCardedValue($isWilcard, 'LIKE', $value));
+ $formValues[$element] = ['LIKE' => self::getWildCardedValue($isWilcard, 'LIKE', $value)];
}
}
}
@@ -6269,20 +6255,17 @@ public static function processSpecialFormValue(&$formValues, $specialFields, $ch
*
* @param string|CRM_Utils_Sort $sort
* The order by string.
- * @param bool $sortByChar
- * If true returns the distinct array of first characters for search results.
* @param null $sortOrder
* Who knows? Hu knows. He who knows Hu knows who.
- * @param string $additionalFromClause
- * Should be clause with proper joins, effective to reduce where clause load.
+ *
* @return array
* list(string $orderByClause, string $additionalFromClause).
*/
- protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
- $order = NULL;
- $orderByArray = array();
- $config = CRM_Core_Config::singleton();
- if ($config->includeOrderByClause ||
+ protected function prepareOrderBy($sort, $sortOrder) {
+ $orderByArray = [];
+ $orderBy = '';
+
+ if (CRM_Core_Config::singleton()->includeOrderByClause ||
isset($this->_distinctComponentClause)
) {
if ($sort) {
@@ -6303,91 +6286,89 @@ protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFro
$orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
}
- $order = " ORDER BY $orderBy";
-
if ($sortOrder) {
- $order .= " $sortOrder";
+ $orderBy .= " $sortOrder";
}
// always add contact_a.id to the ORDER clause
// so the order is deterministic
- if (strpos('contact_a.id', $order) === FALSE) {
- $order .= ", contact_a.id";
+ if (strpos('contact_a.id', $orderBy) === FALSE) {
+ $orderBy .= ", contact_a.id";
}
}
}
- elseif ($sortByChar) {
- $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
- }
else {
- $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
+ $orderBy = " contact_a.sort_name ASC, contact_a.id";
}
}
- if (!$order && empty($orderByArray)) {
- return array($order, $additionalFromClause);
+ if (!$orderBy) {
+ return NULL;
}
// Remove this here & add it at the end for simplicity.
- $order = trim(str_replace('ORDER BY', '', $order));
+ $order = trim($orderBy);
+ $orderByArray = explode(',', $order);
- // hack for order clause
- if (!empty($orderByArray)) {
- $order = implode(', ', $orderByArray);
- }
- else {
- $orderByArray = explode(',', $order);
- }
foreach ($orderByArray as $orderByClause) {
$orderByClauseParts = explode(' ', trim($orderByClause));
$field = $orderByClauseParts[0];
$direction = isset($orderByClauseParts[1]) ? $orderByClauseParts[1] : 'asc';
+ $fieldSpec = $this->getMetadataForRealField($field);
- switch ($field) {
- case 'city':
- case 'postal_code':
- $this->_tables["civicrm_address"] = $this->_whereTables["civicrm_address"] = 1;
- $order = str_replace($field, "civicrm_address.{$field}", $order);
- break;
-
- case 'country':
- case 'state_province':
- $this->_tables["civicrm_{$field}"] = $this->_whereTables["civicrm_{$field}"] = 1;
- if (is_array($this->_returnProperties) && empty($this->_returnProperties)) {
- $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
- }
- $order = str_replace($field, "civicrm_{$field}.name", $order);
- break;
-
- case 'email':
- $this->_tables["civicrm_email"] = $this->_whereTables["civicrm_email"] = 1;
- $order = str_replace($field, "civicrm_email.{$field}", $order);
- break;
-
- default:
- foreach ($this->_pseudoConstantsSelect as $key => $pseudoConstantMetadata) {
- // By replacing the join to the option value table with the mysql construct
- // ORDER BY field('contribution_status_id', 2,1,4)
- // we can remove a join. In the case of the option value join it is
- /// a join known to cause slow queries.
- // @todo cover other pseudoconstant types. Limited to option group ones in the
- // first instance for scope reasons. They require slightly different handling as the column (label)
- // is not declared for them.
- // @todo so far only integer fields are being handled. If we add string fields we need to look at
- // escaping.
- if (isset($pseudoConstantMetadata['pseudoconstant'])
- && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
- && $field === CRM_Utils_Array::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
- ) {
- $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
- 'orderColumn' => 'label',
- ));
- $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
- }
- //CRM-12565 add "`" around $field if it is a pseudo constant
- // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
- if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
- $order = str_replace($field, "`{$field}`", $order);
- }
- }
+ // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
+ // @todo much more cleanup on location handling in addHierarchical elements. Potentially
+ // add keys to $this->fields to represent the actual keys for locations.
+ if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
+ $fieldSpec = $this->getMetadataForField(substr($field, 2));
+ $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
+ }
+
+ if ($this->_returnProperties === []) {
+ if (!empty($fieldSpec['table_name']) && !isset($this->_tables[$fieldSpec['table_name']])) {
+ $this->_tables[$fieldSpec['table_name']] = 1;
+ $order = $fieldSpec['where'] . ' ' . $direction;
+ }
+
+ }
+ $cfID = CRM_Core_BAO_CustomField::getKeyID($field);
+ // add to cfIDs array if not present
+ if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs)) {
+ $this->_cfIDs[$cfID] = [];
+ $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
+ $this->_customQuery->query();
+ $this->_select = array_merge($this->_select, $this->_customQuery->_select);
+ $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
+ }
+
+ // By replacing the join to the option value table with the mysql construct
+ // ORDER BY field('contribution_status_id', 2,1,4)
+ // we can remove a join. In the case of the option value join it is
+ /// a join known to cause slow queries.
+ // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
+ // matching an id+name parrern in the
+ // first instance for scope reasons. They require slightly different handling as the column (label)
+ // is not declared for them.
+ // @todo so far only integer fields are being handled. If we add string fields we need to look at
+ // escaping.
+ $pseudoConstantMetadata = CRM_Utils_Array::value('pseudoconstant', $fieldSpec, FALSE);
+ if (!empty($pseudoConstantMetadata)
+ ) {
+ if (!empty($pseudoConstantMetadata['optionGroupName'])
+ || $this->isPseudoFieldAnFK($fieldSpec)
+ ) {
+ $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name'], NULL, [
+ 'orderColumn' => CRM_Utils_Array::value('labelColumn', $pseudoConstantMetadata, 'label'),
+ ]);
+ $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
+ // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
+ // this might give some early warning.
+ CRM_Utils_Type::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
+ $order = str_replace("$field", "field({$fieldSpec['name']},$fieldIDsInOrder)", $order);
+ }
+ //CRM-12565 add "`" around $field if it is a pseudo constant
+ // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
+ if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
+ $order = str_replace($field, "`{$field}`", $order);
+ }
}
}
@@ -6396,13 +6377,9 @@ protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFro
// The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
// clause. But this magic helper which forgivingly reescapes ORDER BY.
- // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
- if ($sortByChar) {
- return array(' ORDER BY ' . $order, $additionalFromClause);
- }
if ($order) {
$order = CRM_Utils_Type::escape($order, 'MysqlOrderBy');
- return array(' ORDER BY ' . $order, $additionalFromClause);
+ return ' ORDER BY ' . $order;
}
}
@@ -6440,11 +6417,11 @@ public function convertGroupIDStringToLabelString(&$dao, $val) {
public function setQillAndWhere($name, $op, $value, $grouping, $field) {
$this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value);
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [
1 => $field['title'],
2 => $qillop,
3 => $qillVal,
- ));
+ ]);
}
/**
@@ -6461,22 +6438,565 @@ public function setQillAndWhere($name, $op, $value, $grouping, $field) {
* @return bool
*/
private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
- if (!isset($field['pseudoconstant']['optionGroupName'])) {
+ $realField = $this->getMetadataForRealField($fieldName);
+ if (!isset($realField['pseudoconstant'])) {
+ return FALSE;
+ }
+ $pseudoConstant = $realField['pseudoconstant'];
+ if (empty($pseudoConstant['optionGroupName']) &&
+ CRM_Utils_Array::value('labelColumn', $pseudoConstant) !== 'name') {
+ // We are increasing our pseudoconstant handling - but still very cautiously,
+ // hence the check for labelColumn === name
return FALSE;
}
- if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) {
+ if (!empty($pseudoConstant['optionGroupName']) && CRM_Utils_Array::value($pseudoConstant['optionGroupName'], $this->_returnProperties)) {
return TRUE;
}
if (CRM_Utils_Array::value($fieldName, $this->_returnProperties)) {
return TRUE;
}
// Is this still required - the above goes off the unique name. Test with things like
- // communication_prefferences & prefix_id.
+ // communication_preferences & prefix_id.
if (CRM_Utils_Array::value($field['name'], $this->_returnProperties)) {
return TRUE;
}
return FALSE;
}
+ /**
+ * Get Select Clause.
+ *
+ * @return string
+ */
+ public function getSelect() {
+ $select = "SELECT ";
+ if (isset($this->_distinctComponentClause)) {
+ $select .= "{$this->_distinctComponentClause}, ";
+ }
+ $select .= implode(', ', $this->_select);
+ return $select;
+ }
+
+ /**
+ * Add basic statistics to the summary.
+ *
+ * @param array $summary
+ * @param string $where
+ * @param string $from
+ *
+ * @return array
+ */
+ protected function addBasicStatsToSummary(&$summary, $where, $from) {
+ $summary['total']['count'] = 0;
+ $summary['total']['amount'] = $summary['total']['avg'] = [];
+
+ $query = "
+ SELECT COUNT( conts.total_amount ) as total_count,
+ SUM( conts.total_amount ) as total_amount,
+ AVG( conts.total_amount ) as total_avg,
+ conts.currency as currency
+ FROM (
+ SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
+ civicrm_contribution.currency
+ $from
+ $where AND civicrm_contribution.contribution_status_id = 1
+ GROUP BY civicrm_contribution.id
+ ) as conts
+ GROUP BY currency";
+
+ $dao = CRM_Core_DAO::executeQuery($query);
+
+ while ($dao->fetch()) {
+ $summary['total']['count'] += $dao->total_count;
+ $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
+ $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
+ }
+
+ if (!empty($summary['total']['amount'])) {
+ $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
+ $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
+ }
+ else {
+ $summary['total']['amount'] = $summary['total']['avg'] = 0;
+ }
+ return $summary;
+ }
+
+ /**
+ * Add basic soft credit statistics to summary array.
+ *
+ * @param array $summary
+ * @param string $where
+ * @param string $from
+ */
+ protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
+ $query = "
+ SELECT COUNT( conts.total_amount ) as total_count,
+ SUM( conts.total_amount ) as total_amount,
+ AVG( conts.total_amount ) as total_avg,
+ conts.currency as currency
+ FROM (
+ SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
+ $from
+ $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
+ GROUP BY civicrm_contribution_soft.id
+ ) as conts
+ GROUP BY currency";
+
+ $dao = CRM_Core_DAO::executeQuery($query);
+ $summary['soft_credit']['count'] = 0;
+ $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
+ while ($dao->fetch()) {
+ $summary['soft_credit']['count'] += $dao->total_count;
+ $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
+ $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
+ }
+ if (!empty($summary['soft_credit']['amount'])) {
+ $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
+ $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
+ }
+ else {
+ $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
+ }
+ }
+
+ /**
+ * Add basic stats about cancelled contributions to the summary.
+ *
+ * @param array $summary
+ * @param string $where
+ * @param string $from
+ */
+ protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
+ $query = "
+ SELECT COUNT( conts.total_amount ) as cancel_count,
+ SUM( conts.total_amount ) as cancel_amount,
+ AVG( conts.total_amount ) as cancel_avg,
+ conts.currency as currency
+ FROM (
+ SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
+ $from
+ $where AND civicrm_contribution.cancel_date IS NOT NULL
+ GROUP BY civicrm_contribution.id
+ ) as conts
+ GROUP BY currency";
+
+ $dao = CRM_Core_DAO::executeQuery($query);
+
+ if ($dao->N <= 1) {
+ if ($dao->fetch()) {
+ $summary['cancel']['count'] = $dao->cancel_count;
+ $summary['cancel']['amount'] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
+ $summary['cancel']['avg'] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
+ }
+ }
+ else {
+ $summary['cancel']['count'] = 0;
+ $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
+ while ($dao->fetch()) {
+ $summary['cancel']['count'] += $dao->cancel_count;
+ $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
+ $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
+ }
+ $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
+ $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
+ }
+ }
+
+ /**
+ * Create the sql query for an contact search.
+ *
+ * @param int $offset
+ * The offset for the query.
+ * @param int $rowCount
+ * The number of rows to return.
+ * @param string|CRM_Utils_Sort $sort
+ * The order by string.
+ * @param bool $count
+ * Is this a count only query ?.
+ * @param bool $includeContactIds
+ * Should we include contact ids?.
+ * @param bool $sortByChar
+ * If true returns the distinct array of first characters for search results.
+ * @param bool $groupContacts
+ * If true, return only the contact ids.
+ * @param string $additionalWhereClause
+ * If the caller wants to further restrict the search (used for components).
+ * @param null $sortOrder
+ * @param string $additionalFromClause
+ * Should be clause with proper joins, effective to reduce where clause load.
+ *
+ * @param bool $skipOrderAndLimit
+ * @return string
+ */
+ public function getSearchSQL(
+ $offset = 0, $rowCount = 0, $sort = NULL,
+ $count = FALSE, $includeContactIds = FALSE,
+ $sortByChar = FALSE, $groupContacts = FALSE,
+ $additionalWhereClause = NULL, $sortOrder = NULL,
+ $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
+
+ $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
+
+ if ($sortByChar) {
+ CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
+ $sqlParts['order_by'] = 'ORDER BY sort_name asc';
+ }
+
+ if ($skipOrderAndLimit) {
+ CRM_Core_Error::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
+ $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
+ }
+ else {
+ $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
+ }
+ return $query;
+ }
+
+ /**
+ * Get the component parts of the search query as an array.
+ *
+ * @param int $offset
+ * The offset for the query.
+ * @param int $rowCount
+ * The number of rows to return.
+ * @param string|CRM_Utils_Sort $sort
+ * The order by string.
+ * @param bool $count
+ * Is this a count only query ?.
+ * @param bool $includeContactIds
+ * Should we include contact ids?.
+ * @param bool $sortByChar
+ * If true returns the distinct array of first characters for search results.
+ * @param bool $groupContacts
+ * If true, return only the contact ids.
+ * @param string $additionalWhereClause
+ * If the caller wants to further restrict the search (used for components).
+ * @param null $sortOrder
+ * @param string $additionalFromClause
+ * Should be clause with proper joins, effective to reduce where clause load.
+ *
+ * @return array
+ */
+ public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
+ $count = FALSE, $includeContactIds = FALSE,
+ $sortByChar = FALSE, $groupContacts = FALSE,
+ $additionalWhereClause = NULL, $sortOrder = NULL,
+ $additionalFromClause = NULL) {
+ if ($includeContactIds) {
+ $this->_includeContactIds = TRUE;
+ $this->_whereClause = $this->whereClause();
+ }
+ $onlyDeleted = in_array([
+ 'deleted_contacts',
+ '=',
+ '1',
+ '0',
+ '0',
+ ], $this->_params);
+
+ // if we’re explicitly looking for a certain contact’s contribs, events, etc.
+ // and that contact happens to be deleted, set $onlyDeleted to true
+ foreach ($this->_params as $values) {
+ $name = CRM_Utils_Array::value(0, $values);
+ $op = CRM_Utils_Array::value(1, $values);
+ $value = CRM_Utils_Array::value(2, $values);
+ if ($name == 'contact_id' and $op == '=') {
+ if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
+ $onlyDeleted = TRUE;
+ }
+ break;
+ }
+ }
+
+ // building the query string
+ $groupBy = $groupByCols = NULL;
+ if (!$count) {
+ if (isset($this->_groupByComponentClause)) {
+ $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause));
+ $groupByCols = explode(', ', $groupByCols);
+ }
+ elseif ($this->_useGroupBy) {
+ $groupByCols = ['contact_a.id'];
+ }
+ }
+ if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
+ $groupByCols = ['civicrm_activity.id'];
+ }
+ if (!empty($groupByCols)) {
+ $groupBy = " GROUP BY " . implode(', ', $groupByCols);
+ }
+
+ $order = $orderBy = '';
+ if (!$count) {
+ if (!$sortByChar) {
+ $order = $this->prepareOrderBy($sort, $sortOrder);
+ }
+ }
+ // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
+ // 1. When GROUP BY columns are present then disable FGB otherwise it demands to add ORDER BY columns in GROUP BY and eventually in SELECT
+ // clause. This will impact the search query output.
+ $disableFullGroupByMode = (!empty($groupBy) || $groupContacts);
+
+ if ($disableFullGroupByMode) {
+ CRM_Core_DAO::disableFullGroupByMode();
+ }
+
+ // CRM-15231
+ $this->_sort = $sort;
+
+ //CRM-15967
+ $this->includePseudoFieldsJoin($sort);
+
+ list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
+
+ if ($additionalWhereClause) {
+ $where = $where . ' AND ' . $additionalWhereClause;
+ }
+
+ //additional from clause should be w/ proper joins.
+ if ($additionalFromClause) {
+ $from .= "\n" . $additionalFromClause;
+ }
+
+ // if we are doing a transform, do it here
+ // use the $from, $where and $having to get the contact ID
+ if ($this->_displayRelationshipType) {
+ $this->filterRelatedContacts($from, $where, $having);
+ }
+ $limit = (!$count && $rowCount) ? " LIMIT " . CRM_Utils_Type::escape($offset, 'Int') . ", " . CRM_Utils_Type::escape($rowCount, 'Int') : '';
+
+ return [
+ 'select' => $select,
+ 'from' => $from,
+ 'where' => $where,
+ 'order_by' => $order,
+ 'group_by' => $groupBy,
+ 'having' => $having,
+ 'limit' => $limit,
+ ];
+ }
+
+ /**
+ * Get the metadata for a given field.
+ *
+ * @param string $fieldName
+ *
+ * @return array
+ */
+ protected function getMetadataForField($fieldName) {
+ if ($fieldName === 'contact_a.id') {
+ // This seems to be the only anomaly.
+ $fieldName = 'id';
+ }
+ $pseudoField = isset($this->_pseudoConstantsSelect[$fieldName]) ? $this->_pseudoConstantsSelect[$fieldName] : [];
+ $field = isset($this->_fields[$fieldName]) ? $this->_fields[$fieldName] : $pseudoField;
+ $field = array_merge($field, $pseudoField);
+ if (!empty($field) && empty($field['name'])) {
+ // standardising field formatting here - over time we can phase out variants.
+ // all paths using this currently unit tested
+ $field['name'] = CRM_Utils_Array::value('field_name', $field, CRM_Utils_Array::value('idCol', $field, $fieldName));
+ }
+ return $field;
+ }
+
+ /**
+ * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
+ *
+ * @param string $fieldName
+ *
+ * @return array
+ */
+ protected function getMetadataForRealField($fieldName) {
+ $field = $this->getMetadataForField($fieldName);
+ if (!empty($field['is_pseudofield_for'])) {
+ $field = $this->getMetadataForField($field['is_pseudofield_for']);
+ $field['pseudofield_name'] = $fieldName;
+ }
+ elseif (!empty($field['pseudoconstant'])) {
+ if (!empty($field['pseudoconstant']['optionGroupName'])) {
+ $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
+ if (empty($field['table_name'])) {
+ if (!empty($field['where'])) {
+ $field['table_name'] = explode('.', $field['where'])[0];
+ }
+ else {
+ $field['table_name'] = 'civicrm_contact';
+ }
+ }
+ }
+ }
+ return $field;
+ }
+
+ /**
+ * If we have a field that is better rendered via the pseudoconstant handled them here.
+ *
+ * Rather than joining in the additional table we render the option value on output.
+ *
+ * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
+ * carefully with test coverage but aim to extend.
+ *
+ * @param string $name
+ */
+ protected function addPseudoconstantFieldToSelect($name) {
+ $field = $this->getMetadataForRealField($name);
+ $realFieldName = $field['name'];
+ $pseudoFieldName = CRM_Utils_Array::value('pseudofield_name', $field);
+ if ($pseudoFieldName) {
+ // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
+ $this->_pseudoConstantsSelect[$pseudoFieldName] = [
+ 'pseudoField' => $pseudoFieldName,
+ 'idCol' => $realFieldName,
+ 'field_name' => $field['name'],
+ 'bao' => $field['bao'],
+ 'pseudoconstant' => $field['pseudoconstant'],
+ ];
+ }
+
+ $this->_tables[$field['table_name']] = 1;
+ $this->_element[$realFieldName] = 1;
+ $this->_select[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
+ }
+
+ /**
+ * Is this pseudofield a foreign key constraint.
+ *
+ * We are trying to cautiously expand our pseudoconstant handling. This check allows us
+ * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
+ * array which is done for contributions which are mostly handled as pseudoconstants.
+ *
+ * @param $fieldSpec
+ *
+ * @return bool
+ */
+ protected function isPseudoFieldAnFK($fieldSpec) {
+ if (empty($fieldSpec['FKClassName'])
+ || CRM_Utils_Array::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
+ || CRM_Utils_Array::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
+ return FALSE;
+ }
+ return TRUE;
+ }
+
+ /**
+ * Is the field a relative date field.
+ *
+ * @param string $fieldName
+ *
+ * @return bool
+ */
+ protected function isARelativeDateField($fieldName) {
+ if (substr($fieldName, -9, 9) !== '_relative') {
+ return FALSE;
+ }
+ $realField = substr($fieldName, 0, strlen($fieldName) - 9);
+ return isset($this->_fields[$realField]);
+ }
+
+ /**
+ * @param $values
+ */
+ protected function buildRelativeDateQuery(&$values) {
+ $value = CRM_Utils_Array::value(2, $values);
+ if (empty($value)) {
+ return;
+ }
+ $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
+ $fieldSpec = $this->_fields[$fieldName];
+ $tableName = $fieldSpec['table_name'];
+ $filters = CRM_Core_OptionGroup::values('relative_date_filters');
+ $grouping = CRM_Utils_Array::value(3, $values);
+ $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
+
+ $dates = CRM_Utils_Date::getFromTo($value, NULL, NULL);
+ if (empty($dates[0])) {
+ // ie. no start date we only have end date
+ $this->_where[$grouping][] = $fieldSpec['where'] . " <= '{$dates[1]}'";
+
+ $this->_qill[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("to %1", [
+ CRM_Utils_Date::customFormat($dates[1]),
+ ]) . ')';
+ }
+ elseif (empty($dates[1])) {
+ // ie. no end date we only have start date
+ $this->_where[$grouping][] = $fieldSpec['where'] . " >= '{$dates[1]}'";
+
+ $this->_qill[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("from %1", [
+ CRM_Utils_Date::customFormat($dates[0]),
+ ]) . ')';
+ }
+ else {
+ // we have start and end dates.
+ $this->_where[$grouping][] = $fieldSpec['where'] . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
+
+ $this->_qill[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("between %1 and %2", [
+ CRM_Utils_Date::customFormat($dates[0]),
+ CRM_Utils_Date::customFormat($dates[1]),
+ ]) . ')';
+ }
+ }
+
+ /**
+ * Add the address table into the query.
+ *
+ * @param string $tableKey
+ * @param string $joinCondition
+ *
+ * @return array
+ * - alias name
+ * - address join.
+ */
+ protected function addAddressTable($tableKey, $joinCondition) {
+ $tName = "$tableKey-address";
+ $aName = "`$tableKey-address`";
+ $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
+ $this->_element["{$tName}_id"] = 1;
+ $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
+ $this->_tables[$tName] = $addressJoin;
+
+ return [
+ $aName,
+ $addressJoin,
+ ];
+ }
+
+ /**
+ * Get the clause for group status.
+ *
+ * @param int $grouping
+ *
+ * @return string
+ */
+ protected function getGroupStatusClause($grouping) {
+ $statuses = $this->getSelectedGroupStatuses($grouping);
+ return "status IN (" . implode(', ', $statuses) . ")";
+ }
+
+ /**
+ * Get an array of the statuses that have been selected.
+ *
+ * @param string $grouping
+ *
+ * @return array
+ */
+ protected function getSelectedGroupStatuses($grouping) {
+ $statuses = [];
+ $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
+ if ($gcsValues &&
+ is_array($gcsValues[2])
+ ) {
+ foreach ($gcsValues[2] as $k => $v) {
+ if ($v) {
+ $statuses[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
+ }
+ }
+ }
+ else {
+ $statuses[] = "'Added'";
+ }
+ return $statuses;
+ }
+
}
diff --git a/CRM/Contact/BAO/Query/Hook.php b/CRM/Contact/BAO/Query/Hook.php
index 1b337fd3a07c..4b020772be1e 100644
--- a/CRM/Contact/BAO/Query/Hook.php
+++ b/CRM/Contact/BAO/Query/Hook.php
@@ -1,9 +1,9 @@
_queryObjects === NULL) {
- $this->_queryObjects = array();
+ $this->_queryObjects = [];
CRM_Utils_Hook::queryObjects($this->_queryObjects, 'Contact');
}
return $this->_queryObjects;
@@ -72,7 +72,7 @@ public function getSearchQueryObjects() {
* @return array
*/
public function &getFields() {
- $extFields = array();
+ $extFields = [];
foreach (self::getSearchQueryObjects() as $obj) {
$flds = $obj->getFields();
$extFields = array_merge($extFields, $flds);
diff --git a/CRM/Contact/BAO/Query/Interface.php b/CRM/Contact/BAO/Query/Interface.php
index 0987aa61b8f3..17e3202d7a98 100644
--- a/CRM/Contact/BAO/Query/Interface.php
+++ b/CRM/Contact/BAO/Query/Interface.php
@@ -1,9 +1,9 @@
copyValues($params);
@@ -308,7 +316,7 @@ public static function add(&$params, $ids = array(), $contactId = NULL) {
$relationship->contact_id_b = $params['contact_id_b'];
$relationship->contact_id_a = $params['contact_id_a'];
$relationship->relationship_type_id = $type;
- $relationship->id = $relationshipId;
+ $relationship->id = $params['id'];
$dateFields = array('end_date', 'start_date');
@@ -324,7 +332,7 @@ public static function add(&$params, $ids = array(), $contactId = NULL) {
$relationship->$defaultField = $params[$defaultField];
}
}
- elseif (!$relationshipId) {
+ elseif (empty($params['id'])) {
$relationship->$defaultField = $defaultValue;
}
}
@@ -336,8 +344,6 @@ public static function add(&$params, $ids = array(), $contactId = NULL) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_relationship', $relationship->id);
}
- $relationship->free();
-
CRM_Utils_Hook::post($hook, 'Relationship', $relationship->id, $relationship);
return $relationship;
@@ -467,9 +473,9 @@ public static function setContactABFromIDs($params, $ids = array(), $contactID =
*/
public static function getdefaults() {
return array(
- 'is_active' => 0,
- 'is_permission_a_b' => 0,
- 'is_permission_b_a' => 0,
+ 'is_active' => 1,
+ 'is_permission_a_b' => self::NONE,
+ 'is_permission_b_a' => self::NONE,
'description' => '',
'start_date' => 'NULL',
'case_id' => NULL,
@@ -477,7 +483,6 @@ public static function getdefaults() {
);
}
-
/**
* Check if there is data to create the object.
*
@@ -539,7 +544,7 @@ public static function getContactRelationshipType(
$relationship->id = $relationshipId;
if ($relationship->find(TRUE)) {
$contact = new CRM_Contact_DAO_Contact();
- $contact->id = ($relationship->contact_id_a === $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
+ $contact->id = ($relationship->contact_id_a == $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
if ($contact->find(TRUE)) {
$otherContactType = $contact->contact_type;
@@ -654,7 +659,7 @@ public static function clearCurrentEmployer($id, $action) {
$relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name'));
if (
(isset($relTypes['Employee of']) && $relationship->relationship_type_id == $relTypes['Employee of']['id']) ||
- (isset ($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id'])
+ (isset($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id'])
) {
$sharedContact = new CRM_Contact_DAO_Contact();
$sharedContact->id = $relationship->contact_id_a;
@@ -952,11 +957,9 @@ public static function checkDuplicateRelationship(&$params, $id, $contactId = 0,
// Check whether the custom field values are identical.
$result = self::checkDuplicateCustomFields($params, $relationship->id);
if ($result) {
- $relationship->free();
return TRUE;
}
}
- $relationship->free();
return FALSE;
}
@@ -1426,6 +1429,7 @@ public static function getRelationship(
if ($values[$rid]['rtype'] == 'b_a') {
$replace['clientid'] = $values[$rid]['cid'];
}
+ $values[$rid]['case'] = '';
}
}
@@ -1442,7 +1446,6 @@ public static function getRelationship(
}
}
- $relationship->free();
return $values;
}
}
@@ -1456,12 +1459,12 @@ public static function getRelationship(
* @return array
* array reference of all relationship types with context to current contact type .
*/
- static public function getRelationType($targetContactType) {
+ public static function getRelationType($targetContactType) {
$relationshipType = array();
$allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
foreach ($allRelationshipType as $key => $type) {
- if ($type['contact_type_b'] == $targetContactType) {
+ if ($type['contact_type_b'] == $targetContactType || empty($type['contact_type_b'])) {
$relationshipType[$key . '_a_b'] = $type['label_a_b'];
}
}
@@ -1713,10 +1716,10 @@ public static function relatedMemberships($contactId, &$params, $ids, $action =
$membershipValues['skipStatusCal'] = TRUE;
}
foreach (array(
- 'join_date',
- 'start_date',
- 'end_date',
- ) as $dateField) {
+ 'join_date',
+ 'start_date',
+ 'end_date',
+ ) as $dateField) {
if (!empty($membershipValues[$dateField])) {
$membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
}
@@ -1734,6 +1737,10 @@ public static function relatedMemberships($contactId, &$params, $ids, $action =
//contact before creating new membership record.
CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
}
+ //skip status calculation for pay later memberships.
+ if (!empty($membershipValues['status_id']) && $membershipValues['status_id'] == $pendingStatusId) {
+ $membershipValues['skipStatusCal'] = TRUE;
+ }
// check whether we have some related memberships still available
$query = "
@@ -2025,7 +2032,6 @@ public static function membershipTypeToRelationshipTypes(&$params, $direction =
}
}
-
/**
* Wrapper for contact relationship selector.
*
@@ -2081,6 +2087,8 @@ public static function getContactRelationshipSelector(&$params) {
unset($relationships['total_relationships']);
if (!empty($relationships)) {
+ $displayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
+
// format params
foreach ($relationships as $relationshipId => $values) {
$relationship = array();
@@ -2106,29 +2114,49 @@ public static function getContactRelationshipSelector(&$params) {
'civicrm/contact/view',
"reset=1&cid={$values['cid']}");
- $relationship['relation'] = CRM_Utils_System::href(
+ $relationship['relation'] = CRM_Utils_Array::value('case', $values, '') . CRM_Utils_System::href(
$values['relation'],
'civicrm/contact/view/rel',
"action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
- if ($params['context'] == 'current') {
- if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
- ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
- ) {
- $relationship['sort_name'] .= ' *';
- }
-
- if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
- ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
- ) {
- $relationship['relation'] .= ' *';
- }
- }
-
if (!empty($values['description'])) {
$relationship['relation'] .= "
{$values['description']}
";
}
+ if ($params['context'] == 'current') {
+ $smarty = CRM_Core_Smarty::singleton();
+
+ $contactCombos = [
+ [
+ 'permContact' => $params['contact_id'],
+ 'permDisplayName' => $displayName,
+ 'otherContact' => $values['cid'],
+ 'otherDisplayName' => $values['display_name'],
+ 'columnKey' => 'sort_name',
+ ],
+ [
+ 'permContact' => $values['cid'],
+ 'permDisplayName' => $values['display_name'],
+ 'otherContact' => $params['contact_id'],
+ 'otherDisplayName' => $displayName,
+ 'columnKey' => 'relation',
+ ],
+ ];
+
+ foreach ($contactCombos as $combo) {
+ foreach ([CRM_Contact_BAO_Relationship::EDIT, CRM_Contact_BAO_Relationship::VIEW] as $permType) {
+ $smarty->assign('permType', $permType);
+ if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
+ || ($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
+ ) {
+ $smarty->assign('permDisplayName', $combo['permDisplayName']);
+ $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
+ $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
+ }
+ }
+ }
+ }
+
$relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
$relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
$relationship['city'] = $values['city'];
@@ -2149,4 +2177,107 @@ public static function getContactRelationshipSelector(&$params) {
return $relationshipsDT;
}
+ /**
+ * @inheritdoc
+ */
+ public static function buildOptions($fieldName, $context = NULL, $props = array()) {
+ if ($fieldName === 'relationship_type_id') {
+ return self::buildRelationshipTypeOptions($props);
+ }
+
+ return parent::buildOptions($fieldName, $context, $props);
+ }
+
+ /**
+ * Builds a list of options available for relationship types
+ *
+ * @param array $params
+ * - contact_type: Limits by contact type on the "A" side
+ * - relationship_id: Used to find the value for contact type for "B" side.
+ * If contact_a matches provided contact_id then type of contact_b will
+ * be used. Otherwise uses type of contact_a. Must be used with contact_id
+ * - contact_id: Limits by contact types of this contact on the "A" side
+ * - is_form: Returns array with keys indexed for use in a quickform
+ * - relationship_direction: For relationship types with duplicate names
+ * on both sides, defines which option should be returned, a_b or b_a
+ *
+ * @return array
+ */
+ public static function buildRelationshipTypeOptions($params = array()) {
+ $contactId = CRM_Utils_Array::value('contact_id', $params);
+ $direction = CRM_Utils_Array::value('relationship_direction', $params, 'a_b');
+ $relationshipId = CRM_Utils_Array::value('relationship_id', $params);
+ $contactType = CRM_Utils_Array::value('contact_type', $params);
+ $isForm = CRM_Utils_Array::value('is_form', $params);
+ $showAll = FALSE;
+
+ // getContactRelationshipType will return an empty set if these are not set
+ if (!$contactId && !$relationshipId && !$contactType) {
+ $showAll = TRUE;
+ }
+
+ $labels = self::getContactRelationshipType(
+ $contactId,
+ $direction,
+ $relationshipId,
+ $contactType,
+ $showAll,
+ 'label'
+ );
+
+ if ($isForm) {
+ return $labels;
+ }
+
+ $names = self::getContactRelationshipType(
+ $contactId,
+ $direction,
+ $relationshipId,
+ $contactType,
+ $showAll,
+ 'name'
+ );
+
+ // ensure $names contains only entries in $labels
+ $names = array_intersect_key($names, $labels);
+
+ $nameToLabels = array_combine($names, $labels);
+
+ return $nameToLabels;
+ }
+
+ /**
+ * Process the params from api, form and check if current
+ * employer should be set or unset.
+ *
+ * @param array $params
+ * @param int $relationshipId
+ * @param int|NULL $updatedRelTypeID
+ *
+ * @return bool
+ * TRUE if current employer needs to be cleared.
+ */
+ public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
+ $existingTypeID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
+ $existingTypeName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a');
+ $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID;
+
+ if ($existingTypeName !== 'Employer of') {
+ return FALSE;
+ }
+ //Clear employer if relationship is expired.
+ if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
+ return TRUE;
+ }
+ //current employer checkbox is disabled on the form.
+ //inactive or relationship type(employer of) is updated.
+ if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
+ || ((isset($params['is_active']) && empty($params['is_active'])))
+ || $existingTypeID != $updatedRelTypeID) {
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
}
diff --git a/CRM/Contact/BAO/RelationshipType.php b/CRM/Contact/BAO/RelationshipType.php
index 656f7bae6ef5..bc11bf2f0248 100644
--- a/CRM/Contact/BAO/RelationshipType.php
+++ b/CRM/Contact/BAO/RelationshipType.php
@@ -1,9 +1,9 @@
copyValues($params);
if ($relationshipType->find(TRUE)) {
CRM_Core_DAO::storeValues($relationshipType, $defaults);
- $relationshipType->free();
return $relationshipType;
}
return NULL;
@@ -68,8 +67,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) {
return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_RelationshipType', $id, 'is_active', $is_active);
@@ -79,25 +78,20 @@ public static function setIsActive($id, $is_active) {
* Add the relationship type in the db.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
- * @param array $ids
- * The array that holds all the db ids.
*
* @return CRM_Contact_DAO_RelationshipType
*/
- public static function add(&$params, &$ids) {
- //to change name, CRM-3336
- if (empty($params['label_a_b']) && !empty($params['name_a_b'])) {
- $params['label_a_b'] = $params['name_a_b'];
- }
-
- if (empty($params['label_b_a']) && !empty($params['name_b_a'])) {
- $params['label_b_a'] = $params['name_b_a'];
- }
+ public static function add($params) {
+ if (empty($params['id'])) {
+ // Set name to label if not set
+ if (empty($params['label_a_b']) && !empty($params['name_a_b'])) {
+ $params['label_a_b'] = $params['name_a_b'];
+ }
+ if (empty($params['label_b_a']) && !empty($params['name_b_a'])) {
+ $params['label_b_a'] = $params['name_b_a'];
+ }
- // set label to name if it's not set - but *only* for
- // ADD action. CRM-3336 as part from (CRM-3522)
- if (empty($ids['relationshipType'])) {
+ // set label to name if it's not set
if (empty($params['name_a_b']) && !empty($params['label_a_b'])) {
$params['name_a_b'] = $params['label_a_b'];
}
@@ -109,24 +103,18 @@ public static function add(&$params, &$ids) {
// action is taken depending upon the mode
$relationshipType = new CRM_Contact_DAO_RelationshipType();
- $relationshipType->copyValues($params);
+ $hook = empty($params['id']) ? 'create' : 'edit';
+ CRM_Utils_Hook::pre($hook, 'RelationshipType', CRM_Utils_Array::value('id', $params), $params);
- // if label B to A is blank, insert the value label A to B for it
- if (!strlen(trim($strName = CRM_Utils_Array::value('name_b_a', $params)))) {
- $relationshipType->name_b_a = CRM_Utils_Array::value('name_a_b', $params);
- }
- if (!strlen(trim($strName = CRM_Utils_Array::value('label_b_a', $params)))) {
- $relationshipType->label_b_a = CRM_Utils_Array::value('label_a_b', $params);
- }
-
- $relationshipType->id = CRM_Utils_Array::value('relationshipType', $ids);
+ $relationshipType->copyValues($params);
+ $relationshipType->save();
- $result = $relationshipType->save();
+ CRM_Utils_Hook::post($hook, 'RelationshipType', $relationshipType->id, $relationshipType);
CRM_Core_PseudoConstant::relationshipType('label', TRUE);
CRM_Core_PseudoConstant::relationshipType('name', TRUE);
CRM_Case_XMLProcessor::flushStaticCaches();
- return $result;
+ return $relationshipType;
}
/**
@@ -153,10 +141,10 @@ public static function del($relationshipTypeId) {
$relationship->delete();
// remove this relationship type from membership types
- $mems = civicrm_api3('MembershipType', 'get', array(
- 'relationship_type_id' => array('LIKE' => "%{$relationshipTypeId}%"),
- 'return' => array('id', 'relationship_type_id', 'relationship_direction'),
- ));
+ $mems = civicrm_api3('MembershipType', 'get', [
+ 'relationship_type_id' => ['LIKE' => "%{$relationshipTypeId}%"],
+ 'return' => ['id', 'relationship_type_id', 'relationship_direction'],
+ ]);
foreach ($mems['values'] as $membershipTypeId => $membershipType) {
$pos = array_search($relationshipTypeId, $membershipType['relationship_type_id']);
// Api call may have returned false positives but currently the relationship_type_id uses
diff --git a/CRM/Contact/BAO/SavedSearch.php b/CRM/Contact/BAO/SavedSearch.php
index 694f849847db..049dcaf5170b 100644
--- a/CRM/Contact/BAO/SavedSearch.php
+++ b/CRM/Contact/BAO/SavedSearch.php
@@ -1,9 +1,9 @@
'event_date_low',
+ 'event_end_date_high' => 'event_date_high',
+ 'participant_register_date_low' => 'participant_date_low',
+ 'participant_register_date_high' => 'participant_date_high',
+ 'case_from_start_date_low' => 'case_from_date_low',
+ 'case_from_start_date_high' => 'case_from_date_high',
+ 'case_to_end_date_low' => 'case_to_date_low',
+ 'case_to_end_date_high' => 'case_to_date_high',
+ ];
+
$fv = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $id, 'form_values');
$result = NULL;
if ($fv) {
@@ -99,7 +110,7 @@ public static function getFormValues($id) {
$result = unserialize($fv);
}
- $specialFields = array('contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id');
+ $specialFields = ['contact_type', 'group', 'contact_tags', 'member_membership_type_id', 'member_status_id'];
foreach ($result as $element => $value) {
if (CRM_Contact_BAO_Query::isAlreadyProcessedForQueryFormat($value)) {
$id = CRM_Utils_Array::value(0, $value);
@@ -107,21 +118,36 @@ public static function getFormValues($id) {
if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
$value = CRM_Utils_Array::value($op, $value);
- if (in_array($op, array('BETWEEN', '>=', '<='))) {
+ if (in_array($op, ['BETWEEN', '>=', '<='])) {
self::decodeRelativeFields($result, $id, $op, $value);
unset($result[$element]);
continue;
}
}
+ // Check for a date range field, which might be a standard date
+ // range or a relative date.
if (strpos($id, '_date_low') !== FALSE || strpos($id, '_date_high') !== FALSE) {
$entityName = strstr($id, '_date', TRUE);
- if (!empty($result['relative_dates']) && array_key_exists($entityName, $result['relative_dates'])) {
- $result[$id] = NULL;
- $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
- }
- else {
- $result[$id] = $value;
- $result["{$entityName}_date_relative"] = 0;
+
+ // This is the default, for non relative dates. We will overwrite
+ // it if we determine this is a relative date.
+ $result[$id] = $value;
+ $result["{$entityName}_date_relative"] = 0;
+
+ if (!empty($result['relative_dates'])) {
+ if (array_key_exists($entityName, $result['relative_dates'])) {
+ // We have a match from a regular field.
+ $result[$id] = NULL;
+ $result["{$entityName}_date_relative"] = $result['relative_dates'][$entityName];
+ }
+ elseif (!empty($specialDateFields[$id])) {
+ // We may have a match on a special date field.
+ $entityName = strstr($specialDateFields[$id], '_date', TRUE);
+ if (array_key_exists($entityName, $result['relative_dates'])) {
+ $result[$id] = NULL;
+ $result["{$entityName}_relative"] = $result['relative_dates'][$entityName];
+ }
+ }
}
}
else {
@@ -172,7 +198,7 @@ public static function getFormValues($id) {
unset($result['privacy']['do_not_toggle']);
}
- $result['privacy_options'] = array();
+ $result['privacy_options'] = [];
foreach ($result['privacy'] as $name => $val) {
if ($val) {
$result['privacy_options'][] = $name;
@@ -183,6 +209,13 @@ public static function getFormValues($id) {
}
}
+ if ($customSearchClass = CRM_Utils_Array::value('customSearchClass', $result)) {
+ // check if there is a special function - formatSavedSearchFields defined in the custom search form
+ if (method_exists($customSearchClass, 'formatSavedSearchFields')) {
+ $customSearchClass::formatSavedSearchFields($result);
+ }
+ }
+
return $result;
}
@@ -246,7 +279,7 @@ public static function contactIDsSQL($id) {
return CRM_Contact_BAO_SearchCustom::contactIDSQL(NULL, $id);
}
else {
- $tables = $whereTables = array('civicrm_contact' => 1);
+ $tables = $whereTables = ['civicrm_contact' => 1];
$where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
if (!$where) {
$where = '( 1 )';
@@ -274,10 +307,10 @@ public static function fromWhereEmail($id) {
return CRM_Contact_BAO_SearchCustom::fromWhereEmail(NULL, $id);
}
else {
- $tables = $whereTables = array('civicrm_contact' => 1, 'civicrm_email' => 1);
+ $tables = $whereTables = ['civicrm_contact' => 1, 'civicrm_email' => 1];
$where = CRM_Contact_BAO_SavedSearch::whereClause($id, $tables, $whereTables);
$from = CRM_Contact_BAO_Query::fromClause($whereTables);
- return array($from, $where);
+ return [$from, $where];
}
}
else {
@@ -289,7 +322,7 @@ public static function fromWhereEmail($id) {
$where = " ( 1 ) ";
$tables['civicrm_contact'] = $whereTables['civicrm_contact'] = 1;
$tables['civicrm_email'] = $whereTables['civicrm_email'] = 1;
- return array($from, $where);
+ return [$from, $where];
}
}
@@ -307,7 +340,7 @@ public function buildClause() {
}
if (!empty($params)) {
- $tables = $whereTables = array();
+ $tables = $whereTables = [];
$this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
if (!empty($tables)) {
$this->select_tables = serialize($tables);
@@ -389,7 +422,7 @@ protected function assignTestValue($fieldName, &$fieldDef, $counter) {
if ($fieldName == 'form_values') {
// A dummy value for form_values.
$this->{$fieldName} = serialize(
- array('sort_name' => "SortName{$counter}"));
+ ['sort_name' => "SortName{$counter}"]);
}
else {
parent::assignTestValues($fieldName, $fieldDef, $counter);
@@ -403,10 +436,14 @@ protected function assignTestValue($fieldName, &$fieldDef, $counter) {
* @param array $formValues
*/
public static function saveRelativeDates(&$queryParams, $formValues) {
- $relativeDates = array('relative_dates' => array());
+ $relativeDates = ['relative_dates' => []];
+ $specialDateFields = ['event_relative', 'case_from_relative', 'case_to_relative', 'participant_relative'];
foreach ($formValues as $id => $value) {
- if (preg_match('/_date_relative$/', $id) && !empty($value)) {
+ if ((preg_match('/(_date|custom_[0-9]+)_relative$/', $id) || in_array($id, $specialDateFields)) && !empty($value)) {
$entityName = strstr($id, '_date', TRUE);
+ if (empty($entityName)) {
+ $entityName = strstr($id, '_relative', TRUE);
+ }
$relativeDates['relative_dates'][$entityName] = $value;
}
}
@@ -426,14 +463,15 @@ public static function saveRelativeDates(&$queryParams, $formValues) {
*/
public static function saveSkippedElement(&$queryParams, $formValues) {
// these are elements which are skipped in a smart group criteria
- $specialElements = array(
+ $specialElements = [
'operator',
'component_mode',
'display_relationship_type',
- );
+ 'uf_group_id',
+ ];
foreach ($specialElements as $element) {
if (!empty($formValues[$element])) {
- $queryParams[] = array($element, '=', $formValues[$element], 0, 0);
+ $queryParams[] = [$element, '=', $formValues[$element], 0, 0];
}
}
}
@@ -453,7 +491,12 @@ public static function decodeRelativeFields(&$formValues, $fieldName, $op, $valu
// select date range as default
if ($isCustomDateField) {
- $formValues[$fieldName . '_relative'] = 0;
+ if (array_key_exists('relative_dates', $formValues) && array_key_exists($fieldName, $formValues['relative_dates'])) {
+ $formValues[$fieldName . '_relative'] = $formValues['relative_dates'][$fieldName];
+ }
+ else {
+ $formValues[$fieldName . '_relative'] = 0;
+ }
}
switch ($op) {
case 'BETWEEN':
diff --git a/CRM/Contact/BAO/SearchCustom.php b/CRM/Contact/BAO/SearchCustom.php
index e13bc52c4f14..cadd086e4c40 100644
--- a/CRM/Contact/BAO/SearchCustom.php
+++ b/CRM/Contact/BAO/SearchCustom.php
@@ -1,9 +1,9 @@
'custom_search',
'return' => 'name',
'value' => $customSearchID,
- ));
+ ]);
$ext = CRM_Extension_System::singleton()->getMapper();
@@ -95,7 +95,7 @@ public static function details($csID, $ssID = NULL, $gID = NULL) {
CRM_Core_Error::fatal('Custom search file: ' . $customSearchFile . ' does not exist. Please verify your custom search settings in CiviCRM administrative panel.');
}
- return array($customSearchID, $customSearchClass, $formValues);
+ return [$customSearchID, $customSearchClass, $formValues];
}
/**
@@ -138,7 +138,7 @@ public static function &buildFormValues($args) {
$args = trim($args);
$values = explode("\n", $args);
- $formValues = array();
+ $formValues = [];
foreach ($values as $value) {
list($n, $v) = CRM_Utils_System::explode('=', $value, 2);
if (!empty($v)) {
@@ -160,7 +160,7 @@ public static function fromWhereEmail($csID, $ssID) {
$from = $customClass->from();
$where = $customClass->where();
- return array($from, $where);
+ return [$from, $where];
}
}
diff --git a/CRM/Contact/BAO/SubscriptionHistory.php b/CRM/Contact/BAO/SubscriptionHistory.php
index 331e2add53fb..ec1a44d18991 100644
--- a/CRM/Contact/BAO/SubscriptionHistory.php
+++ b/CRM/Contact/BAO/SubscriptionHistory.php
@@ -1,9 +1,9 @@
__table = 'civicrm_acl_contact_cache';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'user_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('ACL Contact Cache ID') ,
- 'description' => 'primary key',
- 'required' => true,
+ 'title' => ts('ACL Contact Cache ID'),
+ 'description' => ts('primary key'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_acl_contact_cache.id',
'table_name' => 'civicrm_acl_contact_cache',
'entity' => 'ACLContactCache',
'bao' => 'CRM_Contact_DAO_ACLContactCache',
'localizable' => 0,
- ) ,
- 'user_id' => array(
+ ],
+ 'user_id' => [
'name' => 'user_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to civicrm_contact (could be null for anon user)',
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to civicrm_contact (could be null for anon user)'),
+ 'where' => 'civicrm_acl_contact_cache.user_id',
'table_name' => 'civicrm_acl_contact_cache',
'entity' => 'ACLContactCache',
'bao' => 'CRM_Contact_DAO_ACLContactCache',
'localizable' => 0,
- 'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to civicrm_contact',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to civicrm_contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_acl_contact_cache.contact_id',
'table_name' => 'civicrm_acl_contact_cache',
'entity' => 'ACLContactCache',
'bao' => 'CRM_Contact_DAO_ACLContactCache',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'operation' => array(
+ ],
+ 'operation' => [
'name' => 'operation',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Operation') ,
- 'description' => 'What operation does this user have permission on?',
- 'required' => true,
+ 'title' => ts('Operation'),
+ 'description' => ts('What operation does this user have permission on?'),
+ 'required' => TRUE,
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_acl_contact_cache.operation',
'table_name' => 'civicrm_acl_contact_cache',
'entity' => 'ACLContactCache',
'bao' => 'CRM_Contact_DAO_ACLContactCache',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_ACL_BAO_ACL::operation',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -197,10 +187,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_contact_cache', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'acl_contact_cache', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -208,27 +199,33 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_contact_cache', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'acl_contact_cache', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_user_contact_operation' => array(
+ $indices = [
+ 'UI_user_contact_operation' => [
'name' => 'UI_user_contact_operation',
- 'field' => array(
+ 'field' => [
0 => 'user_id',
1 => 'contact_id',
2 => 'operation',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_acl_contact_cache::1::user_id::contact_id::operation',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/Contact.php b/CRM/Contact/DAO/Contact.php
index 98a2c243e5b5..736dffa2f7e5 100644
--- a/CRM/Contact/DAO/Contact.php
+++ b/CRM/Contact/DAO/Contact.php
@@ -1,1406 +1,1417 @@
__table = 'civicrm_contact';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'primary_contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'employer_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'primary_contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'employer_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'Unique Contact ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('Unique Contact ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_contact.id',
'headerPattern' => '/internal|contact?|id$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- ) ,
- 'contact_type' => array(
+ ],
+ 'contact_type' => [
'name' => 'contact_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Type') ,
- 'description' => 'Type of Contact.',
+ 'title' => ts('Contact Type'),
+ 'description' => ts('Type of Contact.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'export' => true,
'where' => 'civicrm_contact.contact_type',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NULL',
- )
- ) ,
- 'contact_sub_type' => array(
+ ]
+ ],
+ 'contact_sub_type' => [
'name' => 'contact_sub_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Subtype') ,
- 'description' => 'May be used to over-ride contact view and edit templates.',
+ 'title' => ts('Contact Subtype'),
+ 'description' => ts('May be used to over-ride contact view and edit templates.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.contact_sub_type',
'headerPattern' => '/C(ontact )?(subtype|sub-type|sub type)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NOT NULL',
- )
- ) ,
- 'do_not_email' => array(
+ ]
+ ],
+ 'do_not_email' => [
'name' => 'do_not_email',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Do Not Email') ,
- 'import' => true,
+ 'title' => ts('Do Not Email'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.do_not_email',
'headerPattern' => '/d(o )?(not )?(email)/i',
'dataPattern' => '/^\d{1,}$/',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'do_not_phone' => array(
+ ],
+ ],
+ 'do_not_phone' => [
'name' => 'do_not_phone',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Do Not Phone') ,
- 'import' => true,
+ 'title' => ts('Do Not Phone'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.do_not_phone',
'headerPattern' => '/d(o )?(not )?(call|phone)/i',
'dataPattern' => '/^\d{1,}$/',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'do_not_mail' => array(
+ ],
+ ],
+ 'do_not_mail' => [
'name' => 'do_not_mail',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Do Not Mail') ,
- 'import' => true,
+ 'title' => ts('Do Not Mail'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.do_not_mail',
'headerPattern' => '/^(d(o\s)?n(ot\s)?mail)|(\w*)?bulk\s?(\w*)$/i',
'dataPattern' => '/^\d{1,}$/',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'do_not_sms' => array(
+ ],
+ ],
+ 'do_not_sms' => [
'name' => 'do_not_sms',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Do Not Sms') ,
- 'import' => true,
+ 'title' => ts('Do Not Sms'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.do_not_sms',
'headerPattern' => '/d(o )?(not )?(sms)/i',
'dataPattern' => '/^\d{1,}$/',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'do_not_trade' => array(
+ ],
+ ],
+ 'do_not_trade' => [
'name' => 'do_not_trade',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Do Not Trade') ,
- 'import' => true,
+ 'title' => ts('Do Not Trade'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.do_not_trade',
'headerPattern' => '/d(o )?(not )?(trade)/i',
'dataPattern' => '/^\d{1,}$/',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_opt_out' => array(
+ ],
+ ],
+ 'is_opt_out' => [
'name' => 'is_opt_out',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('No Bulk Emails (User Opt Out)') ,
- 'description' => 'Has the contact opted out from receiving all bulk email from the organization or site domain?',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('No Bulk Emails (User Opt Out)'),
+ 'description' => ts('Has the contact opted out from receiving all bulk email from the organization or site domain?'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_contact.is_opt_out',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'legal_identifier' => array(
+ ],
+ ],
+ 'legal_identifier' => [
'name' => 'legal_identifier',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Legal Identifier') ,
- 'description' => 'May be used for SSN, EIN/TIN, Household ID (census) or other applicable unique legal/government ID.
- ',
+ 'title' => ts('Legal Identifier'),
+ 'description' => ts('May be used for SSN, EIN/TIN, Household ID (census) or other applicable unique legal/government ID.
+ '),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.legal_identifier',
'headerPattern' => '/legal\s?id/i',
'dataPattern' => '/\w+?\d{5,}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'external_identifier' => array(
+ ],
+ ],
+ 'external_identifier' => [
'name' => 'external_identifier',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('External Identifier') ,
- 'description' => 'Unique trusted external ID (generally from a legacy app/datasource). Particularly useful for deduping operations.',
+ 'title' => ts('External Identifier'),
+ 'description' => ts('Unique trusted external ID (generally from a legacy app/datasource). Particularly useful for deduping operations.'),
'maxlength' => 64,
'size' => 8,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.external_identifier',
'headerPattern' => '/external\s?id/i',
'dataPattern' => '/^\d{11,}$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'sort_name' => array(
+ ],
+ ],
+ 'sort_name' => [
'name' => 'sort_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Sort Name') ,
- 'description' => 'Name used for sorting different contact types',
+ 'title' => ts('Sort Name'),
+ 'description' => ts('Name used for sorting different contact types'),
'maxlength' => 128,
'size' => 30,
- 'export' => true,
'where' => 'civicrm_contact.sort_name',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'display_name' => array(
+ ],
+ ],
+ 'display_name' => [
'name' => 'display_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Display Name') ,
- 'description' => 'Formatted name representing preferred format for display/print/other output.',
+ 'title' => ts('Display Name'),
+ 'description' => ts('Formatted name representing preferred format for display/print/other output.'),
'maxlength' => 128,
'size' => 30,
- 'export' => true,
'where' => 'civicrm_contact.display_name',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'nick_name' => array(
+ ],
+ ],
+ 'nick_name' => [
'name' => 'nick_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Nickname') ,
- 'description' => 'Nickname.',
+ 'title' => ts('Nickname'),
+ 'description' => ts('Nickname.'),
'maxlength' => 128,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.nick_name',
'headerPattern' => '/n(ick\s)name|nick$/i',
'dataPattern' => '/^\w+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'legal_name' => array(
+ ],
+ ],
+ 'legal_name' => [
'name' => 'legal_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Legal Name') ,
- 'description' => 'Legal Name.',
+ 'title' => ts('Legal Name'),
+ 'description' => ts('Legal Name.'),
'maxlength' => 128,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.legal_name',
'headerPattern' => '/^legal|(l(egal\s)?name)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'image_URL' => array(
+ ],
+ ],
+ 'image_URL' => [
'name' => 'image_URL',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Image Url') ,
- 'description' => 'optional URL for preferred image (photo, logo, etc.) to display for this contact.',
- 'import' => true,
+ 'title' => ts('Image Url'),
+ 'description' => ts('optional URL for preferred image (photo, logo, etc.) to display for this contact.'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.image_URL',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'File',
- ) ,
- ) ,
- 'preferred_communication_method' => array(
+ ],
+ ],
+ 'preferred_communication_method' => [
'name' => 'preferred_communication_method',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Preferred Communication Method') ,
- 'description' => 'What is the preferred mode of communication.',
+ 'title' => ts('Preferred Communication Method'),
+ 'description' => ts('What is the preferred mode of communication.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.preferred_communication_method',
'headerPattern' => '/^p(ref\w*\s)?c(omm\w*)|( meth\w*)$/i',
'dataPattern' => '/^\w+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'preferred_communication_method',
'optionEditPath' => 'civicrm/admin/options/preferred_communication_method',
- )
- ) ,
- 'preferred_language' => array(
+ ]
+ ],
+ 'preferred_language' => [
'name' => 'preferred_language',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Preferred Language') ,
- 'description' => 'Which language is preferred for communication. FK to languages in civicrm_option_value.',
+ 'title' => ts('Preferred Language'),
+ 'description' => ts('Which language is preferred for communication. FK to languages in civicrm_option_value.'),
'maxlength' => 5,
'size' => CRM_Utils_Type::SIX,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.preferred_language',
'headerPattern' => '/^lang/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'languages',
'keyColumn' => 'name',
'optionEditPath' => 'civicrm/admin/options/languages',
- )
- ) ,
- 'preferred_mail_format' => array(
+ ]
+ ],
+ 'preferred_mail_format' => [
'name' => 'preferred_mail_format',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Preferred Mail Format') ,
- 'description' => 'What is the preferred mode of sending an email.',
+ 'title' => ts('Preferred Mail Format'),
+ 'description' => ts('What is the preferred mode of sending an email.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.preferred_mail_format',
'headerPattern' => '/^p(ref\w*\s)?m(ail\s)?f(orm\w*)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'Both',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::pmf',
- )
- ) ,
- 'hash' => array(
+ ]
+ ],
+ 'hash' => [
'name' => 'hash',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Hash') ,
- 'description' => 'Key for validating requests related to this contact.',
+ 'title' => ts('Contact Hash'),
+ 'description' => ts('Key for validating requests related to this contact.'),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
- 'export' => true,
'where' => 'civicrm_contact.hash',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- ) ,
- 'api_key' => array(
+ ],
+ 'api_key' => [
'name' => 'api_key',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Api Key') ,
- 'description' => 'API Key for validating requests related to this contact.',
+ 'title' => ts('Api Key'),
+ 'description' => ts('API Key for validating requests related to this contact.'),
'maxlength' => 32,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_contact.api_key',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- ) ,
- 'contact_source' => array(
+ ],
+ 'contact_source' => [
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Source') ,
- 'description' => 'where contact come from, e.g. import, donate module insert...',
+ 'title' => ts('Contact Source'),
+ 'description' => ts('where contact come from, e.g. import, donate module insert...'),
'maxlength' => 255,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.source',
'headerPattern' => '/(C(ontact\s)?Source)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'first_name' => array(
+ ],
+ ],
+ 'first_name' => [
'name' => 'first_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('First Name') ,
- 'description' => 'First Name.',
+ 'title' => ts('First Name'),
+ 'description' => ts('First Name.'),
'maxlength' => 64,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.first_name',
'headerPattern' => '/^first|(f(irst\s)?name)$/i',
'dataPattern' => '/^\w+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'middle_name' => array(
+ ],
+ ],
+ 'middle_name' => [
'name' => 'middle_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Middle Name') ,
- 'description' => 'Middle Name.',
+ 'title' => ts('Middle Name'),
+ 'description' => ts('Middle Name.'),
'maxlength' => 64,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.middle_name',
'headerPattern' => '/^middle|(m(iddle\s)?name)$/i',
'dataPattern' => '/^\w+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'last_name' => array(
+ ],
+ ],
+ 'last_name' => [
'name' => 'last_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Last Name') ,
- 'description' => 'Last Name.',
+ 'title' => ts('Last Name'),
+ 'description' => ts('Last Name.'),
'maxlength' => 64,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.last_name',
'headerPattern' => '/^last|(l(ast\s)?name)$/i',
'dataPattern' => '/^\w+(\s\w+)?+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'prefix_id' => array(
+ ],
+ ],
+ 'prefix_id' => [
'name' => 'prefix_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Individual Prefix') ,
- 'description' => 'Prefix or Title for name (Ms, Mr...). FK to prefix ID',
- 'import' => true,
+ 'title' => ts('Individual Prefix'),
+ 'description' => ts('Prefix or Title for name (Ms, Mr...). FK to prefix ID'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.prefix_id',
'headerPattern' => '/^(prefix|title)/i',
'dataPattern' => '/^(mr|ms|mrs|sir|dr)\.?$/i',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'individual_prefix',
'optionEditPath' => 'civicrm/admin/options/individual_prefix',
- )
- ) ,
- 'suffix_id' => array(
+ ]
+ ],
+ 'suffix_id' => [
'name' => 'suffix_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Individual Suffix') ,
- 'description' => 'Suffix for name (Jr, Sr...). FK to suffix ID',
- 'import' => true,
+ 'title' => ts('Individual Suffix'),
+ 'description' => ts('Suffix for name (Jr, Sr...). FK to suffix ID'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.suffix_id',
'headerPattern' => '/^suffix$/i',
'dataPattern' => '/^(sr|jr)\.?|i{2,}$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'individual_suffix',
'optionEditPath' => 'civicrm/admin/options/individual_suffix',
- )
- ) ,
- 'formal_title' => array(
+ ]
+ ],
+ 'formal_title' => [
'name' => 'formal_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Formal Title') ,
- 'description' => 'Formal (academic or similar) title in front of name. (Prof., Dr. etc.)',
+ 'title' => ts('Formal Title'),
+ 'description' => ts('Formal (academic or similar) title in front of name. (Prof., Dr. etc.)'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.formal_title',
'headerPattern' => '/^title/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'communication_style_id' => array(
+ ],
+ ],
+ 'communication_style_id' => [
'name' => 'communication_style_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Communication Style') ,
- 'description' => 'Communication style (e.g. formal vs. familiar) to use with this contact. FK to communication styles in civicrm_option_value.',
- 'export' => true,
+ 'title' => ts('Communication Style'),
+ 'description' => ts('Communication style (e.g. formal vs. familiar) to use with this contact. FK to communication styles in civicrm_option_value.'),
'where' => 'civicrm_contact.communication_style_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'communication_style',
'optionEditPath' => 'civicrm/admin/options/communication_style',
- )
- ) ,
- 'email_greeting_id' => array(
+ ]
+ ],
+ 'email_greeting_id' => [
'name' => 'email_greeting_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Email Greeting ID') ,
- 'description' => 'FK to civicrm_option_value.id, that has to be valid registered Email Greeting.',
+ 'title' => ts('Email Greeting ID'),
+ 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Email Greeting.'),
+ 'where' => 'civicrm_contact.email_greeting_id',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'email_greeting',
'optionEditPath' => 'civicrm/admin/options/email_greeting',
- )
- ) ,
- 'email_greeting_custom' => array(
+ ]
+ ],
+ 'email_greeting_custom' => [
'name' => 'email_greeting_custom',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Email Greeting Custom') ,
- 'description' => 'Custom Email Greeting.',
+ 'title' => ts('Email Greeting Custom'),
+ 'description' => ts('Custom Email Greeting.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.email_greeting_custom',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'email_greeting_display' => array(
+ ],
+ ],
+ 'email_greeting_display' => [
'name' => 'email_greeting_display',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Email Greeting') ,
- 'description' => 'Cache Email Greeting.',
+ 'title' => ts('Email Greeting'),
+ 'description' => ts('Cache Email Greeting.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_contact.email_greeting_display',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'postal_greeting_id' => array(
+ ],
+ ],
+ 'postal_greeting_id' => [
'name' => 'postal_greeting_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Postal Greeting ID') ,
- 'description' => 'FK to civicrm_option_value.id, that has to be valid registered Postal Greeting.',
+ 'title' => ts('Postal Greeting ID'),
+ 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Postal Greeting.'),
+ 'where' => 'civicrm_contact.postal_greeting_id',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'postal_greeting',
'optionEditPath' => 'civicrm/admin/options/postal_greeting',
- )
- ) ,
- 'postal_greeting_custom' => array(
+ ]
+ ],
+ 'postal_greeting_custom' => [
'name' => 'postal_greeting_custom',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Postal Greeting Custom') ,
- 'description' => 'Custom Postal greeting.',
+ 'title' => ts('Postal Greeting Custom'),
+ 'description' => ts('Custom Postal greeting.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.postal_greeting_custom',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'postal_greeting_display' => array(
+ ],
+ ],
+ 'postal_greeting_display' => [
'name' => 'postal_greeting_display',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Postal Greeting') ,
- 'description' => 'Cache Postal greeting.',
+ 'title' => ts('Postal Greeting'),
+ 'description' => ts('Cache Postal greeting.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_contact.postal_greeting_display',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'addressee_id' => array(
+ ],
+ ],
+ 'addressee_id' => [
'name' => 'addressee_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Addressee ID') ,
- 'description' => 'FK to civicrm_option_value.id, that has to be valid registered Addressee.',
+ 'title' => ts('Addressee ID'),
+ 'description' => ts('FK to civicrm_option_value.id, that has to be valid registered Addressee.'),
+ 'where' => 'civicrm_contact.addressee_id',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- ) ,
- 'addressee_custom' => array(
+ 'pseudoconstant' => [
+ 'optionGroupName' => 'addressee',
+ 'optionEditPath' => 'civicrm/admin/options/addressee',
+ ]
+ ],
+ 'addressee_custom' => [
'name' => 'addressee_custom',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Addressee Custom') ,
- 'description' => 'Custom Addressee.',
+ 'title' => ts('Addressee Custom'),
+ 'description' => ts('Custom Addressee.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.addressee_custom',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- 'pseudoconstant' => array(
- 'optionGroupName' => 'addressee',
- 'optionEditPath' => 'civicrm/admin/options/addressee',
- )
- ) ,
- 'addressee_display' => array(
+ ],
+ ],
+ 'addressee_display' => [
'name' => 'addressee_display',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Addressee') ,
- 'description' => 'Cache Addressee.',
+ 'title' => ts('Addressee'),
+ 'description' => ts('Cache Addressee.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_contact.addressee_display',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'job_title' => array(
+ ],
+ ],
+ 'job_title' => [
'name' => 'job_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Job Title') ,
- 'description' => 'Job Title',
+ 'title' => ts('Job Title'),
+ 'description' => ts('Job Title'),
'maxlength' => 255,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.job_title',
'headerPattern' => '/^job|(j(ob\s)?title)$/i',
'dataPattern' => '//',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'gender_id' => array(
+ ],
+ ],
+ 'gender_id' => [
'name' => 'gender_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Gender') ,
- 'description' => 'FK to gender ID',
- 'import' => true,
+ 'title' => ts('Gender'),
+ 'description' => ts('FK to gender ID'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.gender_id',
'headerPattern' => '/^gender$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'gender',
'optionEditPath' => 'civicrm/admin/options/gender',
- )
- ) ,
- 'birth_date' => array(
+ ]
+ ],
+ 'birth_date' => [
'name' => 'birth_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Birth Date') ,
- 'description' => 'Date of birth',
- 'import' => true,
+ 'title' => ts('Birth Date'),
+ 'description' => ts('Date of birth'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.birth_date',
'headerPattern' => '/^birth|(b(irth\s)?date)|D(\W*)O(\W*)B(\W*)$/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'birth',
- ) ,
- ) ,
- 'is_deceased' => array(
+ ],
+ ],
+ 'is_deceased' => [
'name' => 'is_deceased',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Deceased') ,
- 'import' => true,
+ 'title' => ts('Deceased'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.is_deceased',
'headerPattern' => '/i(s\s)?d(eceased)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'deceased_date' => array(
+ ],
+ ],
+ 'deceased_date' => [
'name' => 'deceased_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Deceased Date') ,
- 'description' => 'Date of deceased',
- 'import' => true,
+ 'title' => ts('Deceased Date'),
+ 'description' => ts('Date of deceased'),
+ 'import' => TRUE,
'where' => 'civicrm_contact.deceased_date',
'headerPattern' => '/^deceased|(d(eceased\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'birth',
- ) ,
- ) ,
- 'household_name' => array(
+ ],
+ ],
+ 'household_name' => [
'name' => 'household_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Household Name') ,
- 'description' => 'Household Name.',
+ 'title' => ts('Household Name'),
+ 'description' => ts('Household Name.'),
'maxlength' => 128,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.household_name',
'headerPattern' => '/^household|(h(ousehold\s)?name)$/i',
'dataPattern' => '/^\w+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'primary_contact_id' => array(
+ ],
+ ],
+ 'primary_contact_id' => [
'name' => 'primary_contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Household Primary Contact ID') ,
- 'description' => 'Optional FK to Primary Contact for this household.',
+ 'title' => ts('Household Primary Contact ID'),
+ 'description' => ts('Optional FK to Primary Contact for this household.'),
+ 'where' => 'civicrm_contact.primary_contact_id',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'organization_name' => array(
+ ],
+ ],
+ 'organization_name' => [
'name' => 'organization_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Organization Name') ,
- 'description' => 'Organization Name.',
+ 'title' => ts('Organization Name'),
+ 'description' => ts('Organization Name.'),
'maxlength' => 128,
'size' => 30,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.organization_name',
'headerPattern' => '/^organization|(o(rganization\s)?name)$/i',
'dataPattern' => '/^\w+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'sic_code' => array(
+ ],
+ ],
+ 'sic_code' => [
'name' => 'sic_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Sic Code') ,
- 'description' => 'Standard Industry Classification Code.',
+ 'title' => ts('Sic Code'),
+ 'description' => ts('Standard Industry Classification Code.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.sic_code',
'headerPattern' => '/^sic|(s(ic\s)?code)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'user_unique_id' => array(
+ ],
+ ],
+ 'user_unique_id' => [
'name' => 'user_unique_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Unique ID (OpenID)') ,
- 'description' => 'the OpenID (or OpenID-style http://username.domain/) unique identifier for this contact mainly used for logging in to CiviCRM',
+ 'title' => ts('Unique ID (OpenID)'),
+ 'description' => ts('the OpenID (or OpenID-style http://username.domain/) unique identifier for this contact mainly used for logging in to CiviCRM'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_contact.user_unique_id',
'headerPattern' => '/^Open\s?ID|u(niq\w*)?\s?ID/i',
'dataPattern' => '/^[\w\/\:\.]+$/',
- 'export' => true,
+ 'export' => TRUE,
'rule' => 'url',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'current_employer_id' => array(
+ ],
+ ],
+ 'current_employer_id' => [
'name' => 'employer_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Current Employer') ,
- 'description' => 'OPTIONAL FK to civicrm_contact record.',
- 'export' => true,
+ 'title' => ts('Current Employer'),
+ 'description' => ts('OPTIONAL FK to civicrm_contact record.'),
'where' => 'civicrm_contact.employer_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'contact_is_deleted' => array(
+ ],
+ ],
+ 'contact_is_deleted' => [
'name' => 'is_deleted',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Contact is in Trash') ,
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Contact is in Trash'),
+ 'required' => TRUE,
'where' => 'civicrm_contact.is_deleted',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'created_date' => array(
+ ],
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Created Date') ,
- 'description' => 'When was the contact was created.',
- 'required' => false,
- 'export' => true,
+ 'title' => ts('Created Date'),
+ 'description' => ts('When was the contact was created.'),
+ 'required' => FALSE,
'where' => 'civicrm_contact.created_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- ) ,
- 'modified_date' => array(
+ ],
+ 'modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Modified Date') ,
- 'description' => 'When was the contact (or closely related entity) was created or modified or deleted.',
- 'required' => false,
- 'export' => true,
+ 'title' => ts('Modified Date'),
+ 'description' => ts('When was the contact (or closely related entity) was created or modified or deleted.'),
+ 'required' => FALSE,
'where' => 'civicrm_contact.modified_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'table_name' => 'civicrm_contact',
'entity' => 'Contact',
'bao' => 'CRM_Contact_BAO_Contact',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -1408,10 +1419,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -1419,155 +1431,161 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_contact_type' => array(
+ $indices = [
+ 'index_contact_type' => [
'name' => 'index_contact_type',
- 'field' => array(
+ 'field' => [
0 => 'contact_type',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::contact_type',
- ) ,
- 'index_contact_sub_type' => array(
+ ],
+ 'index_contact_sub_type' => [
'name' => 'index_contact_sub_type',
- 'field' => array(
+ 'field' => [
0 => 'contact_sub_type',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::contact_sub_type',
- ) ,
- 'UI_external_identifier' => array(
+ ],
+ 'UI_external_identifier' => [
'name' => 'UI_external_identifier',
- 'field' => array(
+ 'field' => [
0 => 'external_identifier',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_contact::1::external_identifier',
- ) ,
- 'index_sort_name' => array(
+ ],
+ 'index_sort_name' => [
'name' => 'index_sort_name',
- 'field' => array(
+ 'field' => [
0 => 'sort_name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::sort_name',
- ) ,
- 'index_preferred_communication_method' => array(
+ ],
+ 'index_preferred_communication_method' => [
'name' => 'index_preferred_communication_method',
- 'field' => array(
+ 'field' => [
0 => 'preferred_communication_method',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::preferred_communication_method',
- ) ,
- 'index_hash' => array(
+ ],
+ 'index_hash' => [
'name' => 'index_hash',
- 'field' => array(
+ 'field' => [
0 => 'hash',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::hash',
- ) ,
- 'index_api_key' => array(
+ ],
+ 'index_api_key' => [
'name' => 'index_api_key',
- 'field' => array(
+ 'field' => [
0 => 'api_key',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::api_key',
- ) ,
- 'index_first_name' => array(
+ ],
+ 'index_first_name' => [
'name' => 'index_first_name',
- 'field' => array(
+ 'field' => [
0 => 'first_name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::first_name',
- ) ,
- 'index_last_name' => array(
+ ],
+ 'index_last_name' => [
'name' => 'index_last_name',
- 'field' => array(
+ 'field' => [
0 => 'last_name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::last_name',
- ) ,
- 'UI_prefix' => array(
+ ],
+ 'UI_prefix' => [
'name' => 'UI_prefix',
- 'field' => array(
+ 'field' => [
0 => 'prefix_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::prefix_id',
- ) ,
- 'UI_suffix' => array(
+ ],
+ 'UI_suffix' => [
'name' => 'UI_suffix',
- 'field' => array(
+ 'field' => [
0 => 'suffix_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::suffix_id',
- ) ,
- 'index_communication_style_id' => array(
+ ],
+ 'index_communication_style_id' => [
'name' => 'index_communication_style_id',
- 'field' => array(
+ 'field' => [
0 => 'communication_style_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::communication_style_id',
- ) ,
- 'UI_gender' => array(
+ ],
+ 'UI_gender' => [
'name' => 'UI_gender',
- 'field' => array(
+ 'field' => [
0 => 'gender_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::gender_id',
- ) ,
- 'index_is_deceased' => array(
+ ],
+ 'index_is_deceased' => [
'name' => 'index_is_deceased',
- 'field' => array(
+ 'field' => [
0 => 'is_deceased',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::is_deceased',
- ) ,
- 'index_household_name' => array(
+ ],
+ 'index_household_name' => [
'name' => 'index_household_name',
- 'field' => array(
+ 'field' => [
0 => 'household_name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::household_name',
- ) ,
- 'index_organization_name' => array(
+ ],
+ 'index_organization_name' => [
'name' => 'index_organization_name',
- 'field' => array(
+ 'field' => [
0 => 'organization_name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::organization_name',
- ) ,
- 'index_is_deleted_sort_name' => array(
+ ],
+ 'index_is_deleted_sort_name' => [
'name' => 'index_is_deleted_sort_name',
- 'field' => array(
+ 'field' => [
0 => 'is_deleted',
1 => 'sort_name',
2 => 'id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_contact::0::is_deleted::sort_name::id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/ContactType.php b/CRM/Contact/DAO/ContactType.php
index efc21bcb8e6e..f76bbaab4cf3 100644
--- a/CRM/Contact/DAO/ContactType.php
+++ b/CRM/Contact/DAO/ContactType.php
@@ -1,264 +1,264 @@
__table = 'civicrm_contact_type';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_contact_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_id', 'civicrm_contact_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact Type ID') ,
- 'description' => 'Contact Type ID',
- 'required' => true,
+ 'title' => ts('Contact Type ID'),
+ 'description' => ts('Contact Type ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_contact_type.id',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Internal name of Contact Type (or Subtype).',
+ 'title' => ts('Name'),
+ 'description' => ts('Internal name of Contact Type (or Subtype).'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_contact_type.name',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 0,
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Type Label') ,
- 'description' => 'localized Name of Contact Type.',
+ 'title' => ts('Contact Type Label'),
+ 'description' => ts('localized Name of Contact Type.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_contact_type.label',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 1,
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Contact Type Description') ,
- 'description' => 'localized Optional verbose description of the type.',
+ 'title' => ts('Contact Type Description'),
+ 'description' => ts('localized Optional verbose description of the type.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_contact_type.description',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'image_URL' => array(
+ ],
+ ],
+ 'image_URL' => [
'name' => 'image_URL',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Type Image URL') ,
- 'description' => 'URL of image if any.',
+ 'title' => ts('Contact Type Image URL'),
+ 'description' => ts('URL of image if any.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_contact_type.image_URL',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 0,
- ) ,
- 'parent_id' => array(
+ ],
+ 'parent_id' => [
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact Type Parent') ,
- 'description' => 'Optional FK to parent contact type.',
+ 'title' => ts('Contact Type Parent'),
+ 'description' => ts('Optional FK to parent contact type.'),
+ 'where' => 'civicrm_contact_type.parent_id',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_ContactType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'id',
'labelColumn' => 'label',
'condition' => 'parent_id IS NULL',
- )
- ) ,
- 'is_active' => array(
+ ]
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Contact Type Is Active?') ,
- 'description' => 'Is this entry active?',
+ 'title' => ts('Contact Type Is Active?'),
+ 'description' => ts('Is this entry active?'),
+ 'where' => 'civicrm_contact_type.is_active',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Contact Type is Reserved?') ,
- 'description' => 'Is this contact type a predefined system type',
+ 'title' => ts('Contact Type is Reserved?'),
+ 'description' => ts('Is this contact type a predefined system type'),
+ 'where' => 'civicrm_contact_type.is_reserved',
'table_name' => 'civicrm_contact_type',
'entity' => 'ContactType',
'bao' => 'CRM_Contact_BAO_ContactType',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -266,10 +266,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'contact_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -277,25 +278,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'contact_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'contact_type' => array(
+ $indices = [
+ 'contact_type' => [
'name' => 'contact_type',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_contact_type::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/DashboardContact.php b/CRM/Contact/DAO/DashboardContact.php
index 951be6206121..4585ec169af0 100644
--- a/CRM/Contact/DAO/DashboardContact.php
+++ b/CRM/Contact/DAO/DashboardContact.php
@@ -1,217 +1,215 @@
__table = 'civicrm_dashboard_contact';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'dashboard_id', 'civicrm_dashboard', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'dashboard_id', 'civicrm_dashboard', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dashboard Contact ID') ,
- 'required' => true,
+ 'title' => ts('Dashboard Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dashboard_contact.id',
'table_name' => 'civicrm_dashboard_contact',
'entity' => 'DashboardContact',
'bao' => 'CRM_Contact_BAO_DashboardContact',
'localizable' => 0,
- ) ,
- 'dashboard_id' => array(
+ ],
+ 'dashboard_id' => [
'name' => 'dashboard_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dashboard') ,
- 'description' => 'Dashboard ID',
- 'required' => true,
+ 'title' => ts('Dashboard'),
+ 'description' => ts('Dashboard ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dashboard_contact.dashboard_id',
'table_name' => 'civicrm_dashboard_contact',
'entity' => 'DashboardContact',
'bao' => 'CRM_Contact_BAO_DashboardContact',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Dashboard',
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dashboard Contact') ,
- 'description' => 'Contact ID',
- 'required' => true,
+ 'title' => ts('Dashboard Contact'),
+ 'description' => ts('Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dashboard_contact.contact_id',
'table_name' => 'civicrm_dashboard_contact',
'entity' => 'DashboardContact',
'bao' => 'CRM_Contact_BAO_DashboardContact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'column_no' => array(
+ ],
+ 'column_no' => [
'name' => 'column_no',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Column No') ,
- 'description' => 'column no for this widget',
+ 'title' => ts('Column No'),
+ 'description' => ts('column no for this widget'),
+ 'where' => 'civicrm_dashboard_contact.column_no',
+ 'default' => '0',
'table_name' => 'civicrm_dashboard_contact',
'entity' => 'DashboardContact',
'bao' => 'CRM_Contact_BAO_DashboardContact',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Dashlet is Active?') ,
- 'description' => 'Is this widget active?',
+ 'title' => ts('Dashlet is Active?'),
+ 'description' => ts('Is this widget active?'),
+ 'where' => 'civicrm_dashboard_contact.is_active',
+ 'default' => '0',
'table_name' => 'civicrm_dashboard_contact',
'entity' => 'DashboardContact',
'bao' => 'CRM_Contact_BAO_DashboardContact',
'localizable' => 0,
- ) ,
- 'weight' => array(
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'Ordering of the widgets.',
+ 'title' => ts('Order'),
+ 'description' => ts('Ordering of the widgets.'),
+ 'where' => 'civicrm_dashboard_contact.weight',
+ 'default' => '0',
'table_name' => 'civicrm_dashboard_contact',
'entity' => 'DashboardContact',
'bao' => 'CRM_Contact_BAO_DashboardContact',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -219,10 +217,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dashboard_contact', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dashboard_contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -230,26 +229,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dashboard_contact', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dashboard_contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_dashboard_id_contact_id' => array(
+ $indices = [
+ 'index_dashboard_id_contact_id' => [
'name' => 'index_dashboard_id_contact_id',
- 'field' => array(
+ 'field' => [
0 => 'dashboard_id',
1 => 'contact_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_dashboard_contact::1::dashboard_id::contact_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/Factory.php b/CRM/Contact/DAO/Factory.php
index 5f4432c2b50f..8af2fc1ac416 100644
--- a/CRM/Contact/DAO/Factory.php
+++ b/CRM/Contact/DAO/Factory.php
@@ -5,7 +5,7 @@
*/
class CRM_Contact_DAO_Factory {
- static $_classes = array(
+ public static $_classes = [
'Address' => 'data',
'Contact' => 'data',
'Email' => 'data',
@@ -17,39 +17,35 @@ class CRM_Contact_DAO_Factory {
'Organization' => 'data',
'Phone' => 'data',
'Relationship' => 'data',
- );
+ ];
- static $_prefix = array(
- 'business' => 'CRM/Contact/BAO/',
- 'data' => 'CRM/Contact/DAO/',
- );
-
- static $_suffix = '.php';
+ public static $_prefix = [
+ 'business' => 'CRM_Contact_BAO_',
+ 'data' => 'CRM_Contact_DAO_',
+ ];
/**
* @param string $className
*
* @return mixed
*/
- static function &create($className) {
+ public static function create($className) {
$type = CRM_Utils_Array::value($className, self::$_classes);
if (!$type) {
return CRM_Core_DAO_Factory::create($className);
}
- $file = self::$_prefix[$type] . $className;
- $class = str_replace('/', '_', $file);
-
- require_once($file . self::$_suffix);
+ $class = self::$_prefix[$type] . $className;
if ($type == 'singleton') {
$newObj = $class::singleton();
}
else {
// this is either 'business' or 'data'
- $newObj = new $class;
+ $newObj = new $class();
}
return $newObj;
}
+
}
diff --git a/CRM/Contact/DAO/Group.php b/CRM/Contact/DAO/Group.php
index f3a4ad3091aa..71b28d336732 100644
--- a/CRM/Contact/DAO/Group.php
+++ b/CRM/Contact/DAO/Group.php
@@ -1,469 +1,504 @@
__table = 'civicrm_group';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'saved_search_id', 'civicrm_saved_search', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'modified_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'saved_search_id', 'civicrm_saved_search', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'modified_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group ID') ,
- 'description' => 'Group ID',
- 'required' => true,
+ 'title' => ts('Group ID'),
+ 'description' => ts('Group ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group.id',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Name') ,
- 'description' => 'Internal name of Group.',
+ 'title' => ts('Group Name'),
+ 'description' => ts('Internal name of Group.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_group.name',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'title' => array(
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Title') ,
- 'description' => 'Name of Group.',
+ 'title' => ts('Group Title'),
+ 'description' => ts('Name of Group.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_group.title',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 1,
- ) ,
- 'description' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Group Description') ,
- 'description' => 'Optional verbose description of the group.',
+ 'title' => ts('Group Description'),
+ 'description' => ts('Optional verbose description of the group.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_group.description',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'source' => array(
+ ],
+ ],
+ 'source' => [
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Source') ,
- 'description' => 'Module or process which created this group.',
+ 'title' => ts('Group Source'),
+ 'description' => ts('Module or process which created this group.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_group.source',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'saved_search_id' => array(
+ ],
+ 'saved_search_id' => [
'name' => 'saved_search_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Saved Search ID') ,
- 'description' => 'FK to saved search table.',
+ 'title' => ts('Saved Search ID'),
+ 'description' => ts('FK to saved search table.'),
+ 'where' => 'civicrm_group.saved_search_id',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_SavedSearch',
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Group Enabled') ,
- 'description' => 'Is this entry active?',
+ 'title' => ts('Group Enabled'),
+ 'description' => ts('Is this entry active?'),
+ 'where' => 'civicrm_group.is_active',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'visibility' => array(
+ ],
+ 'visibility' => [
'name' => 'visibility',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Visibility Setting') ,
- 'description' => 'In what context(s) is this field visible.',
+ 'title' => ts('Group Visibility Setting'),
+ 'description' => ts('In what context(s) is this field visible.'),
'maxlength' => 24,
'size' => CRM_Utils_Type::MEDIUM,
+ 'where' => 'civicrm_group.visibility',
'default' => 'User and User Admin Only',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::groupVisibility',
- )
- ) ,
- 'where_clause' => array(
+ ]
+ ],
+ 'where_clause' => [
'name' => 'where_clause',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Group Where Clause') ,
- 'description' => 'the sql where clause if a saved search acl',
+ 'title' => ts('Group Where Clause'),
+ 'description' => ts('the sql where clause if a saved search acl'),
+ 'where' => 'civicrm_group.where_clause',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'select_tables' => array(
+ ],
+ 'select_tables' => [
'name' => 'select_tables',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Tables For Select Clause') ,
- 'description' => 'the tables to be included in a select data',
+ 'title' => ts('Tables For Select Clause'),
+ 'description' => ts('the tables to be included in a select data'),
+ 'where' => 'civicrm_group.select_tables',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'where_tables' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'where_tables' => [
'name' => 'where_tables',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Tables For Where Clause') ,
- 'description' => 'the tables to be included in the count statement',
+ 'title' => ts('Tables For Where Clause'),
+ 'description' => ts('the tables to be included in the count statement'),
+ 'where' => 'civicrm_group.where_tables',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'group_type' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'group_type' => [
'name' => 'group_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Type') ,
- 'description' => 'FK to group type',
+ 'title' => ts('Group Type'),
+ 'description' => ts('FK to group type'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_group.group_type',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND,
+ 'pseudoconstant' => [
'optionGroupName' => 'group_type',
'optionEditPath' => 'civicrm/admin/options/group_type',
- )
- ) ,
- 'cache_date' => array(
+ ]
+ ],
+ 'cache_date' => [
'name' => 'cache_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Group Cache Date') ,
- 'description' => 'Date when we created the cache for a smart group',
- 'required' => false,
+ 'title' => ts('Group Cache Date'),
+ 'description' => ts('Date when we created the cache for a smart group'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_group.cache_date',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'refresh_date' => array(
+ ],
+ 'refresh_date' => [
'name' => 'refresh_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Next Group Refresh Time') ,
- 'description' => 'Date and time when we need to refresh the cache next.',
- 'required' => false,
+ 'title' => ts('Next Group Refresh Time'),
+ 'description' => ts('Date and time when we need to refresh the cache next.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_group.refresh_date',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'parents' => array(
+ ],
+ 'parents' => [
'name' => 'parents',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Group Parents') ,
- 'description' => 'IDs of the parent(s)',
+ 'title' => ts('Group Parents'),
+ 'description' => ts('IDs of the parent(s)'),
+ 'where' => 'civicrm_group.parents',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'children' => array(
+ 'serialize' => self::SERIALIZE_COMMA,
+ 'pseudoconstant' => [
+ 'callback' => 'CRM_Core_PseudoConstant::allGroup',
+ ]
+ ],
+ 'children' => [
'name' => 'children',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Group Children') ,
- 'description' => 'IDs of the child(ren)',
+ 'title' => ts('Group Children'),
+ 'description' => ts('IDs of the child(ren)'),
+ 'where' => 'civicrm_group.children',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'is_hidden' => array(
+ ],
+ 'is_hidden' => [
'name' => 'is_hidden',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Group is Hidden') ,
- 'description' => 'Is this group hidden?',
+ 'title' => ts('Group is Hidden'),
+ 'description' => ts('Is this group hidden?'),
+ 'where' => 'civicrm_group.is_hidden',
+ 'default' => '0',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Group is Reserved') ,
+ 'title' => ts('Group is Reserved'),
+ 'where' => 'civicrm_group.is_reserved',
+ 'default' => '0',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
- ) ,
- 'created_id' => array(
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Created By') ,
- 'description' => 'FK to contact table.',
+ 'title' => ts('Group Created By'),
+ 'description' => ts('FK to contact table.'),
+ 'where' => 'civicrm_group.created_id',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'modified_id' => array(
+ ],
+ 'modified_id' => [
'name' => 'modified_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Modified By') ,
- 'description' => 'FK to contact table.',
+ 'title' => ts('Group Modified By'),
+ 'description' => ts('FK to contact table.'),
+ 'where' => 'civicrm_group.modified_id',
'table_name' => 'civicrm_group',
'entity' => 'Group',
'bao' => 'CRM_Contact_BAO_Group',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -471,10 +506,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -482,42 +518,48 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_group_type' => array(
+ $indices = [
+ 'index_group_type' => [
'name' => 'index_group_type',
- 'field' => array(
+ 'field' => [
0 => 'group_type',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_group::0::group_type',
- ) ,
- 'UI_title' => array(
+ ],
+ 'UI_title' => [
'name' => 'UI_title',
- 'field' => array(
+ 'field' => [
0 => 'title',
- ) ,
- 'localizable' => true,
- 'unique' => true,
+ ],
+ 'localizable' => TRUE,
+ 'unique' => TRUE,
'sig' => 'civicrm_group::1::title',
- ) ,
- 'UI_name' => array(
+ ],
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_group::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/GroupContact.php b/CRM/Contact/DAO/GroupContact.php
index 380588a7d343..8980f8c8bf9d 100644
--- a/CRM/Contact/DAO/GroupContact.php
+++ b/CRM/Contact/DAO/GroupContact.php
@@ -1,239 +1,235 @@
__table = 'civicrm_group_contact';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'location_id', 'civicrm_loc_block', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'email_id', 'civicrm_email', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'location_id', 'civicrm_loc_block', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'email_id', 'civicrm_email', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Contact ID') ,
- 'description' => 'primary key',
- 'required' => true,
+ 'title' => ts('Group Contact ID'),
+ 'description' => ts('primary key'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_contact.id',
'table_name' => 'civicrm_group_contact',
'entity' => 'GroupContact',
'bao' => 'CRM_Contact_BAO_GroupContact',
'localizable' => 0,
- ) ,
- 'group_id' => array(
+ ],
+ 'group_id' => [
'name' => 'group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group ID') ,
- 'description' => 'FK to civicrm_group',
- 'required' => true,
+ 'title' => ts('Group ID'),
+ 'description' => ts('FK to civicrm_group'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_contact.group_id',
'table_name' => 'civicrm_group_contact',
'entity' => 'GroupContact',
'bao' => 'CRM_Contact_BAO_GroupContact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'contact_id' => array(
+ ]
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to civicrm_contact',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to civicrm_contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_contact.contact_id',
'table_name' => 'civicrm_group_contact',
'entity' => 'GroupContact',
'bao' => 'CRM_Contact_BAO_GroupContact',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'status' => array(
+ ],
+ 'status' => [
'name' => 'status',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Contact Status') ,
- 'description' => 'status of contact relative to membership in group',
+ 'title' => ts('Group Contact Status'),
+ 'description' => ts('status of contact relative to membership in group'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_group_contact.status',
'table_name' => 'civicrm_group_contact',
'entity' => 'GroupContact',
'bao' => 'CRM_Contact_BAO_GroupContact',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::groupContactStatus',
- )
- ) ,
- 'location_id' => array(
+ ]
+ ],
+ 'location_id' => [
'name' => 'location_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Contact Location') ,
- 'description' => 'Optional location to associate with this membership',
+ 'title' => ts('Group Contact Location'),
+ 'description' => ts('Optional location to associate with this membership'),
+ 'where' => 'civicrm_group_contact.location_id',
'table_name' => 'civicrm_group_contact',
'entity' => 'GroupContact',
'bao' => 'CRM_Contact_BAO_GroupContact',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_LocBlock',
- ) ,
- 'email_id' => array(
+ ],
+ 'email_id' => [
'name' => 'email_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Contact Email') ,
- 'description' => 'Optional email to associate with this membership',
+ 'title' => ts('Group Contact Email'),
+ 'description' => ts('Optional email to associate with this membership'),
+ 'where' => 'civicrm_group_contact.email_id',
'table_name' => 'civicrm_group_contact',
'entity' => 'GroupContact',
'bao' => 'CRM_Contact_BAO_GroupContact',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Email',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -241,10 +237,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -252,26 +249,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contact_group' => array(
+ $indices = [
+ 'UI_contact_group' => [
'name' => 'UI_contact_group',
- 'field' => array(
+ 'field' => [
0 => 'contact_id',
1 => 'group_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_group_contact::1::contact_id::group_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/GroupContactCache.php b/CRM/Contact/DAO/GroupContactCache.php
index d85be450bd62..0370dcc98c19 100644
--- a/CRM/Contact/DAO/GroupContactCache.php
+++ b/CRM/Contact/DAO/GroupContactCache.php
@@ -1,179 +1,169 @@
__table = 'civicrm_group_contact_cache';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Contact Cache ID') ,
- 'description' => 'primary key',
- 'required' => true,
+ 'title' => ts('Group Contact Cache ID'),
+ 'description' => ts('primary key'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_contact_cache.id',
'table_name' => 'civicrm_group_contact_cache',
'entity' => 'GroupContactCache',
'bao' => 'CRM_Contact_BAO_GroupContactCache',
'localizable' => 0,
- ) ,
- 'group_id' => array(
+ ],
+ 'group_id' => [
'name' => 'group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group') ,
- 'description' => 'FK to civicrm_group',
- 'required' => true,
+ 'title' => ts('Group'),
+ 'description' => ts('FK to civicrm_group'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_contact_cache.group_id',
'table_name' => 'civicrm_group_contact_cache',
'entity' => 'GroupContactCache',
'bao' => 'CRM_Contact_BAO_GroupContactCache',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'contact_id' => array(
+ ]
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to civicrm_contact',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to civicrm_contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_contact_cache.contact_id',
'table_name' => 'civicrm_group_contact_cache',
'entity' => 'GroupContactCache',
'bao' => 'CRM_Contact_BAO_GroupContactCache',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -181,10 +171,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact_cache', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_contact_cache', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -192,26 +183,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact_cache', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_contact_cache', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contact_group' => array(
+ $indices = [
+ 'UI_contact_group' => [
'name' => 'UI_contact_group',
- 'field' => array(
+ 'field' => [
0 => 'contact_id',
1 => 'group_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_group_contact_cache::1::contact_id::group_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/GroupNesting.php b/CRM/Contact/DAO/GroupNesting.php
index 255e80ac9963..e2d83582c81d 100644
--- a/CRM/Contact/DAO/GroupNesting.php
+++ b/CRM/Contact/DAO/GroupNesting.php
@@ -1,171 +1,161 @@
__table = 'civicrm_group_nesting';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'child_group_id', 'civicrm_group', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_group_id', 'civicrm_group', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'child_group_id', 'civicrm_group', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_group_id', 'civicrm_group', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Nesting ID') ,
- 'description' => 'Relationship ID',
- 'required' => true,
+ 'title' => ts('Group Nesting ID'),
+ 'description' => ts('Relationship ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_nesting.id',
'table_name' => 'civicrm_group_nesting',
'entity' => 'GroupNesting',
'bao' => 'CRM_Contact_BAO_GroupNesting',
'localizable' => 0,
- ) ,
- 'child_group_id' => array(
+ ],
+ 'child_group_id' => [
'name' => 'child_group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Child Group') ,
- 'description' => 'ID of the child group',
- 'required' => true,
+ 'title' => ts('Child Group'),
+ 'description' => ts('ID of the child group'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_nesting.child_group_id',
'table_name' => 'civicrm_group_nesting',
'entity' => 'GroupNesting',
'bao' => 'CRM_Contact_BAO_GroupNesting',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
- ) ,
- 'parent_group_id' => array(
+ ],
+ 'parent_group_id' => [
'name' => 'parent_group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Parent Group') ,
- 'description' => 'ID of the parent group',
- 'required' => true,
+ 'title' => ts('Parent Group'),
+ 'description' => ts('ID of the parent group'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_nesting.parent_group_id',
'table_name' => 'civicrm_group_nesting',
'entity' => 'GroupNesting',
'bao' => 'CRM_Contact_BAO_GroupNesting',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -173,10 +163,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_nesting', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_nesting', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -184,15 +175,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_nesting', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_nesting', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/GroupOrganization.php b/CRM/Contact/DAO/GroupOrganization.php
index 718a2bfda29c..b16db55d397c 100644
--- a/CRM/Contact/DAO/GroupOrganization.php
+++ b/CRM/Contact/DAO/GroupOrganization.php
@@ -1,179 +1,169 @@
__table = 'civicrm_group_organization';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'organization_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'organization_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Organization ID') ,
- 'description' => 'Relationship ID',
- 'required' => true,
+ 'title' => ts('Group Organization ID'),
+ 'description' => ts('Relationship ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_organization.id',
'table_name' => 'civicrm_group_organization',
'entity' => 'GroupOrganization',
'bao' => 'CRM_Contact_BAO_GroupOrganization',
'localizable' => 0,
- ) ,
- 'group_id' => array(
+ ],
+ 'group_id' => [
'name' => 'group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group') ,
- 'description' => 'ID of the group',
- 'required' => true,
+ 'title' => ts('Group'),
+ 'description' => ts('ID of the group'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_organization.group_id',
'table_name' => 'civicrm_group_organization',
'entity' => 'GroupOrganization',
'bao' => 'CRM_Contact_BAO_GroupOrganization',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'organization_id' => array(
+ ]
+ ],
+ 'organization_id' => [
'name' => 'organization_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Organization') ,
- 'description' => 'ID of the Organization Contact',
- 'required' => true,
+ 'title' => ts('Organization'),
+ 'description' => ts('ID of the Organization Contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_group_organization.organization_id',
'table_name' => 'civicrm_group_organization',
'entity' => 'GroupOrganization',
'bao' => 'CRM_Contact_BAO_GroupOrganization',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -181,10 +171,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_organization', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'group_organization', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -192,26 +183,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_organization', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'group_organization', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_group_organization' => array(
+ $indices = [
+ 'UI_group_organization' => [
'name' => 'UI_group_organization',
- 'field' => array(
+ 'field' => [
0 => 'group_id',
1 => 'organization_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_group_organization::1::group_id::organization_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/Relationship.php b/CRM/Contact/DAO/Relationship.php
index 5953567a02b1..f6dcce482c6e 100644
--- a/CRM/Contact/DAO/Relationship.php
+++ b/CRM/Contact/DAO/Relationship.php
@@ -1,338 +1,350 @@
__table = 'civicrm_relationship';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id_a', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id_b', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'relationship_type_id', 'civicrm_relationship_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'case_id', 'civicrm_case', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id_a', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id_b', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'relationship_type_id', 'civicrm_relationship_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'case_id', 'civicrm_case', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Relationship ID') ,
- 'description' => 'Relationship ID',
- 'required' => true,
+ 'title' => ts('Relationship ID'),
+ 'description' => ts('Relationship ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship.id',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- ) ,
- 'contact_id_a' => array(
+ ],
+ 'contact_id_a' => [
'name' => 'contact_id_a',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact A') ,
- 'description' => 'id of the first contact',
- 'required' => true,
+ 'title' => ts('Contact A'),
+ 'description' => ts('id of the first contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship.contact_id_a',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'contact_id_b' => array(
+ ],
+ 'contact_id_b' => [
'name' => 'contact_id_b',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact B') ,
- 'description' => 'id of the second contact',
- 'required' => true,
+ 'title' => ts('Contact B'),
+ 'description' => ts('id of the second contact'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship.contact_id_b',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'relationship_type_id' => array(
+ ],
+ ],
+ 'relationship_type_id' => [
'name' => 'relationship_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Relationship Type') ,
- 'description' => 'id of the relationship',
- 'required' => true,
+ 'title' => ts('Relationship Type'),
+ 'description' => ts('id of the relationship'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship.relationship_type_id',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_RelationshipType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'start_date' => array(
+ ],
+ ],
+ 'start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Relationship Start Date') ,
- 'description' => 'date when the relationship started',
+ 'title' => ts('Relationship Start Date'),
+ 'description' => ts('date when the relationship started'),
+ 'where' => 'civicrm_relationship.start_date',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'end_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Relationship End Date') ,
- 'description' => 'date when the relationship ended',
+ 'title' => ts('Relationship End Date'),
+ 'description' => ts('date when the relationship ended'),
+ 'where' => 'civicrm_relationship.end_date',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'is_active' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Relationship Is Active') ,
- 'description' => 'is the relationship active ?',
+ 'title' => ts('Relationship Is Active'),
+ 'description' => ts('is the relationship active ?'),
+ 'where' => 'civicrm_relationship.is_active',
'default' => '1',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'description' => array(
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Description') ,
- 'description' => 'Optional verbose description for the relationship.',
+ 'title' => ts('Relationship Description'),
+ 'description' => ts('Optional verbose description for the relationship.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_relationship.description',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_permission_a_b' => array(
+ ],
+ ],
+ 'is_permission_a_b' => [
'name' => 'is_permission_a_b',
- 'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Contact A has Permission Over Contact B') ,
- 'description' => 'is contact a has permission to view / edit contact and
- related data for contact b ?
- ',
+ 'type' => CRM_Utils_Type::T_INT,
+ 'title' => ts('Contact A has Permission Over Contact B'),
+ 'description' => ts('Permission that Contact A has to view/update Contact B'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship.is_permission_a_b',
+ 'default' => '0',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- 'html' => array(
- 'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_permission_b_a' => array(
+ 'html' => [
+ 'type' => 'Radio',
+ ],
+ 'pseudoconstant' => [
+ 'callback' => 'CRM_Core_SelectValues::getPermissionedRelationshipOptions',
+ ]
+ ],
+ 'is_permission_b_a' => [
'name' => 'is_permission_b_a',
- 'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Contact B has Permission Over Contact A') ,
- 'description' => 'is contact b has permission to view / edit contact and
- related data for contact a ?
- ',
+ 'type' => CRM_Utils_Type::T_INT,
+ 'title' => ts('Contact B has Permission Over Contact A'),
+ 'description' => ts('Permission that Contact B has to view/update Contact A'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship.is_permission_b_a',
+ 'default' => '0',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
- 'html' => array(
- 'type' => 'CheckBox',
- ) ,
- ) ,
- 'case_id' => array(
+ 'html' => [
+ 'type' => 'Radio',
+ ],
+ 'pseudoconstant' => [
+ 'callback' => 'CRM_Core_SelectValues::getPermissionedRelationshipOptions',
+ ]
+ ],
+ 'case_id' => [
'name' => 'case_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Relationship Case') ,
- 'description' => 'FK to civicrm_case',
+ 'title' => ts('Relationship Case'),
+ 'description' => ts('FK to civicrm_case'),
+ 'where' => 'civicrm_relationship.case_id',
'default' => 'NULL',
'table_name' => 'civicrm_relationship',
'entity' => 'Relationship',
'bao' => 'CRM_Contact_BAO_Relationship',
'localizable' => 0,
'FKClassName' => 'CRM_Case_DAO_Case',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -340,10 +352,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -351,15 +364,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/RelationshipType.php b/CRM/Contact/DAO/RelationshipType.php
index 16e0125fe122..7a3a77e310bf 100644
--- a/CRM/Contact/DAO/RelationshipType.php
+++ b/CRM/Contact/DAO/RelationshipType.php
@@ -1,354 +1,376 @@
__table = 'civicrm_relationship_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Relationship Type ID') ,
- 'description' => 'Primary key',
- 'required' => true,
+ 'title' => ts('Relationship Type ID'),
+ 'description' => ts('Primary key'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_relationship_type.id',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- ) ,
- 'name_a_b' => array(
+ ],
+ 'name_a_b' => [
'name' => 'name_a_b',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Type Name A to B') ,
- 'description' => 'name for relationship of contact_a to contact_b.',
+ 'title' => ts('Relationship Type Name A to B'),
+ 'description' => ts('name for relationship of contact_a to contact_b.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_relationship_type.name_a_b',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- ) ,
- 'label_a_b' => array(
+ ],
+ 'label_a_b' => [
'name' => 'label_a_b',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Type Label A to B') ,
- 'description' => 'label for relationship of contact_a to contact_b.',
+ 'title' => ts('Relationship Type Label A to B'),
+ 'description' => ts('label for relationship of contact_a to contact_b.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_relationship_type.label_a_b',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 1,
- ) ,
- 'name_b_a' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'name_b_a' => [
'name' => 'name_b_a',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Type Name B to A') ,
- 'description' => 'Optional name for relationship of contact_b to contact_a.',
+ 'title' => ts('Relationship Type Name B to A'),
+ 'description' => ts('Optional name for relationship of contact_b to contact_a.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_relationship_type.name_b_a',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- ) ,
- 'label_b_a' => array(
+ ],
+ 'label_b_a' => [
'name' => 'label_b_a',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Type Label B to A') ,
- 'description' => 'Optional label for relationship of contact_b to contact_a.',
+ 'title' => ts('Relationship Type Label B to A'),
+ 'description' => ts('Optional label for relationship of contact_b to contact_a.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_relationship_type.label_b_a',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 1,
- ) ,
- 'description' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Description') ,
- 'description' => 'Optional verbose description of the relationship type.',
+ 'title' => ts('Relationship Description'),
+ 'description' => ts('Optional verbose description of the relationship type.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_relationship_type.description',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 1,
- ) ,
- 'contact_type_a' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'contact_type_a' => [
'name' => 'contact_type_a',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Type for Contact A') ,
- 'description' => 'If defined, contact_a in a relationship of this type must be a specific contact_type.',
+ 'title' => ts('Contact Type for Contact A'),
+ 'description' => ts('If defined, contact_a in a relationship of this type must be a specific contact_type.'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_relationship_type.contact_type_a',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NULL',
- )
- ) ,
- 'contact_type_b' => array(
+ ]
+ ],
+ 'contact_type_b' => [
'name' => 'contact_type_b',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Type for Contact B') ,
- 'description' => 'If defined, contact_b in a relationship of this type must be a specific contact_type.',
+ 'title' => ts('Contact Type for Contact B'),
+ 'description' => ts('If defined, contact_b in a relationship of this type must be a specific contact_type.'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_relationship_type.contact_type_b',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NULL',
- )
- ) ,
- 'contact_sub_type_a' => array(
+ ]
+ ],
+ 'contact_sub_type_a' => [
'name' => 'contact_sub_type_a',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Subtype A') ,
- 'description' => 'If defined, contact_sub_type_a in a relationship of this type must be a specific contact_sub_type.
- ',
+ 'title' => ts('Contact Subtype A'),
+ 'description' => ts('If defined, contact_sub_type_a in a relationship of this type must be a specific contact_sub_type.
+ '),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_relationship_type.contact_sub_type_a',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NOT NULL',
- )
- ) ,
- 'contact_sub_type_b' => array(
+ ]
+ ],
+ 'contact_sub_type_b' => [
'name' => 'contact_sub_type_b',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Subtype B') ,
- 'description' => 'If defined, contact_sub_type_b in a relationship of this type must be a specific contact_sub_type.
- ',
+ 'title' => ts('Contact Subtype B'),
+ 'description' => ts('If defined, contact_sub_type_b in a relationship of this type must be a specific contact_sub_type.
+ '),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_relationship_type.contact_sub_type_b',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NOT NULL',
- )
- ) ,
- 'is_reserved' => array(
+ ]
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Relationship Type is Reserved') ,
- 'description' => 'Is this relationship type a predefined system type (can not be changed or de-activated)?',
+ 'title' => ts('Relationship Type is Reserved'),
+ 'description' => ts('Is this relationship type a predefined system type (can not be changed or de-activated)?'),
+ 'where' => 'civicrm_relationship_type.is_reserved',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Relationship Type is Active') ,
- 'description' => 'Is this relationship type currently active (i.e. can be used when creating or editing relationships)?
- ',
+ 'title' => ts('Relationship Type is Active'),
+ 'description' => ts('Is this relationship type currently active (i.e. can be used when creating or editing relationships)?
+ '),
+ 'where' => 'civicrm_relationship_type.is_active',
'default' => '1',
'table_name' => 'civicrm_relationship_type',
'entity' => 'RelationshipType',
'bao' => 'CRM_Contact_BAO_RelationshipType',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -356,10 +378,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'relationship_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -367,34 +390,40 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'relationship_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name_a_b' => array(
+ $indices = [
+ 'UI_name_a_b' => [
'name' => 'UI_name_a_b',
- 'field' => array(
+ 'field' => [
0 => 'name_a_b',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_relationship_type::1::name_a_b',
- ) ,
- 'UI_name_b_a' => array(
+ ],
+ 'UI_name_b_a' => [
'name' => 'UI_name_b_a',
- 'field' => array(
+ 'field' => [
0 => 'name_b_a',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_relationship_type::1::name_b_a',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/SavedSearch.php b/CRM/Contact/DAO/SavedSearch.php
index f6d87c8da145..b7fd62c31a36 100644
--- a/CRM/Contact/DAO/SavedSearch.php
+++ b/CRM/Contact/DAO/SavedSearch.php
@@ -1,236 +1,234 @@
__table = 'civicrm_saved_search';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'mapping_id', 'civicrm_mapping', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'mapping_id', 'civicrm_mapping', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Saved Search ID') ,
- 'description' => 'Saved Search ID',
- 'required' => true,
+ 'title' => ts('Saved Search ID'),
+ 'description' => ts('Saved Search ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_saved_search.id',
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
- ) ,
- 'form_values' => array(
+ ],
+ 'form_values' => [
'name' => 'form_values',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Submitted Form Values') ,
- 'description' => 'Submitted form values for this search',
- 'import' => true,
+ 'title' => ts('Submitted Form Values'),
+ 'description' => ts('Submitted form values for this search'),
+ 'import' => TRUE,
'where' => 'civicrm_saved_search.form_values',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
- ) ,
- 'mapping_id' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'mapping_id' => [
'name' => 'mapping_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Mapping ID') ,
- 'description' => 'Foreign key to civicrm_mapping used for saved search-builder searches.',
+ 'title' => ts('Mapping ID'),
+ 'description' => ts('Foreign key to civicrm_mapping used for saved search-builder searches.'),
+ 'where' => 'civicrm_saved_search.mapping_id',
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Mapping',
- ) ,
- 'search_custom_id' => array(
+ ],
+ 'search_custom_id' => [
'name' => 'search_custom_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Option Value ID') ,
- 'description' => 'Foreign key to civicrm_option value table used for saved custom searches.',
+ 'title' => ts('Option Value ID'),
+ 'description' => ts('Foreign key to civicrm_option value table used for saved custom searches.'),
+ 'where' => 'civicrm_saved_search.search_custom_id',
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
- ) ,
- 'where_clause' => array(
+ ],
+ 'where_clause' => [
'name' => 'where_clause',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Where Clause') ,
- 'description' => 'the sql where clause if a saved search acl',
+ 'title' => ts('Where Clause'),
+ 'description' => ts('the sql where clause if a saved search acl'),
+ 'where' => 'civicrm_saved_search.where_clause',
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
- ) ,
- 'select_tables' => array(
+ ],
+ 'select_tables' => [
'name' => 'select_tables',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Select Tables') ,
- 'description' => 'the tables to be included in a select data',
+ 'title' => ts('Select Tables'),
+ 'description' => ts('the tables to be included in a select data'),
+ 'where' => 'civicrm_saved_search.select_tables',
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
- ) ,
- 'where_tables' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'where_tables' => [
'name' => 'where_tables',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Where Tables') ,
- 'description' => 'the tables to be included in the count statement',
+ 'title' => ts('Where Tables'),
+ 'description' => ts('the tables to be included in the count statement'),
+ 'where' => 'civicrm_saved_search.where_tables',
'table_name' => 'civicrm_saved_search',
'entity' => 'SavedSearch',
'bao' => 'CRM_Contact_BAO_SavedSearch',
'localizable' => 0,
- ) ,
- );
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -238,10 +236,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'saved_search', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'saved_search', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -249,15 +248,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'saved_search', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'saved_search', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/DAO/SubscriptionHistory.php b/CRM/Contact/DAO/SubscriptionHistory.php
index 0890772cca58..1df68f7f3356 100644
--- a/CRM/Contact/DAO/SubscriptionHistory.php
+++ b/CRM/Contact/DAO/SubscriptionHistory.php
@@ -1,259 +1,257 @@
__table = 'civicrm_subscription_history';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'group_id', 'civicrm_group', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'group_id', 'civicrm_group', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group Membership History ID') ,
- 'description' => 'Internal Id',
- 'required' => true,
+ 'title' => ts('Group Membership History ID'),
+ 'description' => ts('Internal Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_subscription_history.id',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'Contact Id',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('Contact Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_subscription_history.contact_id',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'group_id' => array(
+ ],
+ 'group_id' => [
'name' => 'group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Group') ,
- 'description' => 'Group Id',
+ 'title' => ts('Group'),
+ 'description' => ts('Group Id'),
+ 'where' => 'civicrm_subscription_history.group_id',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Group',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'date' => array(
+ ]
+ ],
+ 'date' => [
'name' => 'date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Group Membership Action Date') ,
- 'description' => 'Date of the (un)subscription',
- 'required' => true,
+ 'title' => ts('Group Membership Action Date'),
+ 'description' => ts('Date of the (un)subscription'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_subscription_history.date',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
- ) ,
- 'method' => array(
+ ],
+ 'method' => [
'name' => 'method',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Membership Action') ,
- 'description' => 'How the (un)subscription was triggered',
+ 'title' => ts('Group Membership Action'),
+ 'description' => ts('How the (un)subscription was triggered'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_subscription_history.method',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::getSubscriptionHistoryMethods',
- )
- ) ,
- 'status' => array(
+ ]
+ ],
+ 'status' => [
'name' => 'status',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Membership Status') ,
- 'description' => 'The state of the contact within the group',
+ 'title' => ts('Group Membership Status'),
+ 'description' => ts('The state of the contact within the group'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_subscription_history.status',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::groupContactStatus',
- )
- ) ,
- 'tracking' => array(
+ ]
+ ],
+ 'tracking' => [
'name' => 'tracking',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Group Membership Tracking') ,
- 'description' => 'IP address or other tracking info',
+ 'title' => ts('Group Membership Tracking'),
+ 'description' => ts('IP address or other tracking info'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_subscription_history.tracking',
'table_name' => 'civicrm_subscription_history',
'entity' => 'SubscriptionHistory',
'bao' => 'CRM_Contact_BAO_SubscriptionHistory',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -261,10 +259,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'subscription_history', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'subscription_history', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -272,15 +271,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'subscription_history', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'subscription_history', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Contact/Form/Contact.php b/CRM/Contact/Form/Contact.php
index 2a14de16e94e..f275cfa377f4 100644
--- a/CRM/Contact/Form/Contact.php
+++ b/CRM/Contact/Form/Contact.php
@@ -1,9 +1,9 @@
_contactType,
- array('Individual', 'Household', 'Organization')
+ ['Individual', 'Household', 'Organization']
)
) {
CRM_Core_Error::statusBounce(ts('Could not get a contact id and/or contact type'));
@@ -177,7 +180,7 @@ public function preProcess() {
$this->_contactSubType &&
!(CRM_Contact_BAO_ContactType::isExtendsContactType($this->_contactSubType, $this->_contactType, TRUE))
) {
- CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", array(1 => $this->_contactType)));
+ CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", [1 => $this->_contactType]));
}
$this->_gid = CRM_Utils_Request::retrieve('gid', 'Integer',
@@ -193,7 +196,7 @@ public function preProcess() {
);
$typeLabel = implode(' / ', $typeLabel);
- CRM_Utils_System::setTitle(ts('New %1', array(1 => $typeLabel)));
+ CRM_Utils_System::setTitle(ts('New %1', [1 => $typeLabel]));
$session->pushUserContext(CRM_Utils_System::url('civicrm/dashboard', 'reset=1'));
$this->_contactId = NULL;
}
@@ -204,13 +207,13 @@ public function preProcess() {
}
if ($this->_contactId) {
- $defaults = array();
- $params = array('id' => $this->_contactId);
- $returnProperities = array('id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased');
+ $defaults = [];
+ $params = ['id' => $this->_contactId];
+ $returnProperities = ['id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased'];
CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
if (empty($defaults['id'])) {
- CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', array(1 => $this->_contactId)));
+ CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', [1 => $this->_contactId]));
}
$this->_contactType = CRM_Utils_Array::value('contact_type', $defaults);
@@ -226,7 +229,7 @@ public function preProcess() {
if ($defaults['is_deceased']) {
$displayName .= ' (deceased)';
}
- $displayName = ts('Edit %1', array(1 => $displayName));
+ $displayName = ts('Edit %1', [1 => $displayName]);
// Check if this is default domain contact CRM-10482
if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactId)) {
@@ -235,7 +238,7 @@ public function preProcess() {
// omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
CRM_Utils_System::setTitle($displayName);
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
$urlParams = 'reset=1&cid=' . $this->_contactId;
@@ -256,13 +259,13 @@ public function preProcess() {
$this->_values = $values;
}
else {
- $params = array(
+ $params = [
'id' => $this->_contactId,
'contact_id' => $this->_contactId,
'noRelationships' => TRUE,
'noNotes' => TRUE,
'noGroups' => TRUE,
- );
+ ];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_values, TRUE);
$this->set('values', $this->_values);
@@ -430,7 +433,7 @@ public function setDefaultValues() {
}
// set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
foreach ($this->_editOptions as $name => $label) {
- if (!in_array($name, array('Address', 'Notes'))) {
+ if (!in_array($name, ['Address', 'Notes'])) {
$className = 'CRM_Contact_Form_Edit_' . $name;
$className::setDefaultValues($this, $defaults);
}
@@ -561,19 +564,19 @@ public function addRules() {
return;
}
- $this->addFormRule(array('CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'), $this->_contactId);
+ $this->addFormRule(['CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'], $this->_contactId);
// Call Locking check if editing existing contact
if ($this->_contactId) {
- $this->addFormRule(array('CRM_Contact_Form_Edit_Lock', 'formRule'), $this->_contactId);
+ $this->addFormRule(['CRM_Contact_Form_Edit_Lock', 'formRule'], $this->_contactId);
}
if (array_key_exists('Address', $this->_editOptions)) {
- $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this);
}
if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
- $this->addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this);
}
}
@@ -586,11 +589,12 @@ public function addRules() {
* List of errors to be posted back to the form.
* @param int $contactId
* Contact id if doing update.
+ * @param string $contactType
*
* @return bool
* email/openId
*/
- public static function formRule($fields, &$errors, $contactId = NULL) {
+ public static function formRule($fields, &$errors, $contactId, $contactType) {
$config = CRM_Core_Config::singleton();
// validations.
@@ -615,10 +619,11 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
$blocks['Address'] = $otherEditOptions['Address'];
}
- $openIds = array();
+ $website_types = [];
+ $openIds = [];
$primaryID = FALSE;
foreach ($blocks as $name => $label) {
- $hasData = $hasPrimary = array();
+ $hasData = $hasPrimary = [];
$name = strtolower($name);
if (!empty($fields[$name]) && is_array($fields[$name])) {
foreach ($fields[$name] as $instance => $blockValues) {
@@ -629,8 +634,17 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
}
if ($dataExists) {
- // skip remaining checks for website
if ($name == 'website') {
+ if (!empty($blockValues['website_type_id'])) {
+ if (empty($website_types[$blockValues['website_type_id']])) {
+ $website_types[$blockValues['website_type_id']] = $blockValues['website_type_id'];
+ }
+ else {
+ $errors["{$name}[1][website_type_id]"] = ts('Contacts may only have one website of each type at most.');
+ }
+ }
+
+ // skip remaining checks for website
continue;
}
@@ -638,17 +652,17 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
if (!empty($blockValues['is_primary'])) {
$hasPrimary[] = $instance;
if (!$primaryID &&
- in_array($name, array(
+ in_array($name, [
'email',
'openid',
- )) && !empty($blockValues[$name])
+ ]) && !empty($blockValues[$name])
) {
$primaryID = $blockValues[$name];
}
}
if (empty($blockValues['location_type_id'])) {
- $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', array(1 => $label));
+ $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', [1 => $label]);
}
}
@@ -657,18 +671,18 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
$oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues);
$cid = isset($contactId) ? $contactId : 0;
if ($oid->find(TRUE) && ($oid->contact_id != $cid)) {
- $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', array(1 => $blocks['OpenID']));
+ $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', [1 => $blocks['OpenID']]);
}
}
}
if (empty($hasPrimary) && !empty($hasData)) {
- $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', array(1 => $label));
+ $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', [1 => $label]);
}
if (count($hasPrimary) > 1) {
$errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
- array(1 => $label)
+ [1 => $label]
);
}
}
@@ -678,7 +692,7 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
foreach ($openIds as $instance => $value) {
if (!array_key_exists($instance, array_unique($openIds))) {
- $errors["openid[$instance][openid]"] = ts('%1 already used.', array(1 => $blocks['OpenID']));
+ $errors["openid[$instance][openid]"] = ts('%1 already used.', [1 => $blocks['OpenID']]);
}
}
}
@@ -693,7 +707,7 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
if (isset($fields['address']) &&
is_array($fields['address'])
) {
- $invalidStreetNumbers = array();
+ $invalidStreetNumbers = [];
foreach ($fields['address'] as $cnt => $address) {
if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) {
$parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']);
@@ -708,11 +722,16 @@ public static function formRule($fields, &$errors, $contactId = NULL) {
foreach ($invalidStreetNumbers as & $num) {
$num = CRM_Contact_Form_Contact::ordinalNumber($num);
}
- $errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', array(1 => implode(', ', $invalidStreetNumbers)));
+ $errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', [1 => implode(', ', $invalidStreetNumbers)]);
}
}
}
+ // Check for duplicate contact if it wasn't already handled by ajax or disabled
+ if (!Civi::settings()->get('contact_ajax_check_similar') || !empty($fields['_qf_Contact_refresh_dedupe'])) {
+ self::checkDuplicateContacts($fields, $errors, $contactId, $contactType);
+ }
+
return $primaryID;
}
@@ -728,19 +747,19 @@ public function buildQuickForm() {
if ($this->_action == CRM_Core_Action::UPDATE) {
$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&cid=%%id%%&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' => $this->_contactId,
- ),
+ ],
ts('more'),
FALSE,
'contact.image.delete',
@@ -754,6 +773,14 @@ public function buildQuickForm() {
$className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
$className::buildQuickForm($this);
+ // Ajax duplicate checking
+ $checkSimilar = Civi::settings()->get('contact_ajax_check_similar');
+ $this->assign('checkSimilar', $checkSimilar);
+ if ($checkSimilar == 1) {
+ $ruleParams = ['used' => 'Supervised', 'contact_type' => $this->_contactType];
+ $this->assign('ruleFields', CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams));
+ }
+
// build Custom data if Custom data present in edit option
$buildCustomData = 'noCustomDataPresent';
if (array_key_exists('CustomData', $this->_editOptions)) {
@@ -761,15 +788,15 @@ public function buildQuickForm() {
}
// subtype is a common field. lets keep it here
- $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', array('contact_type' => $this->_contactType));
+ $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', ['contact_type' => $this->_contactType]);
if (!empty($subtypes)) {
- $this->addField('contact_sub_type', array(
+ $this->addField('contact_sub_type', [
'label' => ts('Contact Type'),
'options' => $subtypes,
'class' => $buildCustomData,
'multiple' => 'multiple',
'option_url' => NULL,
- ));
+ ]);
}
// build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
@@ -794,7 +821,7 @@ public function buildQuickForm() {
CRM_Contact_Form_Location::buildQuickForm($this);
// add attachment
- $this->addField('image_URL', array('maxlength' => '255', 'label' => ts('Browse/Upload Image')));
+ $this->addField('image_URL', ['maxlength' => '255', 'label' => ts('Browse/Upload Image')]);
// add the dedupe button
$this->addElement('submit',
@@ -810,26 +837,26 @@ public function buildQuickForm() {
ts('Save With Duplicate Household')
);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'upload',
'name' => ts('Save'),
'subName' => 'view',
'isDefault' => TRUE,
- ),
- );
+ ],
+ ];
if (CRM_Core_Permission::check('add contacts')) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save and New'),
'spacing' => ' ',
'subName' => 'new',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
if (!empty($this->_values['contact_sub_type'])) {
$this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
@@ -866,8 +893,6 @@ public function postProcess() {
}
}
- CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues);
-
if (!empty($params['image_URL'])) {
CRM_Contact_BAO_Contact::processImageParams($params);
}
@@ -885,7 +910,7 @@ public function postProcess() {
$params['contact_type'] = $this->_contactType;
if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
- $params['contact_sub_type'] = array($this->_contactSubType);
+ $params['contact_sub_type'] = [$this->_contactSubType];
}
if ($this->_contactId) {
@@ -900,11 +925,11 @@ public function postProcess() {
if (isset($params['contact_id'])) {
// process membership status for deceased contact
- $deceasedParams = array(
+ $deceasedParams = [
'contact_id' => CRM_Utils_Array::value('contact_id', $params),
'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE),
'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL),
- );
+ ];
$updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
}
@@ -916,8 +941,6 @@ public function postProcess() {
CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
}
- $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE);
-
//CRM-5143
//if subtype is set, send subtype as extend to validate subtype customfield
$customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type'];
@@ -943,11 +966,10 @@ public function postProcess() {
// process shared contact address.
CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
- if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) {
+ if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
unset($params['group']);
}
-
- if (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE) && !empty($params['group'])) {
+ elseif (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE)) {
// figure out which all groups are intended to be removed
$contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
if (is_array($contactGroupList)) {
@@ -966,7 +988,7 @@ public function postProcess() {
$parseStatusMsg = self::parseAddressStatusMsg($parseResult);
}
- $blocks = array('email', 'phone', 'im', 'openid', 'address', 'website');
+ $blocks = ['email', 'phone', 'im', 'openid', 'address', 'website'];
foreach ($blocks as $block) {
if (!empty($this->_preEditValues[$block]) && is_array($this->_preEditValues[$block])) {
foreach ($this->_preEditValues[$block] as $count => $value) {
@@ -985,10 +1007,10 @@ public function postProcess() {
// status message
if ($this->_contactId) {
- $message = ts('%1 has been updated.', array(1 => $contact->display_name));
+ $message = ts('%1 has been updated.', [1 => $contact->display_name]);
}
else {
- $message = ts('%1 has been created.', array(1 => $contact->display_name));
+ $message = ts('%1 has been created.', [1 => $contact->display_name]);
}
// set the contact ID
@@ -996,11 +1018,10 @@ public function postProcess() {
if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
//add contact to tags
- if (isset($params['tag']) && !empty($params['tag'])) {
+ if (isset($params['tag'])) {
$params['tag'] = array_flip(explode(',', $params['tag']));
CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
}
-
//save free tags
if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
@@ -1018,7 +1039,7 @@ public function postProcess() {
$session->setStatus($message, ts('Contact Saved'), 'success');
// add the recently viewed contact
- $recentOther = array();
+ $recentOther = [];
if (($session->get('userID') == $contact->id) ||
CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)
) {
@@ -1047,7 +1068,7 @@ public function postProcess() {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
}
else {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
//validate the qfKey
$urlParams = 'reset=1&cid=' . $contact->id;
@@ -1084,7 +1105,7 @@ public static function blockDataExists(&$fields) {
return FALSE;
}
- static $skipFields = array(
+ static $skipFields = [
'location_type_id',
'is_primary',
'phone_type_id',
@@ -1092,7 +1113,7 @@ public static function blockDataExists(&$fields) {
'country_id',
'website_type_id',
'master_id',
- );
+ ];
foreach ($fields as $name => $value) {
$skipField = FALSE;
foreach ($skipFields as $skip) {
@@ -1137,27 +1158,27 @@ public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $c
// if this is a forced save, ignore find duplicate rule
if (empty($fields['_qf_Contact_upload_duplicate'])) {
- $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($fields, $contactType, 'Supervised', array($contactID));
+ $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($fields, $contactType, 'Supervised', [$contactID]);
if ($ids) {
$contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
$duplicateContactsLinks = '
';
- $duplicateContactsLinks .= ts('One matching contact was found. ', array(
- 'count' => count($contactLinks['rows']),
- 'plural' => '%count matching contacts were found. ',
- ));
+ $duplicateContactsLinks .= ts('One matching contact was found. ', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => '%count matching contacts were found. ',
+ ]);
if ($contactLinks['msg'] == 'view') {
- $duplicateContactsLinks .= ts('You can View the existing contact', array(
- 'count' => count($contactLinks['rows']),
- 'plural' => 'You can View the existing contacts',
- ));
+ $duplicateContactsLinks .= ts('You can View the existing contact', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => 'You can View the existing contacts',
+ ]);
}
else {
- $duplicateContactsLinks .= ts('You can View or Edit the existing contact', array(
- 'count' => count($contactLinks['rows']),
- 'plural' => 'You can View or Edit the existing contacts',
- ));
+ $duplicateContactsLinks .= ts('You can View or Edit the existing contact', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => 'You can View or Edit the existing contacts',
+ ]);
}
if ($contactLinks['msg'] == 'merge') {
// We should also get a merge link if this is for an existing contact
@@ -1228,7 +1249,7 @@ public function getTemplateFileName() {
* as array of success/fails for each address block
*/
public function parseAddress(&$params) {
- $parseSuccess = $parsedFields = array();
+ $parseSuccess = $parsedFields = [];
if (!is_array($params['address']) ||
CRM_Utils_System::isNull($params['address'])
) {
@@ -1238,11 +1259,11 @@ public function parseAddress(&$params) {
foreach ($params['address'] as $instance => & $address) {
$buildStreetAddress = FALSE;
$parseFieldName = 'street_address';
- foreach (array(
- 'street_number',
- 'street_name',
- 'street_unit',
- ) as $fld) {
+ foreach ([
+ 'street_number',
+ 'street_name',
+ 'street_unit',
+ ] as $fld) {
if (!empty($address[$fld])) {
$parseFieldName = 'street_number';
$buildStreetAddress = TRUE;
@@ -1270,16 +1291,16 @@ public function parseAddress(&$params) {
$address['street_number'] = $parsedFields['street_number'];
$streetAddress = NULL;
- foreach (array(
- 'street_number',
- 'street_number_suffix',
- 'street_name',
- 'street_unit',
- ) as $fld) {
- if (in_array($fld, array(
+ foreach ([
+ 'street_number',
+ 'street_number_suffix',
+ 'street_name',
+ 'street_unit',
+ ] as $fld) {
+ if (in_array($fld, [
'street_name',
'street_unit',
- ))) {
+ ])) {
$streetAddress .= ' ';
}
// CRM-17619 - if the street number suffix begins with a number, add a space
@@ -1336,7 +1357,7 @@ public static function parseAddressStatusMsg($parseResult) {
return $statusMsg;
}
- $parseFails = array();
+ $parseFails = [];
foreach ($parseResult as $instance => $success) {
if (!$success) {
$parseFails[] = self::ordinalNumber($instance);
@@ -1345,7 +1366,7 @@ public static function parseAddressStatusMsg($parseResult) {
if (!empty($parseFails)) {
$statusMsg = ts("Complete street address(es) have been saved. However we were unable to split the address in the %1 address block(s) into address elements (street number, street name, street unit) due to an unrecognized address format. You can set the address elements manually by clicking 'Edit Address Elements' next to the Street Address field while in edit mode.",
- array(1 => implode(', ', $parseFails))
+ [1 => implode(', ', $parseFails)]
);
}
@@ -1442,7 +1463,7 @@ public function updateMembershipStatus($deceasedParams) {
);
// add membership log
- $membershipLog = array(
+ $membershipLog = [
'membership_id' => $dao->id,
'status_id' => $deceasedStatusId,
'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
@@ -1451,12 +1472,12 @@ public function updateMembershipStatus($deceasedParams) {
'modified_date' => date('Ymd'),
'membership_type_id' => $dao->membership_type_id,
'max_related' => $dao->max_related,
- );
+ ];
- CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
+ CRM_Member_BAO_MembershipLog::add($membershipLog);
//create activity when membership status is changed
- $activityParam = array(
+ $activityParam = [
'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
'source_contact_id' => $userId,
'target_contact_id' => $dao->contact_id,
@@ -1469,7 +1490,7 @@ public function updateMembershipStatus($deceasedParams) {
'is_auto' => 0,
'is_current_revision' => 1,
'is_deleted' => 0,
- );
+ ];
$activityResult = civicrm_api('activity', 'create', $activityParam);
$memCount++;
@@ -1478,7 +1499,7 @@ public function updateMembershipStatus($deceasedParams) {
// set status msg
if ($memCount) {
$updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
- array(1 => $memCount)
+ [1 => $memCount]
);
}
}
diff --git a/CRM/Contact/Form/CustomData.php b/CRM/Contact/Form/CustomData.php
index fa4bf98db578..ddd06219bb0f 100644
--- a/CRM/Contact/Form/CustomData.php
+++ b/CRM/Contact/Form/CustomData.php
@@ -1,9 +1,9 @@
_groupID);
$mode = CRM_Utils_Request::retrieve('mode', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET');
$mode = ucfirst($mode);
- CRM_Utils_System::setTitle(ts('%1 %2 Record', array(1 => $mode, 2 => $groupTitle)));
+ CRM_Utils_System::setTitle(ts('%1 %2 Record', [1 => $mode, 2 => $groupTitle]));
if (!empty($_POST['hidden_custom'])) {
$this->assign('postedInfo', TRUE);
@@ -177,23 +177,22 @@ public function buildQuickForm() {
if ($isMultiple) {
$this->assign('multiRecordDisplay', $this->_multiRecordDisplay);
$saveButtonName = $this->_copyValueId ? ts('Save a Copy') : ts('Save');
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => $saveButtonName,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'upload',
- 'name' => ts('Save and New'),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => $saveButtonName,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save and New'),
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
return CRM_Custom_Form_CustomData::buildQuickForm($this);
@@ -205,18 +204,17 @@ public function buildQuickForm() {
// make this form an upload since we dont know if the custom data injected dynamically
// is of type file etc
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -234,7 +232,7 @@ public function setDefaultValues() {
NULL,
$this->_entityId,
$this->_groupID,
- array(),
+ [],
NULL,
TRUE,
NULL,
@@ -242,7 +240,7 @@ public function setDefaultValues() {
TRUE,
$this->_copyValueId
);
- $valueIdDefaults = array();
+ $valueIdDefaults = [];
$groupTreeValueId = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, $this->_copyValueId, $this);
CRM_Core_BAO_CustomGroup::setDefaults($groupTreeValueId, $valueIdDefaults, FALSE, FALSE, $this->get('action'));
$tableId = $groupTreeValueId[$this->_groupID]['table_id'];
@@ -280,7 +278,7 @@ public function setDefaultValues() {
$this->assign('customValueCount', $customValueCount);
- $defaults = array();
+ $defaults = [];
return $defaults;
}
diff --git a/CRM/Contact/Form/DedupeFind.php b/CRM/Contact/Form/DedupeFind.php
index 155862b7a794..7f9ebaec2466 100644
--- a/CRM/Contact/Form/DedupeFind.php
+++ b/CRM/Contact/Form/DedupeFind.php
@@ -1,9 +1,9 @@
ts('- All Contacts -')) + CRM_Core_PseudoConstant::nestedGroup();
+ $groupList = ['' => ts('- All Contacts -')] + CRM_Core_PseudoConstant::nestedGroup();
- $this->add('select', 'group_id', ts('Select Group'), $groupList, FALSE, array('class' => 'crm-select2 huge'));
+ $this->add('select', 'group_id', ts('Select Group'), $groupList, FALSE, ['class' => 'crm-select2 huge']);
if (Civi::settings()->get('dedupe_default_limit')) {
$this->add('text', 'limit', ts('No of contacts to find matches for '));
}
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'isDefault' => TRUE,
- ),
- //hack to support cancel button functionality
- array(
- 'type' => 'submit',
- 'class' => 'cancel',
- 'icon' => 'fa-times',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Continue'),
+ 'isDefault' => TRUE,
+ ],
+ //hack to support cancel button functionality
+ [
+ 'type' => 'submit',
+ 'class' => 'cancel',
+ 'icon' => 'fa-times',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Contact/Form/DedupeRules.php b/CRM/Contact/Form/DedupeRules.php
index 3491cfb79f7f..318138ff7607 100644
--- a/CRM/Contact/Form/DedupeRules.php
+++ b/CRM/Contact/Form/DedupeRules.php
@@ -1,9 +1,9 @@
_options = CRM_Core_SelectValues::getDedupeRuleTypes();
$this->_rgid = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
- $contactTypes = civicrm_api3('Contact', 'getOptions', array('field' => "contact_type"));
+
+ // check if $contactType is valid
+ $contactTypes = civicrm_api3('Contact', 'getOptions', ['field' => "contact_type", 'context' => "validate"]);
$contactType = CRM_Utils_Request::retrieve('contact_type', 'String', $this, FALSE, 0);
if (CRM_Utils_Array::value($contactType, $contactTypes['values'])) {
- $this->_contactType = CRM_Utils_Array::value($contactType, $contactTypes['values']);
+ $this->_contactType = $contactType;
}
elseif (!empty($contactType)) {
throw new CRM_Core_Exception('Contact Type is Not valid');
@@ -105,38 +107,32 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addField('title', array('label' => ts('Rule Name')), TRUE);
+ $this->addField('title', ['label' => ts('Rule Name')], TRUE);
$this->addRule('title', ts('A duplicate matching rule with this name already exists. Please select another name.'),
- 'objectExists', array('CRM_Dedupe_DAO_RuleGroup', $this->_rgid, 'title')
+ 'objectExists', ['CRM_Dedupe_DAO_RuleGroup', $this->_rgid, 'title']
);
- $this->addField('used', array('label' => ts('Usage')), TRUE);
- $disabled = array();
- $reserved = $this->addField('is_reserved', array('label' => ts('Reserved?')));
+ $this->addField('used', ['label' => ts('Usage')], TRUE);
+ $reserved = $this->addField('is_reserved', ['label' => ts('Reserved?')]);
if (!empty($this->_defaults['is_reserved'])) {
$reserved->freeze();
}
- $attributes = array('class' => 'two');
- if (!empty($disabled)) {
- $attributes = array_merge($attributes, $disabled);
- }
+ $attributes = ['class' => 'two'];
for ($count = 0; $count < self::RULES_COUNT; $count++) {
$this->add('select', "where_$count", ts('Field'),
- array(
- NULL => ts('- none -'),
- ) + $this->_fields, FALSE, $disabled
+ $this->_fields, FALSE, ['class' => 'crm-select2', 'placeholder' => ts('Select Field')]
);
- $this->addField("length_$count", array('entity' => 'Rule', 'name' => 'rule_length') + $attributes);
- $this->addField("weight_$count", array('entity' => 'Rule', 'name' => 'rule_weight') + $attributes);
+ $this->addField("length_$count", ['entity' => 'Rule', 'name' => 'rule_length'] + $attributes);
+ $this->addField("weight_$count", ['entity' => 'Rule', 'name' => 'rule_weight'] + $attributes);
}
- $this->addField('threshold', array('label' => ts("Weight Threshold to Consider Contacts 'Matching':")) + $attributes);
+ $this->addField('threshold', ['label' => ts("Weight Threshold to Consider Contacts 'Matching':")] + $attributes);
$this->assign('contact_type', $this->_contactType);
- $this->addFormRule(array('CRM_Contact_Form_DedupeRules', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_DedupeRules', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -154,7 +150,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
$fieldSelected = FALSE;
for ($count = 0; $count < self::RULES_COUNT; $count++) {
if (!empty($fields["where_$count"]) || (isset($self->_defaults['is_reserved']) && !empty($self->_defaults["where_$count"]))) {
@@ -184,6 +180,7 @@ public static function formRule($fields, $files, $self) {
*
* @return array
*/
+
/**
* @return array
*/
@@ -206,10 +203,10 @@ public function postProcess() {
SET used = 'General'
WHERE contact_type = %1
AND used = %2";
- $queryParams = array(
- 1 => array($this->_contactType, 'String'),
- 2 => array($values['used'], 'String'),
- );
+ $queryParams = [
+ 1 => [$this->_contactType, 'String'],
+ 2 => [$values['used'], 'String'],
+ ];
CRM_Core_DAO::executeQuery($query, $queryParams);
}
@@ -235,18 +232,16 @@ public function postProcess() {
// lets skip updating of fields for reserved dedupe group
if (CRM_Utils_Array::value('is_reserved', $this->_defaults)) {
- CRM_Core_Session::setStatus(ts("The rule '%1' has been saved.", array(1 => $rgDao->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("The rule '%1' has been saved.", [1 => $rgDao->title]), ts('Saved'), 'success');
return;
}
$ruleDao = new CRM_Dedupe_DAO_Rule();
$ruleDao->dedupe_rule_group_id = $rgDao->id;
$ruleDao->delete();
- $ruleDao->free();
-
- $substrLenghts = array();
+ $substrLenghts = [];
- $tables = array();
+ $tables = [];
$daoObj = new CRM_Core_DAO();
$database = $daoObj->database();
for ($count = 0; $count < self::RULES_COUNT; $count++) {
@@ -264,10 +259,9 @@ public function postProcess() {
$ruleDao->rule_length = $length;
$ruleDao->rule_weight = $weight;
$ruleDao->save();
- $ruleDao->free();
if (!array_key_exists($table, $tables)) {
- $tables[$table] = array();
+ $tables[$table] = [];
}
$tables[$table][] = $field;
}
@@ -275,7 +269,7 @@ public function postProcess() {
// CRM-6245: we must pass table/field/length triples to the createIndexes() call below
if ($length) {
if (!isset($substrLenghts[$table])) {
- $substrLenghts[$table] = array();
+ $substrLenghts[$table] = [];
}
//CRM-13417 to avoid fatal error "Incorrect prefix key; the used key part isn't a string, the used length is longer than the key part, or the storage engine doesn't support unique prefix keys, 1089"
@@ -286,15 +280,14 @@ public function postProcess() {
if ($dao->fetch()) {
// set the length to null for all the fields where prefix length is not supported. eg. int,tinyint,date,enum etc dataTypes.
- if ($dao->COLUMN_NAME == $field && !in_array($dao->DATA_TYPE, array(
- 'char',
- 'varchar',
- 'binary',
- 'varbinary',
- 'text',
- 'blob',
- ))
- ) {
+ if ($dao->COLUMN_NAME == $field && !in_array($dao->DATA_TYPE, [
+ 'char',
+ 'varchar',
+ 'binary',
+ 'varbinary',
+ 'text',
+ 'blob',
+ ])) {
$length = NULL;
}
elseif ($dao->COLUMN_NAME == $field && !empty($dao->CHARACTER_MAXIMUM_LENGTH) && ($length > $dao->CHARACTER_MAXIMUM_LENGTH)) {
@@ -317,7 +310,7 @@ public function postProcess() {
CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey);
- CRM_Core_Session::setStatus(ts("The rule '%1' has been saved.", array(1 => $rgDao->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("The rule '%1' has been saved.", [1 => $rgDao->title]), ts('Saved'), 'success');
}
}
diff --git a/CRM/Contact/Form/Domain.php b/CRM/Contact/Form/Domain.php
index c041cef4c695..dcd9eb914677 100644
--- a/CRM/Contact/Form/Domain.php
+++ b/CRM/Contact/Form/Domain.php
@@ -1,9 +1,9 @@
_id)) {
$params['id'] = $this->_id;
CRM_Core_BAO_Domain::retrieve($params, $domainDefaults);
$this->_contactId = $domainDefaults['contact_id'];
- //get the default domain from email address. fix CRM-3552
- $optionValues = array();
- $grpParams['name'] = 'from_email_address';
- CRM_Core_OptionValue::getValues($grpParams, $optionValues);
- foreach ($optionValues as $Id => $value) {
- if ($value['is_default'] && $value['is_active']) {
- $this->_fromEmailId = $Id;
- $list = explode('"', $value['label']);
- $domainDefaults['email_name'] = CRM_Utils_Array::value(1, $list);
- $domainDefaults['email_address'] = CRM_Utils_Mail::pluckEmailFromHeader($value['label']);
- break;
- }
- }
unset($params['id']);
- $locParams = array('contact_id' => $domainDefaults['contact_id']);
+ $locParams = ['contact_id' => $domainDefaults['contact_id']];
$this->_locationDefaults = $defaults = CRM_Core_BAO_Location::getValues($locParams);
$config = CRM_Core_Config::singleton();
@@ -154,27 +141,24 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addField('name', array('label' => ts('Organization Name')), TRUE);
- $this->addField('description', array('label' => ts('Description'), 'size' => 30));
- $this->add('text', 'email_name', ts('FROM Name'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', 'email'), TRUE);
- $this->add('text', 'email_address', ts('FROM Email Address'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', 'email'), TRUE);
- $this->addRule('email_address', ts('Domain Email Address must use a valid email address format (e.g. \'info@example.org\').'), 'email');
+ $this->addField('name', ['label' => ts('Organization Name')], TRUE);
+ $this->addField('description', ['label' => ts('Description'), 'size' => 30]);
//build location blocks.
CRM_Contact_Form_Location::buildQuickForm($this);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'subName' => 'view',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
@@ -186,7 +170,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_Domain', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Domain', 'formRule']);
}
/**
@@ -204,19 +188,9 @@ public static function formRule($fields) {
// $errors === TRUE means no errors from above formRule excution,
// so declaring $errors to array for further processing
if ($errors === TRUE) {
- $errors = array();
- }
-
- //fix for CRM-3552,
- //as we use "fromName" format for domain email.
- if (strpos($fields['email_name'], '"') !== FALSE) {
- $errors['email_name'] = ts('Double quotes are not allow in from name.');
+ $errors = [];
}
- // Check for default from email address and organization (domain) name. Force them to change it.
- if ($fields['email_address'] == 'info@EXAMPLE.ORG') {
- $errors['email_address'] = ts('Please enter a valid default FROM email address for system-generated emails.');
- }
if ($fields['name'] == 'Default Domain Name') {
$errors['name'] = ts('Please enter the name of the organization or entity which owns this CiviCRM site.');
}
@@ -256,15 +230,15 @@ public function postProcess() {
$params['email'][1]['location_type_id'] = $defaultLocationType->id;
}
- $params += array('contact_id' => $this->_contactId);
- $contactParams = array(
+ $params += ['contact_id' => $this->_contactId];
+ $contactParams = [
'sort_name' => $domain->name,
'display_name' => $domain->name,
'legal_name' => $domain->name,
'organization_name' => $domain->name,
'contact_id' => $this->_contactId,
'contact_type' => 'Organization',
- );
+ ];
if ($this->_contactId) {
$contactParams['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($this->_contactId);
@@ -275,37 +249,7 @@ public function postProcess() {
CRM_Core_BAO_Domain::edit($params, $this->_id);
- //set domain from email address, CRM-3552
- $emailName = '"' . $params['email_name'] . '" <' . $params['email_address'] . '>';
-
- $emailParams = array(
- 'label' => $emailName,
- 'description' => $params['description'],
- 'is_active' => 1,
- 'is_default' => 1,
- );
-
- $groupParams = array('name' => 'from_email_address');
-
- //get the option value wt.
- if ($this->_fromEmailId) {
- $action = $this->_action;
- $emailParams['weight'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_fromEmailId, 'weight');
- }
- else {
- //add from email address.
- $action = CRM_Core_Action::ADD;
- $grpId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'from_email_address', 'id', 'name');
- $fieldValues = array('option_group_id' => $grpId);
- $emailParams['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
- }
-
- //reset default within domain.
- $emailParams['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
-
- CRM_Core_OptionValue::addOptionValue($emailParams, $groupParams, $action, $this->_fromEmailId);
-
- CRM_Core_Session::setStatus(ts("Domain information for '%1' has been saved.", array(1 => $domain->name)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("Domain information for '%1' has been saved.", [1 => $domain->name]), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
$session->replaceUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1'));
}
diff --git a/CRM/Contact/Form/Edit/Address.php b/CRM/Contact/Form/Edit/Address.php
index d7b0275ad92e..8cc795e56a58 100644
--- a/CRM/Contact/Form/Edit/Address.php
+++ b/CRM/Contact/Form/Edit/Address.php
@@ -1,9 +1,9 @@
defaultContactCountry;
-
$form->applyFilter('__ALL__', 'trim');
- $js = array();
+ $js = [];
if (!$inlineEdit) {
- $js = array('onChange' => 'checkLocation( this.id );', 'placeholder' => NULL);
+ $js = ['onChange' => 'checkLocation( this.id );', 'placeholder' => NULL];
}
//make location type required for inline edit
- $form->addField("address[$blockId][location_type_id]", array('entity' => 'address', 'class' => 'eight', 'option_url' => NULL) + $js, $inlineEdit);
+ $form->addField("address[$blockId][location_type_id]", ['entity' => 'address', 'class' => 'eight', 'option_url' => NULL] + $js, $inlineEdit);
if (!$inlineEdit) {
- $js = array('id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
+ $js = ['id' => 'Address_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );'];
}
$form->addField(
- "address[$blockId][is_primary]", array(
+ "address[$blockId][is_primary]", [
'entity' => 'address',
'label' => ts('Primary location for this contact'),
- 'text' => ts('Primary location for this contact')) + $js);
+ 'text' => ts('Primary location for this contact'),
+ ] + $js);
if (!$inlineEdit) {
- $js = array('id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );');
+ $js = ['id' => 'Address_' . $blockId . '_IsBilling', 'onClick' => 'singleSelect( this.id );'];
}
$form->addField(
- "address[$blockId][is_billing]", array(
+ "address[$blockId][is_billing]", [
'entity' => 'address',
'label' => ts('Billing location for this contact'),
- 'text' => ts('Billing location for this contact')) + $js);
+ 'text' => ts('Billing location for this contact'),
+ ] + $js);
// hidden element to store master address id
- $form->addField("address[$blockId][master_id]", array('entity' => 'address', 'type' => 'hidden'));
+ $form->addField("address[$blockId][master_id]", ['entity' => 'address', 'type' => 'hidden']);
$addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'address_options', TRUE, NULL, TRUE
);
- $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
- $elements = array(
+ $elements = [
'address_name',
'street_address',
'supplemental_address_1',
@@ -112,21 +110,20 @@ public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharin
'street_number',
'street_name',
'street_unit',
- );
+ ];
foreach ($elements as $name) {
- //Remove id from name, to allow comparison against enabled addressOtions.
+ //Remove id from name, to allow comparison against enabled addressOptions.
$nameWithoutID = strpos($name, '_id') !== FALSE ? substr($name, 0, -3) : $name;
// Skip fields which are not enabled in the address options.
if (empty($addressOptions[$nameWithoutID])) {
$continue = TRUE;
//Don't skip street parsed fields when parsing is enabled.
- if (in_array($nameWithoutID, array(
- 'street_number',
- 'street_name',
- 'street_unit',
- )) && !empty($addressOptions['street_address_parsing'])
- ) {
+ if (in_array($nameWithoutID, [
+ 'street_number',
+ 'street_name',
+ 'street_unit',
+ ]) && !empty($addressOptions['street_address_parsing'])) {
$continue = FALSE;
}
if ($continue) {
@@ -137,7 +134,7 @@ public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharin
$name = 'name';
}
- $params = array('entity' => 'address');
+ $params = ['entity' => 'address'];
if ($name == 'postal_code_suffix') {
$params['label'] = ts('Suffix');
@@ -153,7 +150,7 @@ public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharin
// CRM-11665 geocode override option
$geoCode = FALSE;
- if (!empty($config->geocodeMethod)) {
+ if (CRM_Utils_GeocodeProvider::getUsableClassName()) {
$geoCode = TRUE;
$form->addElement('checkbox',
"address[$blockId][manual_geo_code]",
@@ -162,69 +159,18 @@ public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharin
}
$form->assign('geoCode', $geoCode);
- // Process any address custom data -
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', NULL, $entityId);
-
- if (isset($groupTree) && is_array($groupTree)) {
- // use simplified formatted groupTree
- $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $form);
-
- // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
- foreach ($groupTree as $id => $group) {
- foreach ($group['fields'] as $fldId => $field) {
- $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
- $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
- }
- }
-
- $defaults = array();
- CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults);
-
- // since we change element name for address custom data, we need to format the setdefault values
- $addressDefaults = array();
- foreach ($defaults as $key => $val) {
- if (empty($val)) {
- continue;
- }
-
- // inorder to set correct defaults for checkbox custom data, we need to converted flat key to array
- // this works for all types custom data
- $keyValues = explode('[', str_replace(']', '', $key));
- $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
- }
-
- $form->setDefaults($addressDefaults);
-
- // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
- // And we can't set it to 'address_' because we want to set it in a slightly different format.
- CRM_Core_BAO_CustomGroup::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
-
- // during contact editing : if no address is filled
- // required custom data must not produce 'required' form rule error
- // more handling done in formRule func
- CRM_Contact_Form_Edit_Address::storeRequiredCustomDataInfo($form, $groupTree);
-
- $template = CRM_Core_Smarty::singleton();
- $tplGroupTree = $template->get_template_vars('address_groupTree');
- $tplGroupTree = empty($tplGroupTree) ? array() : $tplGroupTree;
-
- $form->assign('address_groupTree', $tplGroupTree + array($blockId => $groupTree));
- // unset the temp smarty var that got created
- $form->assign('dnc_groupTree', NULL);
- }
- // address custom data processing ends ..
+ self::addCustomDataToForm($form, $entityId, $blockId);
if ($sharing) {
// shared address
$form->addElement('checkbox', "address[$blockId][use_shared_address]", NULL, ts('Use another contact\'s address'));
// Override the default profile links to add address form
- $profileLinks = CRM_Core_BAO_UFGroup::getCreateLinks(array(
- 'new_individual',
- 'new_organization',
- 'new_household',
- ), 'shared_address');
- $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), array('create' => $profileLinks));
+ $profileLinks = CRM_Contact_BAO_Contact::getEntityRefCreateLinks('shared_address');
+ $form->addEntityRef("address[$blockId][master_contact_id]", ts('Share With'), ['create' => $profileLinks, 'api' => ['extra' => ['contact_type']]]);
+
+ // do we want to update employer for shared address
+ $form->addElement('checkbox', "address[$blockId][update_current_employer]", NULL, ts('Set this organization as current employer'));
}
}
@@ -238,10 +184,10 @@ public static function buildQuickForm(&$form, $addressBlockCount = NULL, $sharin
* @return array|bool
* if no errors
*/
- public static function formRule($fields, $files = array(), $self = NULL) {
- $errors = array();
+ public static function formRule($fields, $files = [], $self = NULL) {
+ $errors = [];
- $customDataRequiredFields = array();
+ $customDataRequiredFields = [];
if ($self && property_exists($self, '_addressRequireOmission')) {
$customDataRequiredFields = explode(',', $self->_addressRequireOmission);
}
@@ -295,14 +241,14 @@ public static function formRule($fields, $files = array(), $self = NULL) {
* Form object.
*/
public static function setDefaultValues(&$defaults, &$form) {
- $addressValues = array();
+ $addressValues = [];
if (isset($defaults['address']) && is_array($defaults['address']) &&
!CRM_Utils_System::isNull($defaults['address'])
) {
// start of contact shared adddress defaults
- $sharedAddresses = array();
- $masterAddress = array();
+ $sharedAddresses = [];
+ $masterAddress = [];
// get contact name of shared contact names
$shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']);
@@ -310,15 +256,15 @@ public static function setDefaultValues(&$defaults, &$form) {
foreach ($defaults['address'] as $key => $addressValue) {
if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) {
$master_cid = $shareAddressContactNames[$addressValue['master_id']]['contact_id'];
- $sharedAddresses[$key]['shared_address_display'] = array(
+ $sharedAddresses[$key]['shared_address_display'] = [
'address' => $addressValue['display'],
'name' => $shareAddressContactNames[$addressValue['master_id']]['name'],
- 'options' => CRM_Core_BAO_Address::getValues(array(
- 'entity_id' => $master_cid,
- 'contact_id' => $master_cid,
- )),
+ 'options' => CRM_Core_BAO_Address::getValues([
+ 'entity_id' => $master_cid,
+ 'contact_id' => $master_cid,
+ ]),
'master_id' => $addressValue['master_id'],
- );
+ ];
$defaults['address'][$key]['master_contact_id'] = $master_cid;
}
else {
@@ -336,19 +282,19 @@ public static function setDefaultValues(&$defaults, &$form) {
// start of parse address functionality
// build street address, CRM-5450.
if ($form->_parseStreetAddress) {
- $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit');
+ $parseFields = ['street_address', 'street_number', 'street_name', 'street_unit'];
foreach ($defaults['address'] as $cnt => & $address) {
$streetAddress = NULL;
- foreach (array(
- 'street_number',
- 'street_number_suffix',
- 'street_name',
- 'street_unit',
- ) as $fld) {
- if (in_array($fld, array(
+ foreach ([
+ 'street_number',
+ 'street_number_suffix',
+ 'street_name',
+ 'street_unit',
+ ] as $fld) {
+ if (in_array($fld, [
'street_name',
'street_unit',
- ))) {
+ ])) {
$streetAddress .= ' ';
}
// CRM-17619 - if the street number suffix begins with a number, add a space
@@ -379,7 +325,7 @@ public static function setDefaultValues(&$defaults, &$form) {
$addressValues["{$field}_{$cnt}"] = CRM_Utils_Array::value($field, $address);
}
// don't load fields, use js to populate.
- foreach (array('street_number', 'street_name', 'street_unit') as $f) {
+ foreach (['street_number', 'street_name', 'street_unit'] as $f) {
if (isset($address[$f])) {
unset($address[$f]);
}
@@ -388,12 +334,12 @@ public static function setDefaultValues(&$defaults, &$form) {
$form->assign('allAddressFieldValues', json_encode($addressValues));
//hack to handle show/hide address fields.
- $parsedAddress = array();
+ $parsedAddress = [];
if ($form->_contactId && !empty($_POST['address']) && is_array($_POST['address'])
) {
foreach ($_POST['address'] as $cnt => $values) {
$showField = 'streetAddress';
- foreach (array('street_number', 'street_name', 'street_unit') as $fld) {
+ foreach (['street_number', 'street_name', 'street_unit'] as $fld) {
if (!empty($values[$fld])) {
$showField = 'addressElements';
break;
@@ -416,7 +362,7 @@ public static function setDefaultValues(&$defaults, &$form) {
* @param array $groupTree
*/
public static function storeRequiredCustomDataInfo(&$form, $groupTree) {
- if (in_array(CRM_Utils_System::getClassName($form), array('CRM_Contact_Form_Contact', 'CRM_Contact_Form_Inline_Address'))) {
+ if (in_array(CRM_Utils_System::getClassName($form), ['CRM_Contact_Form_Contact', 'CRM_Contact_Form_Inline_Address'])) {
$requireOmission = NULL;
foreach ($groupTree as $csId => $csVal) {
// only process Address entity fields
@@ -439,4 +385,64 @@ public static function storeRequiredCustomDataInfo(&$form, $groupTree) {
}
}
+ /**
+ * Add custom data to the form.
+ *
+ * @param CRM_Core_Form $form
+ * @param int $entityId
+ * @param int $blockId
+ */
+ protected static function addCustomDataToForm(&$form, $entityId, $blockId) {
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', NULL, $entityId);
+
+ if (isset($groupTree) && is_array($groupTree)) {
+ // use simplified formatted groupTree
+ $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $form);
+
+ // make sure custom fields are added /w element-name in the format - 'address[$blockId][custom-X]'
+ foreach ($groupTree as $id => $group) {
+ foreach ($group['fields'] as $fldId => $field) {
+ $groupTree[$id]['fields'][$fldId]['element_custom_name'] = $field['element_name'];
+ $groupTree[$id]['fields'][$fldId]['element_name'] = "address[$blockId][{$field['element_name']}]";
+ }
+ }
+
+ $defaults = [];
+ CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $defaults);
+
+ // since we change element name for address custom data, we need to format the setdefault values
+ $addressDefaults = [];
+ foreach ($defaults as $key => $val) {
+ if (!isset($val)) {
+ continue;
+ }
+
+ // inorder to set correct defaults for checkbox custom data, we need to converted flat key to array
+ // this works for all types custom data
+ $keyValues = explode('[', str_replace(']', '', $key));
+ $addressDefaults[$keyValues[0]][$keyValues[1]][$keyValues[2]] = $val;
+ }
+
+ $form->setDefaults($addressDefaults);
+
+ // we setting the prefix to 'dnc_' below, so that we don't overwrite smarty's grouptree var.
+ // And we can't set it to 'address_' because we want to set it in a slightly different format.
+ CRM_Core_BAO_CustomGroup::buildQuickForm($form, $groupTree, FALSE, 'dnc_');
+
+ // during contact editing : if no address is filled
+ // required custom data must not produce 'required' form rule error
+ // more handling done in formRule func
+ CRM_Contact_Form_Edit_Address::storeRequiredCustomDataInfo($form, $groupTree);
+
+ $tplGroupTree = CRM_Core_Smarty::singleton()
+ ->get_template_vars('address_groupTree');
+ $tplGroupTree = empty($tplGroupTree) ? [] : $tplGroupTree;
+
+ $form->assign('address_groupTree', $tplGroupTree + [$blockId => $groupTree]);
+ // unset the temp smarty var that got created
+ $form->assign('dnc_groupTree', NULL);
+ }
+ // address custom data processing ends ..
+ }
+
}
diff --git a/CRM/Contact/Form/Edit/CommunicationPreferences.php b/CRM/Contact/Form/Edit/CommunicationPreferences.php
index 20f08e501bb6..91d125fa1ea2 100644
--- a/CRM/Contact/Form/Edit/CommunicationPreferences.php
+++ b/CRM/Contact/Form/Edit/CommunicationPreferences.php
@@ -1,9 +1,9 @@
addGroup($privacy, 'privacy', ts('Privacy'), ' ');
// preferred communication method
- $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method', array('loclize' => TRUE));
+ $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method', ['loclize' => TRUE]);
foreach ($comm as $value => $title) {
$commPreff[] = $form->createElement('advcheckbox', $value, NULL, $title);
}
- $form->addField('preferred_communication_method', array('entity' => 'contact', 'type' => 'CheckBoxGroup'));
- $form->addField('preferred_language', array('entity' => 'contact'));
+ $form->addField('preferred_communication_method', ['entity' => 'contact', 'type' => 'CheckBoxGroup']);
+ $form->addField('preferred_language', ['entity' => 'contact']);
if (!empty($privacyOptions)) {
$commPreference['privacy'] = $privacyOptions;
@@ -84,27 +84,27 @@ public static function buildQuickForm(&$form) {
//using for display purpose.
$form->assign('commPreference', $commPreference);
- $form->addField('preferred_mail_format', array('entity' => 'contact', 'label' => ts('Email Format')));
+ $form->addField('preferred_mail_format', ['entity' => 'contact', 'label' => ts('Email Format')]);
- $form->addField('is_opt_out', array('entity' => 'contact', 'label' => ts('NO BULK EMAILS (User Opt Out)')));
+ $form->addField('is_opt_out', ['entity' => 'contact', 'label' => ts('NO BULK EMAILS (User Opt Out)')]);
- $form->addField('communication_style_id', array('entity' => 'contact', 'type' => 'RadioGroup'));
+ $form->addField('communication_style_id', ['entity' => 'contact', 'type' => 'RadioGroup']);
//check contact type and build filter clause accordingly for greeting types, CRM-4575
$greetings = self::getGreetingFields($form->_contactType);
foreach ($greetings as $greeting => $fields) {
- $filter = array(
+ $filter = [
'contact_type' => $form->_contactType,
'greeting_type' => $greeting,
- );
+ ];
//add addressee in Contact form
$greetingTokens = CRM_Core_PseudoConstant::greeting($filter);
if (!empty($greetingTokens)) {
$form->addElement('select', $fields['field'], $fields['label'],
- array(
+ [
'' => ts('- select -'),
- ) + $greetingTokens
+ ] + $greetingTokens
);
//custom addressee
$form->addElement('text', $fields['customField'], $fields['customLabel'],
@@ -134,7 +134,7 @@ public static function formRule($fields, $files, $self) {
$customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $details['field'], 'Customized');
if (CRM_Utils_Array::value($details['field'], $fields) == $customizedValue && empty($fields[$details['customField']])) {
$errors[$details['customField']] = ts('Custom %1 is a required field if %1 is of type Customized.',
- array(1 => $details['label'])
+ [1 => $details['label']]
);
}
}
@@ -202,36 +202,36 @@ public static function setDefaultValues(&$form, &$defaults) {
*/
public static function getGreetingFields($contactType) {
if (empty(self::$greetings[$contactType])) {
- self::$greetings[$contactType] = array();
+ self::$greetings[$contactType] = [];
- $js = array(
+ $js = [
'onfocus' => "if (!this.value) { this.value='Dear ';} else return false",
'onblur' => "if ( this.value == 'Dear') { this.value='';} else return false",
- );
+ ];
- self::$greetings[$contactType] = array(
- 'addressee' => array(
+ self::$greetings[$contactType] = [
+ 'addressee' => [
'field' => 'addressee_id',
'customField' => 'addressee_custom',
'label' => ts('Addressee'),
'customLabel' => ts('Custom Addressee'),
'js' => NULL,
- ),
- 'email_greeting' => array(
+ ],
+ 'email_greeting' => [
'field' => 'email_greeting_id',
'customField' => 'email_greeting_custom',
'label' => ts('Email Greeting'),
'customLabel' => ts('Custom Email Greeting'),
'js' => $js,
- ),
- 'postal_greeting' => array(
+ ],
+ 'postal_greeting' => [
'field' => 'postal_greeting_id',
'customField' => 'postal_greeting_custom',
'label' => ts('Postal Greeting'),
'customLabel' => ts('Custom Postal Greeting'),
'js' => $js,
- ),
- );
+ ],
+ ];
}
return self::$greetings[$contactType];
diff --git a/CRM/Contact/Form/Edit/CustomData.php b/CRM/Contact/Form/Edit/CustomData.php
index eb865796ed78..3833b288e6c7 100644
--- a/CRM/Contact/Form/Edit/CustomData.php
+++ b/CRM/Contact/Form/Edit/CustomData.php
@@ -1,9 +1,9 @@
addField('gender_id', array('entity' => 'contact', 'type' => 'Radio', 'allowClear' => TRUE));
+ $form->addField('gender_id', ['entity' => 'contact', 'type' => 'Radio', 'allowClear' => TRUE]);
- $form->addField('birth_date', array('entity' => 'contact'), FALSE, FALSE);
+ $form->addField('birth_date', ['entity' => 'contact'], FALSE, FALSE);
- $form->addField('is_deceased', array('entity' => 'contact', 'label' => ts('Contact is Deceased'), 'onclick' => "showDeceasedDate()"));
- $form->addField('deceased_date', array('entity' => 'contact'), FALSE, FALSE);
+ $form->addField('is_deceased', ['entity' => 'contact', 'label' => ts('Contact is Deceased'), 'onclick' => "showDeceasedDate()"]);
+ $form->addField('deceased_date', ['entity' => 'contact'], FALSE, FALSE);
}
/**
diff --git a/CRM/Contact/Form/Edit/Email.php b/CRM/Contact/Form/Edit/Email.php
index 9d6b217349c8..91ddeffea012 100644
--- a/CRM/Contact/Form/Edit/Email.php
+++ b/CRM/Contact/Form/Edit/Email.php
@@ -1,9 +1,9 @@
applyFilter('__ALL__', 'trim');
//Email box
- $form->addField("email[$blockId][email]", array('entity' => 'email'));
+ $form->addField("email[$blockId][email]", ['entity' => 'email', 'aria-label' => ts('Email %1', [1 => $blockId])]);
$form->addRule("email[$blockId][email]", ts('Email is not valid.'), 'email');
if (isset($form->_contactType) || $blockEdit) {
//Block type
- $form->addField("email[$blockId][location_type_id]", array('entity' => 'email', 'placeholder' => NULL, 'class' => 'eight', 'option_url' => NULL));
+ $form->addField("email[$blockId][location_type_id]", ['entity' => 'email', 'placeholder' => NULL, 'class' => 'eight', 'option_url' => NULL]);
//TODO: Refactor on_hold field to select.
$multipleBulk = CRM_Core_BAO_Email::isMultipleBulkMail();
//On-hold select
if ($multipleBulk) {
- $holdOptions = array(
+ $holdOptions = [
0 => ts('- select -'),
1 => ts('On Hold Bounce'),
2 => ts('On Hold Opt Out'),
- );
+ ];
$form->addElement('select', "email[$blockId][on_hold]", '', $holdOptions);
}
else {
- $form->addField("email[$blockId][on_hold]", array('entity' => 'email', 'type' => 'advcheckbox'));
+ $form->addField("email[$blockId][on_hold]", ['entity' => 'email', 'type' => 'advcheckbox', 'aria-label' => ts('On Hold for Email %1?', [1 => $blockId])]);
}
//Bulkmail checkbox
$form->assign('multipleBulk', $multipleBulk);
- if ($multipleBulk) {
- $js = array('id' => "Email_" . $blockId . "_IsBulkmail");
- $form->addElement('advcheckbox', "email[$blockId][is_bulkmail]", NULL, '', $js);
- }
- else {
- $js = array('id' => "Email_" . $blockId . "_IsBulkmail");
- if (!$blockEdit) {
- $js['onClick'] = 'singleSelect( this.id );';
- }
- $form->addElement('radio', "email[$blockId][is_bulkmail]", '', '', '1', $js);
+ $js = ['id' => "Email_" . $blockId . "_IsBulkmail" , 'aria-label' => ts('Bulk Mailing for Email %1?', [1 => $blockId])];
+ if (!$blockEdit) {
+ $js['onClick'] = 'singleSelect( this.id );';
}
+ $form->addElement('advcheckbox', "email[$blockId][is_bulkmail]", NULL, '', $js);
//is_Primary radio
- $js = array('id' => "Email_" . $blockId . "_IsPrimary");
+ $js = ['id' => "Email_" . $blockId . "_IsPrimary", 'aria-label' => ts('Email %1 is primary?', [1 => $blockId])];
if (!$blockEdit) {
$js['onClick'] = 'singleSelect( this.id );';
}
@@ -105,11 +99,11 @@ public static function buildQuickForm(&$form, $blockCount = NULL, $blockEdit = F
if (CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Contact') {
$form->add('textarea', "email[$blockId][signature_text]", ts('Signature (Text)'),
- array('rows' => 2, 'cols' => 40)
+ ['rows' => 2, 'cols' => 40]
);
$form->add('wysiwyg', "email[$blockId][signature_html]", ts('Signature (HTML)'),
- array('rows' => 2, 'cols' => 40)
+ ['rows' => 2, 'cols' => 40]
);
}
}
diff --git a/CRM/Contact/Form/Edit/Household.php b/CRM/Contact/Form/Edit/Household.php
index 1b6823657e63..1d9fc60fdf3e 100644
--- a/CRM/Contact/Form/Edit/Household.php
+++ b/CRM/Contact/Form/Edit/Household.php
@@ -1,9 +1,9 @@
addField('nick_name');
- $form->addField('contact_source', array('label' => ts('Source')));
+ $form->addField('contact_source', ['label' => ts('Source')]);
}
if (!$inlineEditMode) {
- $form->addField('external_identifier', array('label' => ts('External ID')));
+ $form->addField('external_identifier', ['label' => ts('External ID')]);
$form->addRule('external_identifier',
ts('External ID already exists in Database.'),
'objectExists',
- array('CRM_Contact_DAO_Contact', $form->_contactId, 'external_identifier')
+ ['CRM_Contact_DAO_Contact', $form->_contactId, 'external_identifier']
);
}
}
@@ -84,17 +84,14 @@ public static function buildQuickForm(&$form, $inlineEditMode = NULL) {
* $error
*/
public static function formRule($fields, $files, $contactID = NULL) {
- $errors = array();
- $primaryID = CRM_Contact_Form_Contact::formRule($fields, $errors, $contactID);
+ $errors = [];
+ $primaryID = CRM_Contact_Form_Contact::formRule($fields, $errors, $contactID, 'Household');
// make sure that household name is set
if (empty($fields['household_name'])) {
$errors['household_name'] = 'Household Name should be set.';
}
- //check for duplicate - dedupe rules
- CRM_Contact_Form_Contact::checkDuplicateContacts($fields, $errors, $contactID, 'Household');
-
return empty($errors) ? TRUE : $errors;
}
diff --git a/CRM/Contact/Form/Edit/IM.php b/CRM/Contact/Form/Edit/IM.php
index ca56642b398f..78781d8c2242 100644
--- a/CRM/Contact/Form/Edit/IM.php
+++ b/CRM/Contact/Form/Edit/IM.php
@@ -1,9 +1,9 @@
applyFilter('__ALL__', 'trim');
//IM provider select
- $form->addField("im[$blockId][provider_id]", array('entity' => 'im', 'class' => 'eight', 'placeholder' => NULL));
+ $form->addField("im[$blockId][provider_id]", ['entity' => 'im', 'class' => 'eight', 'placeholder' => NULL]);
//Block type select
- $form->addField("im[$blockId][location_type_id]", array('entity' => 'im', 'class' => 'eight', 'placeholder' => NULL, 'option_url' => NULL));
+ $form->addField("im[$blockId][location_type_id]", ['entity' => 'im', 'class' => 'eight', 'placeholder' => NULL, 'option_url' => NULL]);
//IM box
- $form->addField("im[$blockId][name]", array('entity' => 'im'));
+ $form->addField("im[$blockId][name]", ['entity' => 'im', 'aria-label' => ts('Instant Messenger %1', [1 => $blockId])]);
//is_Primary radio
- $js = array('id' => 'IM_' . $blockId . '_IsPrimary');
+ $js = ['id' => 'IM_' . $blockId . '_IsPrimary', 'aria-label' => ts('Instant Messenger %1 is primary?', [1 => $blockId])];
if (!$blockEdit) {
$js['onClick'] = 'singleSelect( this.id );';
}
diff --git a/CRM/Contact/Form/Edit/Individual.php b/CRM/Contact/Form/Edit/Individual.php
index 0395b783403d..d39c7d95e8e1 100644
--- a/CRM/Contact/Form/Edit/Individual.php
+++ b/CRM/Contact/Form/Edit/Individual.php
@@ -1,9 +1,9 @@
'eight', 'placeholder' => ' ', 'label' => $name == 'prefix_id' ? ts('Prefix') : ts('Suffix'));
+ $props = ['class' => 'eight', 'placeholder' => ' ', 'label' => $name == 'prefix_id' ? ts('Prefix') : ts('Suffix')];
}
$form->addField($name, $props);
}
@@ -84,32 +84,25 @@ public static function buildQuickForm(&$form, $inlineEditMode = NULL) {
// job title
// override the size for UI to look better
- $form->addField('job_title', array('size' => '30'));
+ $form->addField('job_title', ['size' => '30']);
//Current Employer Element
- $props = array(
- 'api' => array('params' => array('contact_type' => 'Organization')),
+ $props = [
+ 'api' => ['params' => ['contact_type' => 'Organization']],
'create' => TRUE,
- );
+ ];
$form->addField('employer_id', $props);
- $form->addField('contact_source', array('class' => 'big'));
+ $form->addField('contact_source', ['class' => 'big']);
}
if (!$inlineEditMode) {
- $checkSimilar = Civi::settings()->get('contact_ajax_check_similar');
-
- if ($checkSimilar == NULL) {
- $checkSimilar = 0;
- }
- $form->assign('checkSimilar', $checkSimilar);
-
//External Identifier Element
- $form->addField('external_identifier', array('label' => 'External ID'));
+ $form->addField('external_identifier', ['label' => 'External ID']);
$form->addRule('external_identifier',
ts('External ID already exists in Database.'),
'objectExists',
- array('CRM_Contact_DAO_Contact', $form->_contactId, 'external_identifier')
+ ['CRM_Contact_DAO_Contact', $form->_contactId, 'external_identifier']
);
CRM_Core_ShowHideBlocks::links($form, 'demographics', '', '');
}
@@ -128,17 +121,14 @@ public static function buildQuickForm(&$form, $inlineEditMode = NULL) {
* TRUE if no errors, else array of errors.
*/
public static function formRule($fields, $files, $contactID = NULL) {
- $errors = array();
- $primaryID = CRM_Contact_Form_Contact::formRule($fields, $errors, $contactID);
+ $errors = [];
+ $primaryID = CRM_Contact_Form_Contact::formRule($fields, $errors, $contactID, 'Individual');
// make sure that firstName and lastName or a primary OpenID is set
if (!$primaryID && (empty($fields['first_name']) || empty($fields['last_name']))) {
$errors['_qf_default'] = ts('First Name and Last Name OR an email OR an OpenID in the Primary Location should be set.');
}
- //check for duplicate - dedupe rules
- CRM_Contact_Form_Contact::checkDuplicateContacts($fields, $errors, $contactID, 'Individual');
-
return empty($errors) ? TRUE : $errors;
}
diff --git a/CRM/Contact/Form/Edit/Lock.php b/CRM/Contact/Form/Edit/Lock.php
index b8119602c117..c844b8cea5e4 100644
--- a/CRM/Contact/Form/Edit/Lock.php
+++ b/CRM/Contact/Form/Edit/Lock.php
@@ -1,9 +1,9 @@
addField('modified_date', array('type' => 'hidden', 'id' => 'modified_date', 'label' => ''));
+ $form->addField('modified_date', ['type' => 'hidden', 'id' => 'modified_date', 'label' => '']);
}
/**
@@ -59,7 +59,7 @@ public static function buildQuickForm(&$form) {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $contactID = NULL) {
- $errors = array();
+ $errors = [];
$timestamps = CRM_Contact_BAO_Contact::getTimestamps($contactID);
if ($fields['modified_date'] != $timestamps['modified_date']) {
diff --git a/CRM/Contact/Form/Edit/Notes.php b/CRM/Contact/Form/Edit/Notes.php
index 7da39198827c..d926847685d7 100644
--- a/CRM/Contact/Form/Edit/Notes.php
+++ b/CRM/Contact/Form/Edit/Notes.php
@@ -1,9 +1,9 @@
applyFilter('__ALL__', 'trim');
- $form->addField('subject', array('entity' => 'note', 'size' => '60'));
- $form->addField('note', array('entity' => 'note', 'rows' => 3));
+ $form->addField('subject', ['entity' => 'note', 'size' => '60']);
+ $form->addField('note', ['entity' => 'note', 'rows' => 3]);
}
}
diff --git a/CRM/Contact/Form/Edit/OpenID.php b/CRM/Contact/Form/Edit/OpenID.php
index de13a9657b5c..2d4ab2ca0c6d 100644
--- a/CRM/Contact/Form/Edit/OpenID.php
+++ b/CRM/Contact/Form/Edit/OpenID.php
@@ -1,9 +1,9 @@
addElement('select', "openid[$blockId][location_type_id]", '', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'));
//is_Primary radio
- $js = array('id' => "OpenID_" . $blockId . "_IsPrimary");
+ $js = ['id' => "OpenID_" . $blockId . "_IsPrimary"];
if (!$blockEdit) {
$js['onClick'] = 'singleSelect( this.id );';
}
diff --git a/CRM/Contact/Form/Edit/Organization.php b/CRM/Contact/Form/Edit/Organization.php
index a52bbd0047ad..05ae544a4f9d 100644
--- a/CRM/Contact/Form/Edit/Organization.php
+++ b/CRM/Contact/Form/Edit/Organization.php
@@ -1,9 +1,9 @@
addField('external_identifier', array('label' => ts('External ID')));
+ $form->addField('external_identifier', ['label' => ts('External ID')]);
$form->addRule('external_identifier',
ts('External ID already exists in Database.'),
'objectExists',
- array('CRM_Contact_DAO_Contact', $form->_contactId, 'external_identifier')
+ ['CRM_Contact_DAO_Contact', $form->_contactId, 'external_identifier']
);
}
}
@@ -85,17 +85,14 @@ public static function buildQuickForm(&$form, $inlineEditMode = NULL) {
* @return array|bool
*/
public static function formRule($fields, $files, $contactID = NULL) {
- $errors = array();
- $primaryID = CRM_Contact_Form_Contact::formRule($fields, $errors, $contactID);
+ $errors = [];
+ $primaryID = CRM_Contact_Form_Contact::formRule($fields, $errors, $contactID, 'Organization');
// make sure that organization name is set
if (empty($fields['organization_name'])) {
$errors['organization_name'] = 'Organization Name should be set.';
}
- //check for duplicate - dedupe rules
- CRM_Contact_Form_Contact::checkDuplicateContacts($fields, $errors, $contactID, 'Organization');
-
// add code to make sure that the uniqueness criteria is satisfied
return empty($errors) ? TRUE : $errors;
}
diff --git a/CRM/Contact/Form/Edit/Phone.php b/CRM/Contact/Form/Edit/Phone.php
index 84b7ccb379a3..79538fbaf977 100644
--- a/CRM/Contact/Form/Edit/Phone.php
+++ b/CRM/Contact/Form/Edit/Phone.php
@@ -1,9 +1,9 @@
applyFilter('__ALL__', 'trim');
//phone type select
- $form->addField("phone[$blockId][phone_type_id]", array(
+ $form->addField("phone[$blockId][phone_type_id]", [
'entity' => 'phone',
'class' => 'eight',
'placeholder' => NULL,
- ));
+ ]);
//main phone number with crm_phone class
- $form->addField("phone[$blockId][phone]", array('entity' => 'phone', 'class' => 'crm_phone twelve'));
- $form->addField("phone[$blockId][phone_ext]", array('entity' => 'phone'));
+ $form->addField("phone[$blockId][phone]", ['entity' => 'phone', 'class' => 'crm_phone twelve', 'aria-label' => ts('Phone %1', [1 => $blockId])]);
+ $form->addField("phone[$blockId][phone_ext]", ['entity' => 'phone', 'aria-label' => ts('Phone Extension %1', [1 => $blockId])]);
if (isset($form->_contactType) || $blockEdit) {
//Block type select
- $form->addField("phone[$blockId][location_type_id]", array(
+ $form->addField("phone[$blockId][location_type_id]", [
'entity' => 'phone',
- 'class' => 'eight',
- 'placeholder' => NULL,
- 'option_url' => NULL,
- ));
+ 'class' => 'eight',
+ 'placeholder' => NULL,
+ 'option_url' => NULL,
+ ]);
//is_Primary radio
- $js = array('id' => 'Phone_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
+ $js = ['id' => 'Phone_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );', 'aria-label' => ts('Phone %1 is primary?', [1 => $blockId])];
$form->addElement('radio', "phone[$blockId][is_primary]", '', '', '1', $js);
}
// TODO: set this up as a group, we need a valid phone_type_id if we have a phone number
diff --git a/CRM/Contact/Form/Edit/TagsAndGroups.php b/CRM/Contact/Form/Edit/TagsAndGroups.php
index 1518c2a119e0..b89c3a023e9e 100644
--- a/CRM/Contact/Form/Edit/TagsAndGroups.php
+++ b/CRM/Contact/Form/Edit/TagsAndGroups.php
@@ -1,9 +1,9 @@
_tagGroup)) {
- $form->_tagGroup = array();
+ $form->_tagGroup = [];
}
// NYSS 5670
@@ -91,7 +91,7 @@ public static function buildQuickForm(
$groupID = isset($form->_grid) ? $form->_grid : NULL;
if ($groupID && $visibility) {
- $ids = array($groupID => $groupID);
+ $ids = [$groupID => $groupID];
}
else {
if ($visibility) {
@@ -107,8 +107,8 @@ public static function buildQuickForm(
$groups = CRM_Contact_BAO_Group::getGroupsHierarchy($ids);
$attributes['skiplabel'] = TRUE;
- $elements = array();
- $groupsOptions = array();
+ $elements = [];
+ $groupsOptions = [];
foreach ($groups as $id => $group) {
// make sure that this group has public visibility
if ($visibility &&
@@ -128,7 +128,7 @@ public static function buildQuickForm(
if ($groupElementType == 'select' && !empty($groupsOptions)) {
$form->add('select', $fName, $groupName, $groupsOptions, FALSE,
- array('id' => $fName, 'multiple' => 'multiple', 'class' => 'crm-select2 twenty')
+ ['id' => $fName, 'multiple' => 'multiple', 'class' => 'crm-select2 twenty']
);
$form->assign('groupCount', count($groupsOptions));
}
@@ -137,7 +137,7 @@ public static function buildQuickForm(
$form->addGroup($elements, $fName, $groupName, ' ');
$form->assign('groupCount', count($elements));
if ($isRequired) {
- $form->addRule($fName, ts('%1 is a required field.', array(1 => $groupName)), 'required');
+ $form->addRule($fName, ts('%1 is a required field.', [1 => $groupName]), 'required');
}
}
$form->assign('groupElementType', $groupElementType);
@@ -148,7 +148,7 @@ public static function buildQuickForm(
$tags = CRM_Core_BAO_Tag::getColorTags('civicrm_contact');
if (!empty($tags)) {
- $form->add('select2', 'tag', ts('Tag(s)'), $tags, FALSE, array('class' => 'huge', 'placeholder' => ts('- select -'), 'multiple' => TRUE));
+ $form->add('select2', 'tag', ts('Tag(s)'), $tags, FALSE, ['class' => 'huge', 'placeholder' => ts('- select -'), 'multiple' => TRUE]);
}
// build tag widget
diff --git a/CRM/Contact/Form/Edit/Website.php b/CRM/Contact/Form/Edit/Website.php
index 8cd7336eaec3..8930e9956c2d 100644
--- a/CRM/Contact/Form/Edit/Website.php
+++ b/CRM/Contact/Form/Edit/Website.php
@@ -1,9 +1,9 @@
applyFilter('__ALL__', 'trim');
//Website type select
- $form->addField("website[$blockId][website_type_id]", array('entity' => 'website', 'class' => 'eight'));
+ $form->addField("website[$blockId][website_type_id]", ['entity' => 'website', 'class' => 'eight', 'placeholder' => NULL]);
//Website box
- $form->addField("website[$blockId][url]", array('entity' => 'website'));
+ $form->addField("website[$blockId][url]", ['entity' => 'website', 'aria-label' => ts('Website URL %1', [1 => $blockId])]);
$form->addRule("website[$blockId][url]", ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'url');
}
diff --git a/CRM/Contact/Form/GroupContact.php b/CRM/Contact/Form/GroupContact.php
index a443d8115f34..da68e58b7755 100644
--- a/CRM/Contact/Form/GroupContact.php
+++ b/CRM/Contact/Form/GroupContact.php
@@ -1,9 +1,9 @@
_contactId = $this->get('contactId');
$this->_groupContactId = $this->get('groupContactId');
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
}
/**
@@ -83,7 +83,7 @@ public function buildQuickForm() {
$ids = CRM_Core_PseudoConstant::allGroup();
$heirGroups = CRM_Contact_BAO_Group::getGroupsHierarchy($ids);
- $allGroups = array();
+ $allGroups = [];
foreach ($heirGroups as $id => $group) {
// make sure that this group has public visibility
if ($onlyPublicGroups && $group['visibility'] == 'User and User Admin Only') {
@@ -111,7 +111,7 @@ public function buildQuickForm() {
$groupSelect = $groupHierarchy;
}
- $groupSelect = array('' => ts('- select group -')) + $groupSelect;
+ $groupSelect = ['' => ts('- select group -')] + $groupSelect;
if (count($groupSelect) > 1) {
$session = CRM_Core_Session::singleton();
@@ -123,16 +123,15 @@ public function buildQuickForm() {
$msg = ts('Add to a group');
}
- $this->addField('group_id', array('class' => 'crm-action-menu fa-plus', 'placeholder' => $msg, 'options' => $groupSelect));
+ $this->addField('group_id', ['class' => 'crm-action-menu fa-plus', 'placeholder' => $msg, 'options' => $groupSelect]);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Add'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Add'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
@@ -140,7 +139,7 @@ public function buildQuickForm() {
* Post process form.
*/
public function postProcess() {
- $contactID = array($this->_contactId);
+ $contactID = [$this->_contactId];
$groupId = $this->controller->exportValue('GroupContact', 'group_id');
$method = ($this->_context == 'user') ? 'Web' : 'Admin';
@@ -154,7 +153,7 @@ public function postProcess() {
if ($groupContact && $this->_context != 'user') {
$groups = CRM_Core_PseudoConstant::group();
- CRM_Core_Session::setStatus(ts("Contact has been added to '%1'.", array(1 => $groups[$groupId])), ts('Added to Group'), 'success');
+ CRM_Core_Session::setStatus(ts("Contact has been added to '%1'.", [1 => $groups[$groupId]]), ts('Added to Group'), 'success');
}
}
diff --git a/CRM/Contact/Form/Inline.php b/CRM/Contact/Form/Inline.php
index 01340a47bd69..0a03b0475e34 100644
--- a/CRM/Contact/Form/Inline.php
+++ b/CRM/Contact/Form/Inline.php
@@ -1,9 +1,9 @@
_contactId);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -114,7 +117,7 @@ public function buildQuickForm() {
* Override default cancel action.
*/
public function cancelAction() {
- $response = array('status' => 'cancel');
+ $response = ['status' => 'cancel'];
CRM_Utils_JSON::output($response);
}
@@ -124,7 +127,7 @@ public function cancelAction() {
* @return array
*/
public function setDefaultValues() {
- $defaults = $params = array();
+ $defaults = $params = [];
$params['id'] = $this->_contactId;
CRM_Contact_BAO_Contact::getValues($params, $defaults);
@@ -175,11 +178,11 @@ public static function renderFooter($cid, $includeCount = TRUE) {
'contact_view_options', TRUE
);
$smarty->assign('changeLog', $viewOptions['log']);
- $ret = array('markup' => $smarty->fetch('CRM/common/contactFooter.tpl'));
+ $ret = ['markup' => $smarty->fetch('CRM/common/contactFooter.tpl')];
if ($includeCount) {
$ret['count'] = CRM_Contact_BAO_Contact::getCountComponent('log', $cid);
}
- return array('changeLog' => $ret);
+ return ['changeLog' => $ret];
}
}
diff --git a/CRM/Contact/Form/Inline/Address.php b/CRM/Contact/Form/Inline/Address.php
index e6c7e3504144..eda850c7d3ec 100644
--- a/CRM/Contact/Form/Inline/Address.php
+++ b/CRM/Contact/Form/Inline/Address.php
@@ -1,9 +1,9 @@
assign('addressSequence', $addressSequence);
- $this->_values = array();
+ $this->_values = [];
$this->_addressId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, NULL, $_REQUEST);
$this->_action = CRM_Core_Action::ADD;
if ($this->_addressId) {
- $params = array('id' => $this->_addressId);
+ $params = ['id' => $this->_addressId];
$address = CRM_Core_BAO_Address::getValues($params, FALSE, 'id');
$this->_values['address'][$this->_locBlockNo] = array_pop($address);
$this->_action = CRM_Core_Action::UPDATE;
@@ -125,7 +130,7 @@ public function preProcess() {
public function buildQuickForm() {
parent::buildQuickForm();
CRM_Contact_Form_Edit_Address::buildQuickForm($this, $this->_locBlockNo, TRUE, TRUE);
- $this->addFormRule(array('CRM_Contact_Form_Edit_Address', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this);
}
/**
diff --git a/CRM/Contact/Form/Inline/CommunicationPreferences.php b/CRM/Contact/Form/Inline/CommunicationPreferences.php
index ce67560a2b66..adbc82f07924 100644
--- a/CRM/Contact/Form/Inline/CommunicationPreferences.php
+++ b/CRM/Contact/Form/Inline/CommunicationPreferences.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this);
}
/**
diff --git a/CRM/Contact/Form/Inline/ContactInfo.php b/CRM/Contact/Form/Inline/ContactInfo.php
index 48ef0d31b43a..55f1a1ddc822 100644
--- a/CRM/Contact/Form/Inline/ContactInfo.php
+++ b/CRM/Contact/Form/Inline/ContactInfo.php
@@ -1,9 +1,9 @@
ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_rel' => CRM_Contact_BAO_Contact::getCountComponent('rel', $this->_contactId),
- );
+ ];
if (CRM_Core_Permission::access('CiviContribute')) {
$this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
diff --git a/CRM/Contact/Form/Inline/ContactName.php b/CRM/Contact/Form/Inline/ContactName.php
index 1fabfabdd535..2458683ff26f 100644
--- a/CRM/Contact/Form/Inline/ContactName.php
+++ b/CRM/Contact/Form/Inline/ContactName.php
@@ -1,9 +1,9 @@
_contactType;
$class::buildQuickForm($this, 1);
- $this->addFormRule(array('CRM_Contact_Form_Inline_ContactName', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Inline_ContactName', 'formRule'], $this);
}
/**
@@ -63,7 +63,7 @@ public static function formRule($fields, $errors, $form) {
if (empty($fields['first_name']) && empty($fields['last_name'])
&& empty($fields['organization_name'])
&& empty($fields['household_name'])) {
- $emails = civicrm_api3('Email', 'getcount', array('contact_id' => $form->_contactId));
+ $emails = civicrm_api3('Email', 'getcount', ['contact_id' => $form->_contactId]);
if (!$emails) {
$errorField = $form->_contactType == 'Individual' ? 'last' : strtolower($form->_contactType);
$errors[$errorField . '_name'] = ts('Contact with no email must have a name.');
diff --git a/CRM/Contact/Form/Inline/CustomData.php b/CRM/Contact/Form/Inline/CustomData.php
index 418969f183a1..046ff6e4cb6b 100644
--- a/CRM/Contact/Form/Inline/CustomData.php
+++ b/CRM/Contact/Form/Inline/CustomData.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Inline_Email', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Inline_Email', 'formRule'], $this);
}
/**
@@ -119,7 +121,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $errors, $form) {
- $hasData = $hasPrimary = $errors = array();
+ $hasData = $hasPrimary = $errors = [];
if (!empty($fields['email']) && is_array($fields['email'])) {
foreach ($fields['email'] as $instance => $blockValues) {
$dataExists = CRM_Contact_Form_Contact::blockDataExists($blockValues);
@@ -152,7 +154,7 @@ public static function formRule($fields, $errors, $form) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!empty($this->_emails)) {
foreach ($this->_emails as $id => $value) {
$defaults['email'][$id] = $value;
@@ -191,7 +193,7 @@ public function postProcess() {
if ($email['is_primary']) {
CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'display_name', $email['email']);
CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'sort_name', $email['email']);
- $this->ajaxResponse['reloadBlocks'] = array('#crm-contactname-content');
+ $this->ajaxResponse['reloadBlocks'] = ['#crm-contactname-content'];
break;
}
}
diff --git a/CRM/Contact/Form/Inline/IM.php b/CRM/Contact/Form/Inline/IM.php
index 1464c320aed1..89658d42bced 100644
--- a/CRM/Contact/Form/Inline/IM.php
+++ b/CRM/Contact/Form/Inline/IM.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Inline_IM', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Inline_IM', 'formRule']);
}
/**
@@ -102,7 +104,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $errors) {
- $hasData = $hasPrimary = $errors = array();
+ $hasData = $hasPrimary = $errors = [];
if (!empty($fields['im']) && is_array($fields['im'])) {
foreach ($fields['im'] as $instance => $blockValues) {
$dataExists = CRM_Contact_Form_Contact::blockDataExists($blockValues);
@@ -135,7 +137,7 @@ public static function formRule($fields, $errors) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!empty($this->_ims)) {
foreach ($this->_ims as $id => $value) {
$defaults['im'][$id] = $value;
diff --git a/CRM/Contact/Form/Inline/Lock.php b/CRM/Contact/Form/Inline/Lock.php
index be6d6b024d1f..62c94420f5b0 100644
--- a/CRM/Contact/Form/Inline/Lock.php
+++ b/CRM/Contact/Form/Inline/Lock.php
@@ -1,9 +1,9 @@
addElement('hidden', 'oplock_ts', $timestamps['modified_date'], array('id' => 'oplock_ts'));
- $form->addFormRule(array('CRM_Contact_Form_Inline_Lock', 'formRule'), $contactID);
+ $form->addElement('hidden', 'oplock_ts', $timestamps['modified_date'], ['id' => 'oplock_ts']);
+ $form->addFormRule(['CRM_Contact_Form_Inline_Lock', 'formRule'], $contactID);
}
/**
@@ -70,7 +70,7 @@ public static function buildQuickForm(&$form, $contactID) {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $contactID = NULL) {
- $errors = array();
+ $errors = [];
$timestamps = CRM_Contact_BAO_Contact::getTimestamps($contactID);
if ($fields['oplock_ts'] != $timestamps['modified_date']) {
@@ -93,7 +93,7 @@ public static function formRule($fields, $files, $contactID = NULL) {
*/
public static function getResponse($contactID) {
$timestamps = CRM_Contact_BAO_Contact::getTimestamps($contactID);
- return array('oplock_ts' => $timestamps['modified_date']);
+ return ['oplock_ts' => $timestamps['modified_date']];
}
}
diff --git a/CRM/Contact/Form/Inline/OpenID.php b/CRM/Contact/Form/Inline/OpenID.php
index 6d102887a492..399279fd98e1 100644
--- a/CRM/Contact/Form/Inline/OpenID.php
+++ b/CRM/Contact/Form/Inline/OpenID.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Inline_OpenID', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Inline_OpenID', 'formRule']);
}
/**
@@ -102,7 +104,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $errors) {
- $hasData = $hasPrimary = $errors = array();
+ $hasData = $hasPrimary = $errors = [];
if (!empty($fields['openid']) && is_array($fields['openid'])) {
foreach ($fields['openid'] as $instance => $blockValues) {
$dataExists = CRM_Contact_Form_Contact::blockDataExists($blockValues);
@@ -135,7 +137,7 @@ public static function formRule($fields, $errors) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!empty($this->_openids)) {
foreach ($this->_openids as $id => $value) {
$defaults['openid'][$id] = $value;
diff --git a/CRM/Contact/Form/Inline/Phone.php b/CRM/Contact/Form/Inline/Phone.php
index 26872ac827b6..8cd7b6f729b1 100644
--- a/CRM/Contact/Form/Inline/Phone.php
+++ b/CRM/Contact/Form/Inline/Phone.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Inline_Phone', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Inline_Phone', 'formRule']);
}
/**
@@ -102,7 +104,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $errors) {
- $hasData = $hasPrimary = $errors = array();
+ $hasData = $hasPrimary = $errors = [];
if (!empty($fields['phone']) && is_array($fields['phone'])) {
$primaryID = NULL;
foreach ($fields['phone'] as $instance => $blockValues) {
@@ -136,7 +138,7 @@ public static function formRule($fields, $errors) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!empty($this->_phones)) {
foreach ($this->_phones as $id => $value) {
$defaults['phone'][$id] = $value;
diff --git a/CRM/Contact/Form/Inline/Website.php b/CRM/Contact/Form/Inline/Website.php
index 7671a5fd3bad..a90ae37734a7 100644
--- a/CRM/Contact/Form/Inline/Website.php
+++ b/CRM/Contact/Form/Inline/Website.php
@@ -1,9 +1,9 @@
$this->_contactId);
- $values = array();
+ $params = ['contact_id' => $this->_contactId];
+ $values = [];
$this->_websites = CRM_Core_BAO_Website::getValues($params, $values);
}
@@ -87,6 +89,8 @@ public function buildQuickForm() {
CRM_Contact_Form_Edit_Website::buildQuickForm($this, $blockId, TRUE);
}
+ $this->addFormRule(['CRM_Contact_Form_Inline_Website', 'formRule'], $this);
+
}
/**
@@ -95,7 +99,7 @@ public function buildQuickForm() {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (!empty($this->_websites)) {
foreach ($this->_websites as $id => $value) {
$defaults['website'][$id] = $value;
@@ -122,10 +126,44 @@ public function postProcess() {
}
}
// Process / save websites
- CRM_Core_BAO_Website::create($params['website'], $this->_contactId, TRUE);
+ CRM_Core_BAO_Website::process($params['website'], $this->_contactId, TRUE);
$this->log();
$this->response();
}
+ /**
+ * Global validation rules for the form.
+ *
+ * @param array $fields
+ * Posted values of the form.
+ * @param array $errors
+ * List of errors to be posted back to the form.
+ * @param CRM_Contact_Form_Inline_Website $form
+ *
+ * @return array
+ */
+ public static function formRule($fields, $errors, $form) {
+ $hasData = $errors = [];
+ if (!empty($fields['website']) && is_array($fields['website'])) {
+ $types = [];
+ foreach ($fields['website'] as $instance => $blockValues) {
+ $dataExists = CRM_Contact_Form_Contact::blockDataExists($blockValues);
+
+ if ($dataExists) {
+ $hasData[] = $instance;
+ if (!empty($blockValues['website_type_id'])) {
+ if (empty($types[$blockValues['website_type_id']])) {
+ $types[$blockValues['website_type_id']] = $blockValues['website_type_id'];
+ }
+ else {
+ $errors["website[" . $instance . "][website_type_id]"] = ts('Contacts may only have one website of each type at most.');
+ }
+ }
+ }
+ }
+ }
+ return $errors;
+ }
+
}
diff --git a/CRM/Contact/Form/Location.php b/CRM/Contact/Form/Location.php
index eb3cdcbb294f..0f3bd5c63b77 100644
--- a/CRM/Contact/Form/Location.php
+++ b/CRM/Contact/Form/Location.php
@@ -1,9 +1,9 @@
_blocks = array(
+ $form->_blocks = [
'Address' => ts('Address'),
'Email' => ts('Email'),
'Phone' => ts('Phone'),
- );
+ ];
}
$form->assign('blocks', $form->_blocks);
@@ -76,15 +76,14 @@ public static function preProcess(&$form) {
*/
public static function buildQuickForm(&$form) {
// required for subsequent AJAX requests.
- $ajaxRequestBlocks = array();
+ $ajaxRequestBlocks = [];
$generateAjaxRequest = 0;
//build 1 instance of all blocks, without using ajax ...
foreach ($form->_blocks as $blockName => $label) {
- require_once str_replace('_', DIRECTORY_SEPARATOR, 'CRM_Contact_Form_Edit_' . $blockName) . '.php';
$name = strtolower($blockName);
- $instances = array(1);
+ $instances = [1];
if (!empty($_POST[$name]) && is_array($_POST[$name])) {
$instances = array_keys($_POST[$name]);
}
diff --git a/CRM/Contact/Form/Merge.php b/CRM/Contact/Form/Merge.php
index 5a8f5a77c5eb..1434c173f647 100644
--- a/CRM/Contact/Form/Merge.php
+++ b/CRM/Contact/Form/Merge.php
@@ -1,9 +1,9 @@
_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
$this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
$this->limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this, FALSE);
- $urlParams = "reset=1&rgid={$this->_rgid}&gid={$this->_gid}&limit=" . $this->limit;
+ $this->criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $this, FALSE, '{}');
+
+ $urlParams = ['reset' => 1, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
$this->bounceIfInvalid($this->_cid, $this->_oid);
- $this->_contactType = civicrm_api3('Contact', 'getvalue', array(
- 'id' => $this->_cid,
- 'return' => 'contact_type',
- ));
+ $contacts = civicrm_api3('Contact', 'get', [
+ 'id' => ['IN' => [$this->_cid, $this->_oid]],
+ 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
+ ])['values'];
- $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', $urlParams . '&action=browse');
+ $this->_contactType = $contacts[$this->_cid]['contact_type'];
+
+ $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
if (!$this->_rgid) {
// Unset browse URL as we have come from the search screen.
$browseUrl = '';
- $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', array(
+ $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', [
'contact_type' => $this->_contactType,
'used' => 'Supervised',
'return' => 'id',
- ));
+ ]);
}
$this->assign('browseUrl', $browseUrl);
if ($browseUrl) {
CRM_Core_Session::singleton()->pushUserContext($browseUrl);
}
- $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid);
+ $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE));
$join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
$where = "de.id IS NULL";
@@ -113,35 +128,33 @@ public function preProcess() {
$mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
$mainUser = NULL;
if ($mainUfId) {
- // d6 compatible
- if ($config->userSystem->is_drupal == '1') {
- $mainUser = user_load($mainUfId);
- }
- elseif ($config->userFramework == 'Joomla') {
- $mainUser = JFactory::getUser($mainUfId);
- }
-
+ $mainUser = $config->userSystem->getUser($this->_cid);
$this->assign('mainUfId', $mainUfId);
- $this->assign('mainUfName', $mainUser ? $mainUser->name : NULL);
+ $this->assign('mainUfName', $mainUser ? $mainUser['name'] : NULL);
}
-
- $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
- "reset=1&action=update&cid={$this->_oid}&oid={$this->_cid}&rgid={$this->_rgid}&gid={$gid}"
- );
+ $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid, 'oid' => $this->_cid]);
if (!$flip) {
- $flipUrl .= '&flip=1';
+ $flipParams['flip'] = '1';
}
+ $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
+ $flipParams
+ );
$this->assign('flip', $flipUrl);
$this->prev = $this->next = NULL;
- foreach (array(
- 'prev',
- 'next',
- ) as $position) {
+ foreach ([
+ 'prev',
+ 'next',
+ ] as $position) {
if (!empty($pos[$position])) {
if ($pos[$position]['id1'] && $pos[$position]['id2']) {
- $urlParams .= "&cid={$pos[$position]['id1']}&oid={$pos[$position]['id2']}&mergeId={$pos[$position]['mergeId']}&action=update";
- $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
+ $rowParams = array_merge($urlParams, [
+ 'action' => 'update',
+ 'cid' => $pos[$position]['id1'],
+ 'oid' => $pos[$position]['id2'],
+ 'mergeId' => $pos[$position]['mergeId'],
+ ]);
+ $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $rowParams);
$this->assign($position, $this->$position);
}
}
@@ -152,16 +165,9 @@ public function preProcess() {
$otherUser = NULL;
if ($otherUfId) {
- // d6 compatible
- if ($config->userSystem->is_drupal == '1') {
- $otherUser = user_load($otherUfId);
- }
- elseif ($config->userFramework == 'Joomla') {
- $otherUser = JFactory::getUser($otherUfId);
- }
-
+ $otherUser = $config->userSystem->getUser($this->_oid);
$this->assign('otherUfId', $otherUfId);
- $this->assign('otherUfName', $otherUser ? $otherUser->name : NULL);
+ $this->assign('otherUfName', $otherUser ? $otherUser['name'] : NULL);
}
$cmsUser = ($mainUfId && $otherUfId) ? TRUE : FALSE;
@@ -177,11 +183,28 @@ public function preProcess() {
$this->assign('main_cid', $main['contact_id']);
$this->assign('other_cid', $other['contact_id']);
$this->assign('rgid', $this->_rgid);
+ $this->assignSummaryRowsToTemplate($contacts);
- $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
+ $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
$this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
$this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
+ $this->assign('mainContactTypeIcon', CRM_Contact_BAO_Contact_Utils::getImage($contacts[$this->_cid]['contact_sub_type'] ? $contacts[$this->_cid]['contact_sub_type'] : $contacts[$this->_cid]['contact_type'],
+ FALSE,
+ $this->_cid
+ ));
+ $this->assign('otherContactTypeIcon', CRM_Contact_BAO_Contact_Utils::getImage($contacts[$this->_oid]['contact_sub_type'] ? $contacts[$this->_oid]['contact_sub_type'] : $contacts[$this->_oid]['contact_type'],
+ FALSE,
+ $this->_oid
+ ));
+
+ if (isset($rowsElementsAndInfo['rows']['move_contact_type'])) {
+ // We don't permit merging contacts of different types so this is just clutter - putting
+ // the icon next to the contact name is consistent with elsewhere and permits hover-info
+ // https://lab.civicrm.org/dev/core/issues/824
+ unset($rowsElementsAndInfo['rows']['move_contact_type']);
+ }
+
$this->assign('rows', $rowsElementsAndInfo['rows']);
// add elements
@@ -191,16 +214,16 @@ public function preProcess() {
// on the form.
if (substr($element[1], 0, 13) === 'move_location') {
$element[4] = array_merge(
- (array) CRM_Utils_Array::value(4, $element, array()),
- array(
+ (array) CRM_Utils_Array::value(4, $element, []),
+ [
'data-location' => substr($element[1], 14),
'data-is_location' => TRUE,
- ));
+ ]);
}
if (substr($element[1], 0, 15) === 'location_blocks') {
// @todo We could add some data elements here to make jquery manipulation more straight-forward
// @todo consider enabling if it is an add & defaulting to true.
- $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, array()), array('disabled' => TRUE));
+ $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
}
$this->addElement($element[0],
$element[1],
@@ -230,35 +253,36 @@ public function addRules() {
}
public function buildQuickForm() {
- CRM_Utils_System::setTitle(ts('Merge %1 contacts', array(1 => $this->_contactType)));
- $buttons = array();
+ $this->unsavedChangesWarn = FALSE;
+ CRM_Utils_System::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
+ $buttons = [];
- $buttons[] = array(
+ $buttons[] = [
'type' => 'next',
'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
'isDefault' => TRUE,
- 'icon' => $this->next ? 'circle-triangle-e' : 'check',
- );
+ 'icon' => $this->next ? 'fa-play-circle' : 'check',
+ ];
if ($this->next || $this->prev) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'submit',
'name' => ts('Merge and go to Listing'),
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'type' => 'done',
'name' => ts('Merge and View Result'),
'icon' => 'fa-check-circle',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Contact_Form_Merge', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
}
/**
@@ -269,13 +293,13 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
$link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
'civicrm/contact/merge',
'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
);
if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
- $errors['_qf_default'] = ts("The Default Organization contact cannot be merged into another contact record. It is associated with the CiviCRM installation for this domain and contains information used for system functions. If you want to merge these records, you can: %1", array(1 => $link));
+ $errors['_qf_default'] = ts("The Default Organization contact cannot be merged into another contact record. It is associated with the CiviCRM installation for this domain and contains information used for system functions. If you want to merge these records, you can: %1", [1 => $link]);
}
return $errors;
}
@@ -285,30 +309,29 @@ public function postProcess() {
$formValues['main_details'] = $this->_mainDetails;
$formValues['other_details'] = $this->_otherDetails;
- $migrationData = array('migration_info' => $formValues);
+ $migrationData = ['migration_info' => $formValues];
CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
$name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
- $message = '
' . ts('%1 has been updated.', array(1 => $name)) . '
' . ts('Contact ID %1 has been deleted.', array(1 => $this->_oid)) . '
';
+ $message = '
' . ts('%1 has been updated.', [1 => $name]) . '
' . ts('Contact ID %1 has been deleted.', [1 => $this->_oid]) . '
';
CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
- $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
- $urlParams = "reset=1&gid={$this->_gid}&rgid={$this->_rgid}&limit={$this->limit}";
+ $urlParams = ['reset' => 1, 'cid' => $this->_cid, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
+ $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', ['reset' => 1, 'cid' => $this->_cid]);
if (!empty($formValues['_qf_Merge_submit'])) {
- $urlParams .= "&action=update";
- $lisitingURL = CRM_Utils_System::url('civicrm/contact/dedupefind',
+ $urlParams['action'] = "update";
+ CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind',
$urlParams
- );
- CRM_Utils_System::redirect($lisitingURL);
+ ));
}
if (!empty($formValues['_qf_Merge_done'])) {
- CRM_Utils_System::redirect($url);
+ CRM_Utils_System::redirect($contactViewUrl);
}
if ($this->next && $this->_mergeId) {
- $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid);
+ $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE));
$join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
$where = "de.id IS NULL";
@@ -320,12 +343,16 @@ public function postProcess() {
$pos['next']['id2']
) {
- $urlParams .= "&cid={$pos['next']['id1']}&oid={$pos['next']['id2']}&mergeId={$pos['next']['mergeId']}&action=update";
- $url = CRM_Utils_System::url('civicrm/contact/merge', $urlParams);
+ $urlParams['cid'] = $pos['next']['id1'];
+ $urlParams['oid'] = $pos['next']['id2'];
+ $urlParams['mergeId'] = $pos['next']['mergeId'];
+ $urlParams['action'] = 'update';
+ CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/merge', $urlParams));
}
}
- CRM_Utils_System::redirect($url);
+ // Perhaps never reached.
+ CRM_Utils_System::redirect($contactViewUrl);
}
/**
@@ -345,7 +372,7 @@ public function bounceIfInvalid($cid, $oid) {
}
if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
- CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the Dedupe Exceptions page.', array(1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1'))));
+ CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the Dedupe Exceptions page.', [1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1')]));
}
if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
@@ -357,10 +384,40 @@ public function bounceIfInvalid($cid, $oid) {
// ensure that oid is not the current user, if so refuse to do the merge
if (CRM_Core_Session::singleton()->getLoggedInContactID() == $oid) {
$message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
- array(1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName())
+ [1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName()]
);
CRM_Core_Error::statusBounce($message);
}
}
+ /**
+ * Assign the summary_rows variable to the tpl.
+ *
+ * This adds rows to the beginning of the block that will help in making merge choices.
+ *
+ * It can be modified by a hook by altering what is assigned. Although not technically supported this
+ * is an easy tweak with no earth-shattering impacts if later changes stop if from working.
+ *
+ * https://lab.civicrm.org/dev/core/issues/824
+ *
+ * @param array $contacts
+ */
+ protected function assignSummaryRowsToTemplate($contacts) {
+ $mostRecent = ($contacts[$this->_cid]['modified_date'] < $contacts[$this->_oid]['modified_date']) ? $this->_oid : $this->_cid;
+ $this->assign('summary_rows', [
+ [
+ 'name' => 'created_date',
+ 'label' => ts('Created'),
+ 'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['created_date']),
+ 'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['created_date']),
+ ],
+ [
+ 'name' => 'modified_date',
+ 'label' => ts('Last Modified'),
+ 'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['modified_date']) . ($mostRecent == $this->_cid ? ' (' . ts('Most Recent') . ')' : ''),
+ 'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['modified_date']) . ($mostRecent == $this->_oid ? ' (' . ts('Most Recent') . ')' : ''),
+ ],
+ ]);
+ }
+
}
diff --git a/CRM/Contact/Form/RelatedContact.php b/CRM/Contact/Form/RelatedContact.php
index 2f3eede68378..2795870041ad 100644
--- a/CRM/Contact/Form/RelatedContact.php
+++ b/CRM/Contact/Form/RelatedContact.php
@@ -1,9 +1,9 @@
id = $this->_contactId;
if (!$contact->find(TRUE)) {
- CRM_Core_Error::statusBounce(ts('contact does not exist: %1', array(1 => $this->_contactId)));
+ CRM_Core_Error::statusBounce(ts('contact does not exist: %1', [1 => $this->_contactId]));
}
$this->_contactType = $contact->contact_type;
@@ -111,7 +111,7 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
- $params = array();
+ $params = [];
$params['id'] = $params['contact_id'] = $this->_contactId;
$contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_defaults);
@@ -132,17 +132,17 @@ public function buildQuickForm() {
ts('Contact Information')
);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -153,11 +153,11 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$locType = CRM_Core_BAO_LocationType::getDefault();
- foreach (array(
- 'phone',
- 'email',
- 'address',
- ) as $locFld) {
+ foreach ([
+ 'phone',
+ 'email',
+ 'address',
+ ] as $locFld) {
if (!empty($this->_defaults[$locFld]) && $this->_defaults[$locFld][1]['location_type_id']) {
$params[$locFld][1]['is_primary'] = $this->_defaults[$locFld][1]['is_primary'];
$params[$locFld][1]['location_type_id'] = $this->_defaults[$locFld][1]['location_type_id'];
@@ -179,10 +179,10 @@ public function postProcess() {
// set status message.
if ($this->_contactId) {
- $message = ts('%1 has been updated.', array(1 => $contact->display_name));
+ $message = ts('%1 has been updated.', [1 => $contact->display_name]);
}
else {
- $message = ts('%1 has been created.', array(1 => $contact->display_name));
+ $message = ts('%1 has been created.', [1 => $contact->display_name]);
}
CRM_Core_Session::setStatus($message, ts('Contact Saved'), 'success');
}
diff --git a/CRM/Contact/Form/Relationship.php b/CRM/Contact/Form/Relationship.php
index e90727bb0715..1516238bbf77 100644
--- a/CRM/Contact/Form/Relationship.php
+++ b/CRM/Contact/Form/Relationship.php
@@ -1,9 +1,9 @@
assign('display_name_a', $this->_display_name_a);
//get the relationship values.
- $this->_values = array();
+ $this->_values = [];
if ($this->_relationshipId) {
- $params = array('id' => $this->_relationshipId);
+ $params = ['id' => $this->_relationshipId];
CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Relationship', $params, $this->_values);
}
// Check for permissions
- if (in_array($this->_action, array(CRM_Core_Action::ADD, CRM_Core_Action::UPDATE, CRM_Core_Action::DELETE))) {
+ if (in_array($this->_action, [CRM_Core_Action::ADD, CRM_Core_Action::UPDATE, CRM_Core_Action::DELETE])) {
if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)
&& !CRM_Contact_BAO_Contact_Permission::allow($this->_values['contact_id_b'], CRM_Core_Permission::EDIT)) {
CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
@@ -149,19 +155,19 @@ public function preProcess() {
// Set page title based on action
switch ($this->_action) {
case CRM_Core_Action::VIEW:
- CRM_Utils_System::setTitle(ts('View Relationship for %1', array(1 => $this->_display_name_a)));
+ CRM_Utils_System::setTitle(ts('View Relationship for %1', [1 => $this->_display_name_a]));
break;
case CRM_Core_Action::ADD:
- CRM_Utils_System::setTitle(ts('Add Relationship for %1', array(1 => $this->_display_name_a)));
+ CRM_Utils_System::setTitle(ts('Add Relationship for %1', [1 => $this->_display_name_a]));
break;
case CRM_Core_Action::UPDATE:
- CRM_Utils_System::setTitle(ts('Edit Relationship for %1', array(1 => $this->_display_name_a)));
+ CRM_Utils_System::setTitle(ts('Edit Relationship for %1', [1 => $this->_display_name_a]));
break;
case CRM_Core_Action::DELETE:
- CRM_Utils_System::setTitle(ts('Delete Relationship for %1', array(1 => $this->_display_name_a)));
+ CRM_Utils_System::setTitle(ts('Delete Relationship for %1', [1 => $this->_display_name_a]));
break;
}
@@ -178,7 +184,7 @@ public function preProcess() {
}
//get the relationship type id
- $this->_relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $this->_rtypeId);
+ $this->_relationshipTypeId = str_replace(['_a_b', '_b_a'], ['', ''], $this->_rtypeId);
//get the relationship type
if (!$this->_rtype) {
@@ -212,22 +218,17 @@ public function preProcess() {
* Set default values for the form.
*/
public function setDefaultValues() {
-
- $defaults = array();
+ $defaults = [];
if ($this->_action & CRM_Core_Action::UPDATE) {
if (!empty($this->_values)) {
$defaults['relationship_type_id'] = $this->_rtypeId;
- if (!empty($this->_values['start_date'])) {
- list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']);
- }
- if (!empty($this->_values['end_date'])) {
- list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']);
- }
+ $defaults['start_date'] = CRM_Utils_Array::value('start_date', $this->_values);
+ $defaults['end_date'] = CRM_Utils_Array::value('end_date', $this->_values);
$defaults['description'] = CRM_Utils_Array::value('description', $this->_values);
$defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values);
- // The javascript on the form will swap these fields if it is a b_a relationship, so we compensate here
+ // The postprocess function will swap these fields if it is a b_a relationship, so we compensate here
$defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_' . $this->_rtype, $this->_values);
$defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_' . strrev($this->_rtype), $this->_values);
@@ -247,12 +248,12 @@ public function setDefaultValues() {
$this->assign('display_name_b', $this->_display_name_b);
}
- $noteParams = array(
+ $noteParams = [
'entity_id' => $this->_relationshipId,
'entity_table' => 'civicrm_relationship',
'limit' => 1,
'version' => 3,
- );
+ ];
$note = civicrm_api('Note', 'getsingle', $noteParams);
$defaults['note'] = CRM_Utils_Array::value('note', $note);
}
@@ -260,6 +261,7 @@ public function setDefaultValues() {
else {
$defaults['is_active'] = $defaults['is_current_employer'] = 1;
$defaults['relationship_type_id'] = $this->_rtypeId;
+ $defaults['is_permission_a_b'] = $defaults['is_permission_b_a'] = CRM_Contact_BAO_Relationship::NONE;
}
$this->_enabled = $defaults['is_active'];
@@ -270,9 +272,8 @@ public function setDefaultValues() {
* Add the rules for form.
*/
public function addRules() {
-
if (!($this->_action & CRM_Core_Action::DELETE)) {
- $this->addFormRule(array('CRM_Contact_Form_Relationship', 'dateRule'));
+ $this->addFormRule(['CRM_Contact_Form_Relationship', 'dateRule']);
}
}
@@ -281,26 +282,24 @@ public function addRules() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
return;
}
// Select list
$relationshipList = CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId);
- // Metadata needed on clientside
- $this->assign('relationshipData', self::getRelationshipTypeMetadata($relationshipList));
+ $this->assign('contactTypes', CRM_Contact_BAO_ContactType::contactTypeInfo(TRUE));
foreach ($this->_allRelationshipNames as $id => $vals) {
if ($vals['name_a_b'] === 'Employee of') {
@@ -309,10 +308,25 @@ public function buildQuickForm() {
}
}
- $this->addField('relationship_type_id', array('options' => array('' => ts('- select -')) + $relationshipList, 'class' => 'huge', 'placeholder' => '- select -'), TRUE);
+ $this->addField(
+ 'relationship_type_id',
+ [
+ 'options' => ['' => ts('- select -')] + $relationshipList,
+ 'class' => 'huge',
+ 'placeholder' => '- select -',
+ 'option_url' => 'civicrm/admin/reltype',
+ 'option_context' => [
+ 'contact_id' => $this->_contactId,
+ 'relationship_direction' => $this->_rtype,
+ 'relationship_id' => $this->_relationshipId,
+ 'is_form' => TRUE,
+ ],
+ ],
+ TRUE
+ );
$label = $this->_action & CRM_Core_Action::ADD ? ts('Contact(s)') : ts('Contact');
- $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE);
+ $contactField = $this->addField('related_contact_id', ['label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE], TRUE);
// This field cannot be updated
if ($this->_action & CRM_Core_Action::UPDATE) {
$contactField->freeze();
@@ -320,53 +334,55 @@ public function buildQuickForm() {
$this->add('advcheckbox', 'is_current_employer', $this->_contactType == 'Organization' ? ts('Current Employee') : ts('Current Employer'));
- $this->addField('start_date', array('label' => ts('Start Date'), 'formatType' => 'searchDate'));
- $this->addField('end_date', array('label' => ts('End Date'), 'formatType' => 'searchDate'));
+ $this->addField('start_date', ['label' => ts('Start Date')], FALSE, FALSE);
+ $this->addField('end_date', ['label' => ts('End Date')], FALSE, FALSE);
- $this->addField('is_active', array('label' => ts('Enabled?'), 'type' => 'advcheckbox'));
+ $this->addField('is_active', ['label' => ts('Enabled?'), 'type' => 'advcheckbox']);
- $this->addField('is_permission_a_b');
- $this->addField('is_permission_b_a');
+ $this->addField('is_permission_a_b', [], TRUE);
+ $this->addField('is_permission_b_a', [], TRUE);
- $this->addField('description', array('label' => ts('Description')));
+ $this->addField('description', ['label' => ts('Description')]);
CRM_Contact_Form_Edit_Notes::buildQuickForm($this);
if ($this->_action & CRM_Core_Action::VIEW) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
- ),
- ));
+ ],
+ ]);
}
else {
// make this form an upload since we don't know if the custom data injected dynamically is of type file etc.
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save Relationship'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
/**
* This function is called when the form is submitted and also from unit test.
+ *
* @param array $params
*
* @return array
+ * @throws \CRM_Core_Exception
*/
public function submit($params) {
switch ($this->getAction()) {
case CRM_Core_Action::DELETE:
$this->deleteAction($this->_relationshipId);
- return array();
+ return [];
case CRM_Core_Action::UPDATE:
return $this->updateAction($params);
@@ -403,10 +419,13 @@ public function postProcess() {
$this->setEmploymentRelationship($params, $relationshipIds);
// Refresh contact tabs which might have been affected
- $this->ajaxResponse['updateTabs'] = array(
- '#tab_member' => CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId),
- '#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
- );
+ $this->ajaxResponse = [
+ 'reloadBlocks' => ['#crm-contactinfo-content'],
+ 'updateTabs' => [
+ '#tab_member' => CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId),
+ '#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
+ ],
+ ];
}
/**
@@ -419,13 +438,11 @@ public function postProcess() {
* mixed true or array of errors
*/
public static function dateRule($params) {
- $errors = array();
+ $errors = [];
// check start and end date
if (!empty($params['start_date']) && !empty($params['end_date'])) {
- $start_date = CRM_Utils_Date::format(CRM_Utils_Array::value('start_date', $params));
- $end_date = CRM_Utils_Date::format(CRM_Utils_Array::value('end_date', $params));
- if ($start_date && $end_date && (int ) $end_date < (int ) $start_date) {
+ if ($params['end_date'] < $params['start_date']) {
$errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
}
}
@@ -445,28 +462,28 @@ public static function dateRule($params) {
*/
protected function setMessage($outcome) {
if (!empty($outcome['valid']) && empty($outcome['saved'])) {
- CRM_Core_Session::setStatus(ts('Relationship created.', array(
+ CRM_Core_Session::setStatus(ts('Relationship created.', [
'count' => $outcome['valid'],
'plural' => '%count relationships created.',
- )), ts('Saved'), 'success');
+ ]), ts('Saved'), 'success');
}
if (!empty($outcome['invalid'])) {
- CRM_Core_Session::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array(
+ CRM_Core_Session::setStatus(ts('%count relationship record was not created due to an invalid contact type.', [
'count' => $outcome['invalid'],
'plural' => '%count relationship records were not created due to invalid contact types.',
- )), ts('%count invalid relationship record', array(
+ ]), ts('%count invalid relationship record', [
'count' => $outcome['invalid'],
'plural' => '%count invalid relationship records',
- )));
+ ]));
}
if (!empty($outcome['duplicate'])) {
- CRM_Core_Session::setStatus(ts('One relationship was not created because it already exists.', array(
+ CRM_Core_Session::setStatus(ts('One relationship was not created because it already exists.', [
'count' => $outcome['duplicate'],
'plural' => '%count relationships were not created because they already exist.',
- )), ts('%count duplicate relationship', array(
+ ]), ts('%count duplicate relationship', [
'count' => $outcome['duplicate'],
'plural' => '%count duplicate relationships',
- )));
+ ]));
}
if (!empty($outcome['saved'])) {
CRM_Core_Session::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success');
@@ -475,26 +492,27 @@ protected function setMessage($outcome) {
/**
* @param $relationshipList
+ *
* @return array
*/
public static function getRelationshipTypeMetadata($relationshipList) {
$contactTypes = CRM_Contact_BAO_ContactType::contactTypeInfo(TRUE);
$allRelationshipNames = CRM_Core_PseudoConstant::relationshipType('name');
- $jsData = array();
+ $jsData = [];
// Get just what we need to keep the dom small
- $whatWeWant = array_flip(array(
+ $whatWeWant = array_flip([
'contact_type_a',
'contact_type_b',
'contact_sub_type_a',
'contact_sub_type_b',
- ));
+ ]);
foreach ($allRelationshipNames as $id => $vals) {
if (isset($relationshipList["{$id}_a_b"]) || isset($relationshipList["{$id}_b_a"])) {
$jsData[$id] = array_filter(array_intersect_key($allRelationshipNames[$id], $whatWeWant));
// Add user-friendly placeholder
- foreach (array('a', 'b') as $x) {
+ foreach (['a', 'b'] as $x) {
$type = !empty($jsData[$id]["contact_sub_type_$x"]) ? $jsData[$id]["contact_sub_type_$x"] : CRM_Utils_Array::value("contact_type_$x", $jsData[$id]);
- $jsData[$id]["placeholder_$x"] = $type ? ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -');
+ $jsData[$id]["placeholder_$x"] = $type ? ts('- select %1 -', [strtolower($contactTypes[$type]['label'])]) : ts('- select contact -');
}
}
}
@@ -511,7 +529,7 @@ private function deleteAction($id) {
CRM_Contact_BAO_Relationship::del($id);
// reload all blocks to reflect this change on the user interface.
- $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
+ $this->ajaxResponse['reloadBlocks'] = ['#crm-contactinfo-content'];
}
/**
@@ -520,11 +538,10 @@ private function deleteAction($id) {
* @param array $params
*
* @return array
+ * @throws \CRM_Core_Exception
*/
private function updateAction($params) {
- $params = $this->preparePostProcessParameters($params);
- $params = $params[0];
-
+ list($params, $_) = $this->preparePostProcessParameters($params);
try {
civicrm_api3('relationship', 'create', $params);
}
@@ -532,11 +549,8 @@ private function updateAction($params) {
throw new CRM_Core_Exception('Relationship create error ' . $e->getMessage());
}
- $this->clearCurrentEmployer($params);
-
- $this->setMessage(array('saved' => TRUE));
-
- return array($params, array($this->_relationshipId));
+ $this->setMessage(['saved' => TRUE]);
+ return [$params, [$this->_relationshipId]];
}
/**
@@ -545,6 +559,7 @@ private function updateAction($params) {
* @param array $params
*
* @return array
+ * @throws \CRM_Core_Exception
*/
private function createAction($params) {
list($params, $primaryContactLetter) = $this->preparePostProcessParameters($params);
@@ -555,42 +570,36 @@ private function createAction($params) {
$this->setMessage($outcome);
- return array($params, $relationshipIds);
+ return [$params, $relationshipIds];
}
-
/**
* Prepares parameters to be used for create/update actions
*
- * @param array $params
+ * @param array $values
*
* @return array
*/
- private function preparePostProcessParameters($params) {
- $relationshipTypeParts = explode('_', $params['relationship_type_id']);
+ private function preparePostProcessParameters($values) {
+ $params = $values;
+ list($relationshipTypeId, $a, $b) = explode('_', $params['relationship_type_id']);
- $params['relationship_type_id'] = $relationshipTypeParts[0];
- $params['contact_id_' . $relationshipTypeParts[1]] = $this->_contactId;
+ $params['relationship_type_id'] = $relationshipTypeId;
+ $params['contact_id_' . $a] = $this->_contactId;
if (empty($this->_relationshipId)) {
- $params['contact_id_' . $relationshipTypeParts[2]] = explode(',', $params['related_contact_id']);
+ $params['contact_id_' . $b] = explode(',', $params['related_contact_id']);
}
else {
$params['id'] = $this->_relationshipId;
- $params['contact_id_' . $relationshipTypeParts[2]] = $params['related_contact_id'];
-
- foreach (array('start_date', 'end_date') as $dateParam) {
- if (!empty($params[$dateParam])) {
- $params[$dateParam] = CRM_Utils_Date::processDate($params[$dateParam]);
- }
- }
+ $params['contact_id_' . $b] = $params['related_contact_id'];
}
- // CRM-14612 - Don't use adv-checkbox as it interferes with the form js
- $params['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $params, 0);
- $params['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $params, 0);
+ // If this is a b_a relationship these form elements are flipped
+ $params['is_permission_a_b'] = CRM_Utils_Array::value("is_permission_{$a}_{$b}", $values, 0);
+ $params['is_permission_b_a'] = CRM_Utils_Array::value("is_permission_{$b}_{$a}", $values, 0);
- return array($params, $relationshipTypeParts[1]);
+ return [$params, $a];
}
/**
@@ -598,13 +607,15 @@ private function preparePostProcessParameters($params) {
*
* @param array $relationshipIds
* @param string $note
+ *
+ * @throws \CiviCRM_API3_Exception
*/
private function saveRelationshipNotes($relationshipIds, $note) {
foreach ($relationshipIds as $id) {
- $noteParams = array(
+ $noteParams = [
'entity_id' => $id,
'entity_table' => 'civicrm_relationship',
- );
+ ];
$existing = civicrm_api3('note', 'get', $noteParams);
if (!empty($existing['id'])) {
@@ -634,38 +645,19 @@ private function saveRelationshipNotes($relationshipIds, $note) {
* @param array $relationshipIds
*/
private function setEmploymentRelationship($params, $relationshipIds) {
- if (
- !empty($params['is_current_employer']) &&
- $this->_allRelationshipNames[$params['relationship_type_id']]["name_a_b"] == 'Employee of') {
- $employerParams = array();
- foreach ($relationshipIds as $id) {
+ $employerParams = [];
+ foreach ($relationshipIds as $id) {
+ if (!CRM_Contact_BAO_Relationship::isCurrentEmployerNeedingToBeCleared($params, $id)
+ //don't think this is required to check again.
+ && $this->_allRelationshipNames[$params['relationship_type_id']]["name_a_b"] == 'Employee of') {
// Fixme this is dumb why do we have to look this up again?
$rel = CRM_Contact_BAO_Relationship::getRelationshipByID($id);
$employerParams[$rel->contact_id_a] = $rel->contact_id_b;
}
+ }
+ if (!empty($employerParams)) {
// @todo this belongs in the BAO.
CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($employerParams);
- // Refresh contact summary if in ajax mode
- $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
- }
- }
-
- /**
- * Clears the current employer if the relationship type
- * get changed, disabled or 'current employer' checkbox get unchecked.
- *
- * @param $params
- */
- private function clearCurrentEmployer($params) {
- // @todo this belongs in the BAO.
- if ($this->_isCurrentEmployer) {
- $relChanged = $params['relationship_type_id'] != $this->_values['relationship_type_id'];
- if (!$params['is_active'] || !$params['is_current_employer'] || $relChanged) {
- CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['contact_id_a']);
-
- // Refresh contact summary if in ajax mode
- $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
- }
}
}
diff --git a/CRM/Contact/Form/Search.php b/CRM/Contact/Form/Search.php
index 08a5019fd953..297b0f3face6 100644
--- a/CRM/Contact/Form/Search.php
+++ b/CRM/Contact/Form/Search.php
@@ -1,9 +1,9 @@
'Show members of group',
'amtg' => 'Add members to group',
'basic' => 'Basic Search',
@@ -183,7 +184,7 @@ public static function &validContext() {
'builder' => 'Search Builder',
'advanced' => 'Advanced Search',
'custom' => 'Custom Search',
- );
+ ];
}
return self::$_validContext;
}
@@ -199,124 +200,170 @@ public static function isSearchContext($context) {
}
public static function setModeValues() {
- if (!self::$_modeValues) {
- self::$_modeValues = array(
- 1 => array(
- 'selectorName' => self::$_selectorName,
- 'selectorLabel' => ts('Contacts'),
- 'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Contact/Form/Selector.tpl',
- 'resultContext' => NULL,
- 'taskClassName' => 'CRM_Contact_Task',
- ),
- 2 => array(
- 'selectorName' => 'CRM_Contribute_Selector_Search',
- 'selectorLabel' => ts('Contributions'),
- 'taskFile' => 'CRM/common/searchResultTasks.tpl',
- 'taskContext' => 'Contribution',
- 'resultFile' => 'CRM/Contribute/Form/Selector.tpl',
- 'resultContext' => 'Search',
- 'taskClassName' => 'CRM_Contribute_Task',
- ),
- 3 => array(
- 'selectorName' => 'CRM_Event_Selector_Search',
- 'selectorLabel' => ts('Event Participants'),
- 'taskFile' => 'CRM/common/searchResultTasks.tpl',
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Event/Form/Selector.tpl',
- 'resultContext' => 'Search',
- 'taskClassName' => 'CRM_Event_Task',
- ),
- 4 => array(
- 'selectorName' => 'CRM_Activity_Selector_Search',
- 'selectorLabel' => ts('Activities'),
- 'taskFile' => 'CRM/common/searchResultTasks.tpl',
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Activity/Form/Selector.tpl',
- 'resultContext' => 'Search',
- 'taskClassName' => 'CRM_Activity_Task',
- ),
- 5 => array(
- 'selectorName' => 'CRM_Member_Selector_Search',
- 'selectorLabel' => ts('Memberships'),
- 'taskFile' => "CRM/common/searchResultTasks.tpl",
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Member/Form/Selector.tpl',
- 'resultContext' => 'Search',
- 'taskClassName' => 'CRM_Member_Task',
- ),
- 6 => array(
- 'selectorName' => 'CRM_Case_Selector_Search',
- 'selectorLabel' => ts('Cases'),
- 'taskFile' => "CRM/common/searchResultTasks.tpl",
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Case/Form/Selector.tpl',
- 'resultContext' => 'Search',
- 'taskClassName' => 'CRM_Case_Task',
- ),
- 7 => array(
- 'selectorName' => self::$_selectorName,
- 'selectorLabel' => ts('Related Contacts'),
- 'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Contact/Form/Selector.tpl',
- 'resultContext' => NULL,
- 'taskClassName' => 'CRM_Contact_Task',
- ),
- 8 => array(
- 'selectorName' => 'CRM_Mailing_Selector_Search',
- 'selectorLabel' => ts('Mailings'),
- 'taskFile' => "CRM/common/searchResultTasks.tpl",
- 'taskContext' => NULL,
- 'resultFile' => 'CRM/Mailing/Form/Selector.tpl',
- 'resultContext' => 'Search',
- 'taskClassName' => 'CRM_Mailing_Task',
- ),
- );
- }
+ self::$_modeValues = [
+ CRM_Contact_BAO_Query::MODE_CONTACTS => [
+ 'selectorName' => self::$_selectorName,
+ 'selectorLabel' => ts('Contacts'),
+ 'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Contact/Form/Selector.tpl',
+ 'resultContext' => NULL,
+ 'taskClassName' => 'CRM_Contact_Task',
+ 'component' => '',
+ ],
+ CRM_Contact_BAO_Query::MODE_CONTRIBUTE => [
+ 'selectorName' => 'CRM_Contribute_Selector_Search',
+ 'selectorLabel' => ts('Contributions'),
+ 'taskFile' => 'CRM/common/searchResultTasks.tpl',
+ 'taskContext' => 'Contribution',
+ 'resultFile' => 'CRM/Contribute/Form/Selector.tpl',
+ 'resultContext' => 'Search',
+ 'taskClassName' => 'CRM_Contribute_Task',
+ 'component' => 'CiviContribute',
+ ],
+ CRM_Contact_BAO_Query::MODE_EVENT => [
+ 'selectorName' => 'CRM_Event_Selector_Search',
+ 'selectorLabel' => ts('Event Participants'),
+ 'taskFile' => 'CRM/common/searchResultTasks.tpl',
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Event/Form/Selector.tpl',
+ 'resultContext' => 'Search',
+ 'taskClassName' => 'CRM_Event_Task',
+ 'component' => 'CiviEvent',
+ ],
+ CRM_Contact_BAO_Query::MODE_ACTIVITY => [
+ 'selectorName' => 'CRM_Activity_Selector_Search',
+ 'selectorLabel' => ts('Activities'),
+ 'taskFile' => 'CRM/common/searchResultTasks.tpl',
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Activity/Form/Selector.tpl',
+ 'resultContext' => 'Search',
+ 'taskClassName' => 'CRM_Activity_Task',
+ 'component' => 'activity',
+ ],
+ CRM_Contact_BAO_Query::MODE_MEMBER => [
+ 'selectorName' => 'CRM_Member_Selector_Search',
+ 'selectorLabel' => ts('Memberships'),
+ 'taskFile' => "CRM/common/searchResultTasks.tpl",
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Member/Form/Selector.tpl',
+ 'resultContext' => 'Search',
+ 'taskClassName' => 'CRM_Member_Task',
+ 'component' => 'CiviMember',
+ ],
+ CRM_Contact_BAO_Query::MODE_CASE => [
+ 'selectorName' => 'CRM_Case_Selector_Search',
+ 'selectorLabel' => ts('Cases'),
+ 'taskFile' => "CRM/common/searchResultTasks.tpl",
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Case/Form/Selector.tpl',
+ 'resultContext' => 'Search',
+ 'taskClassName' => 'CRM_Case_Task',
+ 'component' => 'CiviCase',
+ ],
+ CRM_Contact_BAO_Query::MODE_CONTACTSRELATED => [
+ 'selectorName' => self::$_selectorName,
+ 'selectorLabel' => ts('Related Contacts'),
+ 'taskFile' => 'CRM/Contact/Form/Search/ResultTasks.tpl',
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Contact/Form/Selector.tpl',
+ 'resultContext' => NULL,
+ 'taskClassName' => 'CRM_Contact_Task',
+ 'component' => 'related_contact',
+ ],
+ CRM_Contact_BAO_Query::MODE_MAILING => [
+ 'selectorName' => 'CRM_Mailing_Selector_Search',
+ 'selectorLabel' => ts('Mailings'),
+ 'taskFile' => "CRM/common/searchResultTasks.tpl",
+ 'taskContext' => NULL,
+ 'resultFile' => 'CRM/Mailing/Form/Selector.tpl',
+ 'resultContext' => 'Search',
+ 'taskClassName' => 'CRM_Mailing_Task',
+ 'component' => 'CiviMail',
+ ],
+ ];
}
/**
+ * Get the metadata for the query mode (this includes task class names)
+ *
* @param int $mode
*
- * @return mixed
+ * @return array
+ * @throws \CRM_Core_Exception
*/
- public static function getModeValue($mode = 1) {
- self::setModeValues();
+ public static function getModeValue($mode = CRM_Contact_BAO_Query::MODE_CONTACTS) {
+ $searchPane = CRM_Utils_Request::retrieve('searchPane', 'String');
+ if (!empty($searchPane)) {
+ $mode = array_search($searchPane, self::getModeToComponentMapping());
+ }
+ self::setModeValues();
if (!array_key_exists($mode, self::$_modeValues)) {
- $mode = 1;
+ $mode = CRM_Contact_BAO_Query::MODE_CONTACTS;
}
return self::$_modeValues[$mode];
}
+ /**
+ * Get a mapping of modes to components.
+ *
+ * This will map the integers to the components. Contact has an empty component
+ * an pseudo-components exist for activity & related_contact.
+ *
+ * @return array
+ */
+ public static function getModeToComponentMapping() {
+ $mapping = [];
+ self::setModeValues();
+
+ foreach (self::$_modeValues as $id => $metadata) {
+ $mapping[$id] = $metadata['component'];
+ }
+ return $mapping;
+ }
+
/**
* @return array
*/
public static function getModeSelect() {
self::setModeValues();
- $select = array();
+ $enabledComponents = CRM_Core_Component::getEnabledComponents();
+ $componentModes = [];
foreach (self::$_modeValues as $id => & $value) {
- $select[$id] = $value['selectorLabel'];
+ if (strpos($value['component'], 'Civi') !== FALSE
+ && !array_key_exists($value['component'], $enabledComponents)
+ ) {
+ continue;
+ }
+ $componentModes[$id] = $value['selectorLabel'];
+ }
+
+ // unset disabled components
+ if (!array_key_exists('CiviMail', $enabledComponents)) {
+ unset($componentModes[CRM_Contact_BAO_Query::MODE_MAILING]);
}
- // unset contributions or participants if user does not have
- // permission on them
+ // unset contributions or participants if user does not have permission on them
if (!CRM_Core_Permission::access('CiviContribute')) {
- unset($select['2']);
+ unset($componentModes[CRM_Contact_BAO_Query::MODE_CONTRIBUTE]);
}
if (!CRM_Core_Permission::access('CiviEvent')) {
- unset($select['3']);
+ unset($componentModes[CRM_Contact_BAO_Query::MODE_EVENT]);
+ }
+
+ if (!CRM_Core_Permission::access('CiviMember')) {
+ unset($componentModes[CRM_Contact_BAO_Query::MODE_MEMBER]);
}
if (!CRM_Core_Permission::check('view all activities')) {
- unset($select['4']);
+ unset($componentModes[CRM_Contact_BAO_Query::MODE_ACTIVITY]);
}
- return $select;
+
+ return $componentModes;
}
/**
@@ -325,26 +372,17 @@ public static function getModeSelect() {
* @return array
*/
public function buildTaskList() {
+ // amtg = 'Add members to group'
if ($this->_context !== 'amtg') {
- $permission = CRM_Core_Permission::getPermission();
-
- if ($this->_componentMode == 1 || $this->_componentMode == 7) {
- $this->_taskList += CRM_Contact_Task::permissionedTaskTitles($permission,
- CRM_Utils_Array::value('deleted_contacts', $this->_formValues)
- );
- }
- else {
- $className = $this->_modeValue['taskClassName'];
- $this->_taskList += $className::permissionedTaskTitles($permission, FALSE);
- }
-
- // Only offer the "Update Smart Group" task if a smart group/saved search is already in play
- if (isset($this->_ssID) && $permission == CRM_Core_Permission::EDIT) {
- $this->_taskList += CRM_Contact_Task::optionalTaskTitle();
+ $taskParams['deletedContacts'] = FALSE;
+ if ($this->_componentMode == CRM_Contact_BAO_Query::MODE_CONTACTS || $this->_componentMode == CRM_Contact_BAO_Query::MODE_CONTACTSRELATED) {
+ $taskParams['deletedContacts'] = CRM_Utils_Array::value('deleted_contacts', $this->_formValues);
}
+ $className = $this->_modeValue['taskClassName'];
+ $taskParams['ssID'] = isset($this->_ssID) ? $this->_ssID : NULL;
+ $this->_taskList += $className::permissionedTaskTitles(CRM_Core_Permission::getPermission(), $taskParams);
}
- asort($this->_taskList);
return $this->_taskList;
}
@@ -353,36 +391,19 @@ public function buildTaskList() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- CRM_Core_Resources::singleton()
- // jsTree is needed for tags popup
- ->addScriptFile('civicrm', 'packages/jquery/plugins/jstree/jquery.jstree.js', 0, 'html-header', FALSE)
- ->addStyleFile('civicrm', 'packages/jquery/plugins/jstree/themes/default/style.css', 0, 'html-header');
- $permission = CRM_Core_Permission::getPermission();
+
// some tasks.. what do we want to do with the selected contacts ?
- $tasks = array();
- if ($this->_componentMode == 1 || $this->_componentMode == 7) {
- $tasks += CRM_Contact_Task::permissionedTaskTitles($permission,
- CRM_Utils_Array::value('deleted_contacts', $this->_formValues)
- );
- }
- else {
- $className = $this->_modeValue['taskClassName'];
- $tasks += $className::permissionedTaskTitles($permission, FALSE);
- }
+ $this->_taskList = $this->buildTaskList();
if (isset($this->_ssID)) {
- if ($permission == CRM_Core_Permission::EDIT) {
- $tasks = $tasks + CRM_Contact_Task::optionalTaskTitle();
- }
-
$search_custom_id
= CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $this->_ssID, 'search_custom_id');
- $savedSearchValues = array(
+ $savedSearchValues = [
'id' => $this->_ssID,
'name' => CRM_Contact_BAO_SavedSearch::getName($this->_ssID, 'title'),
'search_custom_id' => $search_custom_id,
- );
+ ];
$this->assign_by_ref('savedSearch', $savedSearchValues);
$this->assign('ssID', $this->_ssID);
}
@@ -413,7 +434,7 @@ public function buildQuickForm() {
}
// set the group title
- $groupValues = array('id' => $this->_groupID, 'title' => $this->_group[$this->_groupID]);
+ $groupValues = ['id' => $this->_groupID, 'title' => $this->_group[$this->_groupID]];
$this->assign_by_ref('group', $groupValues);
// also set ssID if this is a saved search
@@ -428,10 +449,10 @@ public function buildQuickForm() {
}
// Set dynamic page title for 'Show Members of Group'
- CRM_Utils_System::setTitle(ts('Contacts in Group: %1', array(1 => $this->_group[$this->_groupID])));
+ CRM_Utils_System::setTitle(ts('Contacts in Group: %1', [1 => $this->_group[$this->_groupID]]));
}
- $group_contact_status = array();
+ $group_contact_status = [];
foreach (CRM_Core_SelectValues::groupContactStatus() as $k => $v) {
if (!empty($k)) {
$group_contact_status[] = $this->createElement('checkbox', $k, NULL, $v);
@@ -455,29 +476,29 @@ public function buildQuickForm() {
}
// Set dynamic page title for 'Add Members Group'
- CRM_Utils_System::setTitle(ts('Add to Group: %1', array(1 => $this->_group[$this->_amtgID])));
+ CRM_Utils_System::setTitle(ts('Add to Group: %1', [1 => $this->_group[$this->_amtgID]]));
// also set the group title and freeze the action task with Add Members to Group
- $groupValues = array('id' => $this->_amtgID, 'title' => $this->_group[$this->_amtgID]);
+ $groupValues = ['id' => $this->_amtgID, 'title' => $this->_group[$this->_amtgID]];
$this->assign_by_ref('group', $groupValues);
- $this->add('submit', $this->_actionButtonName, ts('Add Contacts to %1', array(1 => $this->_group[$this->_amtgID])),
- array(
+ $this->add('submit', $this->_actionButtonName, ts('Add Contacts to %1', [1 => $this->_group[$this->_amtgID]]),
+ [
'class' => 'crm-form-submit',
- )
+ ]
);
- $this->add('hidden', 'task', CRM_Contact_Task::GROUP_CONTACTS);
- $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', array('checked' => 'checked'));
+ $this->add('hidden', 'task', CRM_Contact_Task::GROUP_ADD);
+ $selectedRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', ['checked' => 'checked']);
$allRowsRadio = $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all');
$this->assign('ts_sel_id', $selectedRowsRadio->_attributes['id']);
$this->assign('ts_all_id', $allRowsRadio->_attributes['id']);
}
- $selectedContactIds = array();
+ $selectedContactIds = [];
$qfKeyParam = CRM_Utils_Array::value('qfKey', $this->_formValues);
// We use ajax to handle selections only if the search results component_mode is set to "contacts"
- if ($qfKeyParam && ($this->get('component_mode') <= 1 || $this->get('component_mode') == 7)) {
+ if ($qfKeyParam && ($this->get('component_mode') <= CRM_Contact_BAO_Query::MODE_CONTACTS || $this->get('component_mode') == CRM_Contact_BAO_Query::MODE_CONTACTSRELATED)) {
$this->addClass('crm-ajax-selection-form');
$qfKeyParam = "civicrm search {$qfKeyParam}";
- $selectedContactIdsArr = CRM_Core_BAO_PrevNextCache::getSelection($qfKeyParam);
+ $selectedContactIdsArr = Civi::service('prevnext')->getSelection($qfKeyParam);
$selectedContactIds = array_keys($selectedContactIdsArr[$qfKeyParam]);
}
@@ -515,8 +536,8 @@ public function preProcess() {
$this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
$this->_sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', $this);
$this->_ufGroupID = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $this->_componentMode = CRM_Utils_Request::retrieve('component_mode', 'Positive', $this, FALSE, 1, $_REQUEST);
- $this->_operator = CRM_Utils_Request::retrieve('operator', 'String', $this, FALSE, 1, $_REQUEST, 'AND');
+ $this->_componentMode = CRM_Utils_Request::retrieve('component_mode', 'Positive', $this, FALSE, CRM_Contact_BAO_Query::MODE_CONTACTS, $_REQUEST);
+ $this->_operator = CRM_Utils_Request::retrieve('operator', 'String', $this, FALSE, CRM_Contact_BAO_Query::SEARCH_OPERATOR_AND, 'REQUEST');
/**
* set the button names
@@ -535,7 +556,7 @@ public function preProcess() {
}
// assign context to drive the template display, make sure context is valid
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
if (!CRM_Utils_Array::value($this->_context, self::validContext())) {
$this->_context = 'search';
}
@@ -617,23 +638,23 @@ public function preProcess() {
// FIXME: we should generalise in a way that components could inject url-filters
// just like they build their own form elements
- foreach (array(
- 'mailing_id',
- 'mailing_delivery_status',
- 'mailing_open_status',
- 'mailing_click_status',
- 'mailing_reply_status',
- 'mailing_optout',
- 'mailing_forward',
- 'mailing_unsubscribe',
- 'mailing_date_low',
- 'mailing_date_high',
- ) as $mailingFilter) {
+ foreach ([
+ 'mailing_id',
+ 'mailing_delivery_status',
+ 'mailing_open_status',
+ 'mailing_click_status',
+ 'mailing_reply_status',
+ 'mailing_optout',
+ 'mailing_forward',
+ 'mailing_unsubscribe',
+ 'mailing_date_low',
+ 'mailing_date_high',
+ ] as $mailingFilter) {
$type = 'String';
if ($mailingFilter == 'mailing_id' &&
$filterVal = CRM_Utils_Request::retrieve('mailing_id', 'Positive', $this)
) {
- $this->_formValues[$mailingFilter] = array($filterVal);
+ $this->_formValues[$mailingFilter] = [$filterVal];
}
elseif ($filterVal = CRM_Utils_Request::retrieve($mailingFilter, $type, $this)) {
$this->_formValues[$mailingFilter] = $filterVal;
@@ -648,9 +669,9 @@ public function preProcess() {
$this->assign('id',
CRM_Utils_Array::value('uf_group_id', $this->_formValues)
);
- $operator = CRM_Utils_Array::value('operator', $this->_formValues, 'AND');
+ $operator = CRM_Utils_Array::value('operator', $this->_formValues, CRM_Contact_BAO_Query::SEARCH_OPERATOR_AND);
$this->set('queryOperator', $operator);
- if ($operator == 'OR') {
+ if ($operator == CRM_Contact_BAO_Query::SEARCH_OPERATOR_OR) {
$this->assign('operator', ts('OR'));
}
else {
@@ -660,17 +681,16 @@ public function preProcess() {
// show the context menu only when we’re not searching for deleted contacts; CRM-5673
if (empty($this->_formValues['deleted_contacts'])) {
$menuItems = CRM_Contact_BAO_Contact::contextMenu();
- $primaryActions = CRM_Utils_Array::value('primaryActions', $menuItems, array());
- $this->_contextMenu = CRM_Utils_Array::value('moreActions', $menuItems, array());
+ $primaryActions = CRM_Utils_Array::value('primaryActions', $menuItems, []);
+ $this->_contextMenu = CRM_Utils_Array::value('moreActions', $menuItems, []);
$this->assign('contextMenu', $primaryActions + $this->_contextMenu);
}
if (!isset($this->_componentMode)) {
$this->_componentMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
}
- self::setModeValues();
-
self::$_selectorName = $this->_modeValue['selectorName'];
+ self::setModeValues();
$setDynamic = FALSE;
if (strpos(self::$_selectorName, 'CRM_Contact_Selector') !== FALSE) {
@@ -763,7 +783,7 @@ public function postProcess() {
) {
//reset the cache table for new search
$cacheKey = "civicrm search {$this->controller->_key}";
- CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey);
+ Civi::service('prevnext')->deleteItem(NULL, $cacheKey);
}
//get the button name
diff --git a/CRM/Contact/Form/Search/Advanced.php b/CRM/Contact/Form/Search/Advanced.php
index d17106838786..0656d737d63d 100644
--- a/CRM/Contact/Form/Search/Advanced.php
+++ b/CRM/Contact/Form/Search/Advanced.php
@@ -1,9 +1,9 @@
normalizeDefaultValues($defaults);
if ($this->_context === 'amtg') {
- $defaults['task'] = CRM_Contact_Task::GROUP_CONTACTS;
+ $defaults['task'] = CRM_Contact_Task::GROUP_ADD;
}
return $defaults;
@@ -236,9 +237,9 @@ public function postProcess() {
// FIXME: so leaving this as a dependency for now
if (array_key_exists('contribution_amount_low', $this->_formValues)) {
foreach (array(
- 'contribution_amount_low',
- 'contribution_amount_high',
- ) as $f) {
+ 'contribution_amount_low',
+ 'contribution_amount_high',
+ ) as $f) {
$this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
}
}
@@ -269,11 +270,11 @@ public function postProcess() {
!$this->_force
) {
foreach (array(
- 'case_type_id',
- 'case_status_id',
- 'case_deleted',
- 'case_tags',
- ) as $caseCriteria) {
+ 'case_type_id',
+ 'case_status_id',
+ 'case_deleted',
+ 'case_tags',
+ ) as $caseCriteria) {
if (!empty($this->_formValues[$caseCriteria])) {
$allCases = TRUE;
$this->_formValues['case_owner'] = 1;
diff --git a/CRM/Contact/Form/Search/Basic.php b/CRM/Contact/Form/Search/Basic.php
index 460af450a583..9a3386836dbb 100644
--- a/CRM/Contact/Form/Search/Basic.php
+++ b/CRM/Contact/Form/Search/Basic.php
@@ -1,9 +1,9 @@
ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements();
+ $contactTypes = ['' => ts('- any contact type -')] + CRM_Contact_BAO_ContactType::getSelectElements();
$this->add('select', 'contact_type',
ts('is...'),
$contactTypes,
FALSE,
- array('class' => 'crm-select2')
+ ['class' => 'crm-select2']
);
}
@@ -67,22 +67,22 @@ public function buildQuickForm() {
// Get hierarchical listing of groups, respecting ACLs for CRM-16836.
$groupHierarchy = CRM_Contact_BAO_Group::getGroupsHierarchy($this->_group, NULL, ' ', TRUE);
if (!empty($searchOptions['groups'])) {
- $this->addField('group', array(
- 'entity' => 'group_contact',
- 'label' => ts('in'),
- 'placeholder' => ts('- any group -'),
- 'options' => $groupHierarchy,
- ));
+ $this->addField('group', [
+ 'entity' => 'group_contact',
+ 'label' => ts('in'),
+ 'placeholder' => ts('- any group -'),
+ 'options' => $groupHierarchy,
+ ]);
}
if (!empty($searchOptions['tags'])) {
// tag criteria
if (!empty($this->_tag)) {
- $this->addField('tag', array(
- 'entity' => 'entity_tag',
- 'label' => ts('with'),
- 'placeholder' => ts('- any tag -'),
- ));
+ $this->addField('tag', [
+ 'entity' => 'entity_tag',
+ 'label' => ts('with'),
+ 'placeholder' => ts('- any tag -'),
+ ]);
}
}
@@ -97,7 +97,7 @@ public function buildQuickForm() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults['sort_name'] = CRM_Utils_Array::value('sort_name', $this->_formValues);
foreach (self::$csv as $v) {
@@ -111,7 +111,7 @@ public function setDefaultValues() {
}
if ($this->_context === 'amtg') {
- $defaults['task'] = CRM_Contact_Task::GROUP_CONTACTS;
+ $defaults['task'] = CRM_Contact_Task::GROUP_ADD;
}
if ($this->_context === 'smog') {
@@ -125,7 +125,7 @@ public function setDefaultValues() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_Search_Basic', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Search_Basic', 'formRule']);
}
/**
@@ -197,14 +197,16 @@ public function postProcess() {
* If Go is pressed then we must select some checkboxes and an action.
*
* @param array $fields
+ * @param array $files
+ * @param object $form
*
* @return array|bool
*/
- public static function formRule($fields) {
+ public static function formRule($fields, $files, $form) {
// check actionName and if next, then do not repeat a search, since we are going to the next page
if (array_key_exists('_qf_Search_next', $fields)) {
if (empty($fields['task'])) {
- return array('task' => 'Please select a valid action.');
+ return ['task' => 'Please select a valid action.'];
}
if (CRM_Utils_Array::value('task', $fields) == CRM_Contact_Task::SAVE_SEARCH) {
@@ -222,7 +224,7 @@ public static function formRule($fields) {
return TRUE;
}
}
- return array('task' => 'Please select one or more checkboxes to perform the action on.');
+ return ['task' => 'Please select one or more checkboxes to perform the action on.'];
}
return TRUE;
}
@@ -232,6 +234,7 @@ public static function formRule($fields) {
*
* @return string
*/
+
/**
* @return string
*/
diff --git a/CRM/Contact/Form/Search/Builder.php b/CRM/Contact/Form/Search/Builder.php
index b052193a0c72..2a73f11a250f 100644
--- a/CRM/Contact/Form/Search/Builder.php
+++ b/CRM/Contact/Form/Search/Builder.php
@@ -1,9 +1,9 @@
$field) {
- if (strpos($name, '_date') || CRM_Utils_Array::value('data_type', $field) == 'Date') {
- $dateFields[] = $name;
- }
- // it's necessary to know which of the fields are from string data type
- if (isset($field['type']) && $field['type'] === CRM_Utils_Type::T_STRING) {
- $stringFields[] = $name;
- }
+ // Assign date type to respective field name, which will be later used to modify operator list
+ $fieldNameTypes[$name] = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $field));
// it's necessary to know which of the fields are searchable by label
if (isset($field['searchByLabel']) && $field['searchByLabel']) {
$searchByLabelFields[] = $name;
@@ -112,18 +106,16 @@ public function buildQuickForm() {
// Add javascript
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Search/Builder.js', 1, 'html-header')
- ->addSetting(array(
- 'searchBuilder' => array(
+ ->addSetting([
+ 'searchBuilder' => [
// Index of newly added/expanded block (1-based index)
'newBlock' => $this->get('newBlock'),
- 'dateFields' => $dateFields,
'fieldOptions' => self::fieldOptions(),
- 'stringFields' => $stringFields,
'searchByLabelFields' => $searchByLabelFields,
- 'generalOperators' => array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(),
- 'stringOperators' => array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(CRM_Utils_Type::T_STRING),
- ),
- ));
+ 'fieldTypes' => $fieldNameTypes,
+ 'generalOperators' => ['' => ts('-operator-')] + CRM_Core_SelectValues::getSearchBuilderOperators(),
+ ],
+ ]);
//get the saved search mapping id
$mappingId = NULL;
if ($this->_ssID) {
@@ -139,7 +131,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_Search_Builder', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Search_Builder', 'formRule'], $this);
}
/**
@@ -159,7 +151,7 @@ public static function formRule($values, $files, $self) {
$fields = self::fields();
$fld = CRM_Core_BAO_Mapping::formattedFields($values, TRUE);
- $errorMsg = array();
+ $errorMsg = [];
foreach ($fld as $k => $v) {
if (!$v[1]) {
$errorMsg["operator[$v[3]][$v[4]]"] = ts("Please enter the operator.");
@@ -168,19 +160,17 @@ public static function formRule($values, $files, $self) {
// CRM-10338
$v[2] = self::checkArrayKeyEmpty($v[2]);
- if (in_array($v[1], array(
- 'IS NULL',
- 'IS NOT NULL',
- 'IS EMPTY',
- 'IS NOT EMPTY',
- )) &&
- !empty($v[2])
- ) {
- $errorMsg["value[$v[3]][$v[4]]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1]));
+ if (in_array($v[1], [
+ 'IS NULL',
+ 'IS NOT NULL',
+ 'IS EMPTY',
+ 'IS NOT EMPTY',
+ ]) && !empty($v[2])) {
+ $errorMsg["value[$v[3]][$v[4]]"] = ts('Please clear your value if you want to use %1 operator.', [1 => $v[1]]);
}
elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') {
if (isset($v[2])) {
- $v2 = array($v[2]);
+ $v2 = [$v[2]];
if (!isset($v[2])) {
$errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
}
@@ -201,10 +191,10 @@ public static function formRule($values, $files, $self) {
$type = $fields[$fieldKey]['data_type'];
// hack to handle custom data of type state and country
- if (in_array($type, array(
+ if (in_array($type, [
'Country',
'StateProvince',
- ))) {
+ ])) {
$type = "Integer";
}
}
@@ -227,7 +217,7 @@ public static function formRule($values, $files, $self) {
}
// Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL.
elseif (!in_array($v[1],
- array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))
+ ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])
) {
if ((($type == 'Int' || $type == 'Boolean') && !is_array($v[2]) && !trim($v[2])) && $v[2] != '0') {
$errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
@@ -258,7 +248,7 @@ public static function formRule($values, $files, $self) {
// Validate each value in parenthesis to avoid db errors
if (empty($errorMsg)) {
- $parenValues = array();
+ $parenValues = [];
$parenValues = is_array($v[2]) ? (array_key_exists($v[1], $v[2])) ? $v[2][$v[1]] : $v[2] : explode(',', trim($inVal, "(..)"));
foreach ($parenValues as $val) {
if ($type == 'Date' || $type == 'Timestamp') {
@@ -284,6 +274,12 @@ public static function formRule($values, $files, $self) {
}
elseif (trim($v[2])) {
//else check value for rest of the Operators
+ if ($type == 'Date' || $type == 'Timestamp') {
+ $v[2] = CRM_Utils_Date::processDate($v[2]);
+ if ($type == 'Date') {
+ $v[2] = substr($v[2], 0, 8);
+ }
+ }
$error = CRM_Utils_Type::validate($v[2], $type, FALSE);
if ($error != $v[2]) {
$errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
@@ -440,7 +436,7 @@ public static function fields() {
public static function fieldOptions() {
// Hack to add options not retrieved by getfields
// This list could go on and on, but it would be better to fix getfields
- $options = array(
+ $options = [
'group' => 'group_contact',
'tag' => 'entity_tag',
'on_hold' => 'yesno',
@@ -452,8 +448,8 @@ public static function fieldOptions() {
'member_is_test' => 'yesno',
'member_is_pay_later' => 'yesno',
'is_override' => 'yesno',
- );
- $entities = array(
+ ];
+ $entities = [
'contact',
'address',
'activity',
@@ -463,7 +459,7 @@ public static function fieldOptions() {
'contribution',
'case',
'grant',
- );
+ ];
CRM_Contact_BAO_Query_Hook::singleton()->alterSearchBuilderOptions($entities, $options);
foreach ($entities as $entity) {
$fields = civicrm_api3($entity, 'getfields');
@@ -475,13 +471,15 @@ public static function fieldOptions() {
$options[substr($field, 0, -3)] = $entity;
}
}
- elseif (!empty($info['data_type']) && in_array($info['data_type'], array('StateProvince', 'Country'))) {
- $options[$field] = $entity;
+ elseif (!empty($info['data_type'])) {
+ if (in_array($info['data_type'], ['StateProvince', 'Country'])) {
+ $options[$field] = $entity;
+ }
}
- elseif (in_array(substr($field, 0, 3), array(
- 'is_',
- 'do_',
- )) || CRM_Utils_Array::value('data_type', $info) == 'Boolean'
+ elseif (in_array(substr($field, 0, 3), [
+ 'is_',
+ 'do_',
+ ]) || CRM_Utils_Array::value('data_type', $info) == 'Boolean'
) {
$options[$field] = 'yesno';
if ($entity != 'contact') {
diff --git a/CRM/Contact/Form/Search/Criteria.php b/CRM/Contact/Form/Search/Criteria.php
index f876e40e8129..a22d9a95ecc0 100644
--- a/CRM/Contact/Form/Search/Criteria.php
+++ b/CRM/Contact/Form/Search/Criteria.php
@@ -1,9 +1,9 @@
addElement('hidden', 'hidden_basic', 1);
if ($form->_searchOptions['contactType']) {
@@ -42,7 +44,7 @@ public static function basic(&$form) {
if ($contactTypes) {
$form->add('select', 'contact_type', ts('Contact Type(s)'), $contactTypes, FALSE,
- array('id' => 'contact_type', 'multiple' => 'multiple', 'class' => 'crm-select2', 'style' => 'width: 100%;')
+ ['id' => 'contact_type', 'multiple' => 'multiple', 'class' => 'crm-select2', 'style' => 'width: 100%;']
);
}
}
@@ -54,11 +56,11 @@ public static function basic(&$form) {
$groupHierarchy = CRM_Contact_BAO_Group::getGroupsHierarchy($form->_group, NULL, ' ', TRUE);
$form->add('select', 'group', ts('Groups'), $groupHierarchy, FALSE,
- array('id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
$groupOptions = CRM_Core_BAO_OptionValue::getOptionValuesAssocArrayFromName('group_type');
$form->add('select', 'group_type', ts('Group Types'), $groupOptions, FALSE,
- array('id' => 'group_type', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'group_type', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
$form->add('hidden', 'group_search_selected', 'group');
}
@@ -69,8 +71,8 @@ public static function basic(&$form) {
$contactTags = CRM_Core_BAO_Tag::getTags();
if ($contactTags) {
- $form->add('select', 'contact_tags', ts('Tags'), $contactTags, FALSE,
- array('id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2', 'style' => 'width: 100%;')
+ $form->add('select', 'contact_tags', ts('Select Tag(s)'), $contactTags, FALSE,
+ ['id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2', 'style' => 'width: 100%;']
);
}
@@ -78,7 +80,7 @@ public static function basic(&$form) {
CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_contact', NULL, TRUE, FALSE);
$used_for = CRM_Core_OptionGroup::values('tag_used_for');
- $tagsTypes = array();
+ $tagsTypes = [];
$showAllTagTypes = FALSE;
foreach ($used_for as $key => $value) {
//check tags for every type and find if there are any defined
@@ -93,16 +95,16 @@ public static function basic(&$form) {
}
$tagTypesText = implode(" or ", $tagsTypes);
if ($showAllTagTypes) {
- $form->add('checkbox', 'all_tag_types', ts('Include tags used for %1', array(1 => $tagTypesText)));
+ $form->add('checkbox', 'all_tag_types', ts('Include tags used for %1', [1 => $tagTypesText]));
$form->add('hidden', 'tag_types_text', $tagTypesText);
}
}
// add text box for last name, first name, street name, city
- $form->addElement('text', 'sort_name', ts('Find...'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
+ $form->addElement('text', 'sort_name', ts('Complete OR Partial Name'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
// add text box for last name, first name, street name, city
- $form->add('text', 'email', ts('Contact Email'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
+ $form->add('text', 'email', ts('Complete OR Partial Email'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
//added contact source
$form->add('text', 'contact_source', ts('Contact Source'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'contact_source'));
@@ -111,7 +113,7 @@ public static function basic(&$form) {
$form->addElement('text', 'job_title', ts('Job Title'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'job_title'));
//added internal ID
- $form->add('number', 'contact_id', ts('Contact ID'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'id') + array('min' => 1));
+ $form->add('number', 'contact_id', ts('Contact ID'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'id') + ['min' => 1]);
$form->addRule('contact_id', ts('Please enter valid Contact ID'), 'positiveInteger');
//added external ID
@@ -131,16 +133,16 @@ public static function basic(&$form) {
// FIXME: This is probably a part of profiles - need to be
// FIXME: eradicated from here when profiles are reworked.
- $types = array('Participant', 'Contribution', 'Membership');
+ $types = ['Participant', 'Contribution', 'Membership'];
// get component profiles
- $componentProfiles = array();
+ $componentProfiles = [];
$componentProfiles = CRM_Core_BAO_UFGroup::getProfiles($types);
$ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('Search Profile', 1);
$accessibleUfGroups = CRM_Core_Permission::ufGroup(CRM_Core_Permission::VIEW);
- $searchProfiles = array();
+ $searchProfiles = [];
foreach ($ufGroups as $key => $var) {
if (!array_key_exists($key, $componentProfiles) && in_array($key, $accessibleUfGroups)) {
$searchProfiles[$key] = $var['title'];
@@ -150,63 +152,38 @@ public static function basic(&$form) {
$form->add('select',
'uf_group_id',
ts('Views For Display Contacts'),
- array(
+ [
'0' => ts('- default view -'),
- ) + $searchProfiles,
+ ] + $searchProfiles,
FALSE,
- array('class' => 'crm-select2')
+ ['class' => 'crm-select2']
);
$componentModes = CRM_Contact_Form_Search::getModeSelect();
- $enabledComponents = CRM_Core_Component::getEnabledComponents();
-
- // unset disabled components that must should have been enabled
- // to the option be viable
- if (!array_key_exists('CiviMail', $enabledComponents)) {
- unset($componentModes['8']);
- }
-
- // unset contributions or participants if user does not have
- // permission on them
- if (!CRM_Core_Permission::access('CiviContribute')) {
- unset($componentModes['2']);
- }
-
- if (!CRM_Core_Permission::access('CiviEvent')) {
- unset($componentModes['3']);
- }
-
- if (!CRM_Core_Permission::access('CiviMember')) {
- unset($componentModes['5']);
- }
-
- if (!CRM_Core_Permission::check('view all activities')) {
- unset($componentModes['4']);
- }
-
+ $form->assign('component_mappings', json_encode(CRM_Contact_Form_Search::getModeToComponentMapping()));
if (count($componentModes) > 1) {
$form->add('select',
'component_mode',
ts('Display Results As'),
$componentModes,
FALSE,
- array('class' => 'crm-select2')
+ ['class' => 'crm-select2']
);
}
$form->addRadio(
'operator',
ts('Search Operator'),
- array(
- 'AND' => ts('AND'),
- 'OR' => ts('OR'),
- ),
- array('allowClear' => FALSE)
+ [
+ CRM_Contact_BAO_Query::SEARCH_OPERATOR_AND => ts('AND'),
+ CRM_Contact_BAO_Query::SEARCH_OPERATOR_OR => ts('OR'),
+ ],
+ ['allowClear' => FALSE]
);
// add the option to display relationships
$rTypes = CRM_Core_PseudoConstant::relationshipType();
- $rSelect = array('' => ts('- Select Relationship Type-'));
+ $rSelect = ['' => ts('- Select Relationship Type-')];
foreach ($rTypes as $rid => $rValue) {
if ($rValue['label_a_b'] == $rValue['label_b_a']) {
$rSelect[$rid] = $rValue['label_a_b'];
@@ -221,7 +198,7 @@ public static function basic(&$form) {
'display_relationship_type',
ts('Display Results as Relationship'),
$rSelect,
- array('class' => 'crm-select2')
+ ['class' => 'crm-select2']
);
// checkboxes for DO NOT phone, email, mail
@@ -232,47 +209,118 @@ public static function basic(&$form) {
ts('Privacy'),
$t,
FALSE,
- array(
+ [
'id' => 'privacy_options',
'multiple' => 'multiple',
'class' => 'crm-select2',
- )
+ ]
);
$form->addElement('select',
'privacy_operator',
ts('Operator'),
- array(
+ [
'OR' => ts('OR'),
'AND' => ts('AND'),
- )
+ ]
);
- $options = array(
+ $options = [
1 => ts('Exclude'),
2 => ts('Include by Privacy Option(s)'),
- );
- $form->addRadio('privacy_toggle', ts('Privacy Options'), $options, array('allowClear' => FALSE));
+ ];
+ $form->addRadio('privacy_toggle', ts('Privacy Options'), $options, ['allowClear' => FALSE]);
// preferred communication method
-
- $onHold[] = $form->createElement('advcheckbox', 'on_hold', NULL, '');
- $form->addGroup($onHold, 'email_on_hold', ts('Email On Hold'));
+ if (Civi::settings()->get('civimail_multiple_bulk_emails')) {
+ $form->addSelect('email_on_hold',
+ ['entity' => 'email', 'multiple' => 'multiple', 'label' => ts('Email On Hold'), 'options' => CRM_Core_PseudoConstant::emailOnHoldOptions()]);
+ }
+ else {
+ $form->add('advcheckbox', 'email_on_hold', ts('Email On Hold'));
+ }
$form->addSelect('preferred_communication_method',
- array('entity' => 'contact', 'multiple' => 'multiple', 'label' => ts('Preferred Communication Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')));
+ ['entity' => 'contact', 'multiple' => 'multiple', 'label' => ts('Preferred Communication Method'), 'option_url' => NULL, 'placeholder' => ts('- any -')]);
//CRM-6138 Preferred Language
- $form->addSelect('preferred_language', array('class' => 'twenty', 'context' => 'search'));
+ $form->addSelect('preferred_language', ['class' => 'twenty', 'context' => 'search']);
// Phone search
$form->addElement('text', 'phone_numeric', ts('Phone'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone'));
$locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$phoneType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
- $form->add('select', 'phone_location_type_id', ts('Phone Location'), array('' => ts('- any -')) + $locationType, FALSE, array('class' => 'crm-select2'));
- $form->add('select', 'phone_phone_type_id', ts('Phone Type'), array('' => ts('- any -')) + $phoneType, FALSE, array('class' => 'crm-select2'));
+ $form->add('select', 'phone_location_type_id', ts('Phone Location'), ['' => ts('- any -')] + $locationType, FALSE, ['class' => 'crm-select2']);
+ $form->add('select', 'phone_phone_type_id', ts('Phone Type'), ['' => ts('- any -')] + $phoneType, FALSE, ['class' => 'crm-select2']);
}
+ /**
+ * Defines the fields that can be displayed for the basic search section.
+ *
+ * @param CRM_Core_Form $form
+ */
+ protected static function setBasicSearchFields($form) {
+ $userFramework = CRM_Core_Config::singleton()->userFramework;
+
+ $form->assign('basicSearchFields', [
+ 'sort_name' => ['name' => 'sort_name'],
+ 'email' => ['name' => 'email'],
+ 'contact_type' => ['name' => 'contact_type'],
+ 'group' => [
+ 'name' => 'group',
+ 'template' => 'CRM/Contact/Form/Search/Criteria/Fields/group.tpl',
+ ],
+ 'contact_tags' => ['name' => 'contact_tags'],
+ 'tag_types_text' => ['name' => 'tag_types_text'],
+ 'tag_search' => [
+ 'name' => 'tag_search',
+ 'help' => ['id' => 'id-all-tags'],
+ ],
+ 'tag_set' => [
+ 'name' => 'tag_set',
+ 'is_custom' => TRUE,
+ 'template' => 'CRM/Contact/Form/Search/Criteria/Fields/tag_set.tpl',
+ ],
+ 'all_tag_types' => [
+ 'name' => 'all_tag_types',
+ 'class' => 'search-field__span-3 search-field__checkbox',
+ 'help' => ['id' => 'id-all-tag-types'],
+ ],
+ 'phone_numeric' => [
+ 'name' => 'phone_numeric',
+ 'description' => ts('Punctuation and spaces are ignored.'),
+ ],
+ 'phone_location_type_id' => ['name' => 'phone_location_type_id'],
+ 'phone_phone_type_id' => ['name' => 'phone_phone_type_id'],
+ 'privacy_toggle' => [
+ 'name' => 'privacy_toggle',
+ 'class' => 'search-field__span-2',
+ 'template' => 'CRM/Contact/Form/Search/Criteria/Fields/privacy_toggle.tpl',
+ ],
+ 'preferred_communication_method' => [
+ 'name' => 'preferred_communication_method',
+ 'template' => 'CRM/Contact/Form/Search/Criteria/Fields/preferred_communication_method.tpl',
+ ],
+ 'contact_source' => [
+ 'name' => 'contact_source',
+ 'help' => ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact'],
+ ],
+ 'job_title' => ['name' => 'job_title'],
+ 'preferred_language' => ['name' => 'preferred_language'],
+ 'contact_id' => [
+ 'name' => 'contact_id',
+ 'help' => ['id' => 'id-contact-id', 'file' => 'CRM/Contact/Form/Contact'],
+ ],
+ 'external_identifier' => [
+ 'name' => 'external_identifier',
+ 'help' => ['id' => 'id-external-id', 'file' => 'CRM/Contact/Form/Contact'],
+ ],
+ 'uf_user' => [
+ 'name' => 'uf_user',
+ 'description' => ts('Does the contact have a %1 Account?', [$userFramework]),
+ ],
+ ]);
+ }
/**
* @param CRM_Core_Form $form
@@ -295,21 +343,21 @@ public static function location(&$form) {
$attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Address');
- $elements = array(
- 'street_address' => array(ts('Street Address'), $attributes['street_address'], NULL, NULL),
- 'supplemental_address_1' => array(ts('Supplemental Address 1'), $attributes['supplemental_address_1'], NULL, NULL),
- 'supplemental_address_2' => array(ts('Supplemental Address 2'), $attributes['supplemental_address_2'], NULL, NULL),
- 'supplemental_address_3' => array(ts('Supplemental Address 3'), $attributes['supplemental_address_3'], NULL, NULL),
- 'city' => array(ts('City'), $attributes['city'], NULL, NULL),
- 'postal_code' => array(ts('Postal Code'), $attributes['postal_code'], NULL, NULL),
- 'country' => array(ts('Country'), $attributes['country_id'], 'country', FALSE),
- 'state_province' => array(ts('State/Province'), $attributes['state_province_id'], 'stateProvince', TRUE),
- 'county' => array(ts('County'), $attributes['county_id'], 'county', TRUE),
- 'address_name' => array(ts('Address Name'), $attributes['address_name'], NULL, NULL),
- 'street_number' => array(ts('Street Number'), $attributes['street_number'], NULL, NULL),
- 'street_name' => array(ts('Street Name'), $attributes['street_name'], NULL, NULL),
- 'street_unit' => array(ts('Apt/Unit/Suite'), $attributes['street_unit'], NULL, NULL),
- );
+ $elements = [
+ 'street_address' => [ts('Street Address'), $attributes['street_address'], NULL, NULL],
+ 'supplemental_address_1' => [ts('Supplemental Address 1'), $attributes['supplemental_address_1'], NULL, NULL],
+ 'supplemental_address_2' => [ts('Supplemental Address 2'), $attributes['supplemental_address_2'], NULL, NULL],
+ 'supplemental_address_3' => [ts('Supplemental Address 3'), $attributes['supplemental_address_3'], NULL, NULL],
+ 'city' => [ts('City'), $attributes['city'], NULL, NULL],
+ 'postal_code' => [ts('Postal Code'), $attributes['postal_code'], NULL, NULL],
+ 'country' => [ts('Country'), $attributes['country_id'], 'country', FALSE],
+ 'state_province' => [ts('State/Province'), $attributes['state_province_id'], 'stateProvince', TRUE],
+ 'county' => [ts('County'), $attributes['county_id'], 'county', TRUE],
+ 'address_name' => [ts('Address Name'), $attributes['address_name'], NULL, NULL],
+ 'street_number' => [ts('Street Number'), $attributes['street_number'], NULL, NULL],
+ 'street_name' => [ts('Street Name'), $attributes['street_name'], NULL, NULL],
+ 'street_unit' => [ts('Apt/Unit/Suite'), $attributes['street_unit'], NULL, NULL],
+ ];
$parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', $addressOptions, 0);
$form->assign('parseStreetAddress', $parseStreetAddress);
@@ -317,7 +365,7 @@ public static function location(&$form) {
list($title, $attributes, $select, $multiSelect) = $v;
if (in_array($name,
- array('street_number', 'street_name', 'street_unit')
+ ['street_number', 'street_name', 'street_unit']
)) {
if (!$parseStreetAddress) {
continue;
@@ -336,8 +384,8 @@ public static function location(&$form) {
$element = $form->addChainSelect($name);
}
else {
- $selectElements = array('' => ts('- any -')) + CRM_Core_PseudoConstant::$select();
- $element = $form->add('select', $name, $title, $selectElements, FALSE, array('class' => 'crm-select2'));
+ $selectElements = ['' => ts('- any -')] + CRM_Core_PseudoConstant::$select();
+ $element = $form->add('select', $name, $title, $selectElements, FALSE, ['class' => 'crm-select2']);
}
if ($multiSelect) {
$element->setMultiple(TRUE);
@@ -348,34 +396,34 @@ public static function location(&$form) {
}
if ($addressOptions['postal_code']) {
- $attr = array('class' => 'six') + (array) CRM_Utils_Array::value('postal_code', $attributes);
- $form->addElement('text', 'postal_code_low', NULL, $attr + array('placeholder' => ts('From')));
- $form->addElement('text', 'postal_code_high', NULL, $attr + array('placeholder' => ts('To')));
+ $attr = ['class' => 'six'] + (array) CRM_Utils_Array::value('postal_code', $attributes);
+ $form->addElement('text', 'postal_code_low', NULL, $attr + ['placeholder' => ts('From')]);
+ $form->addElement('text', 'postal_code_high', NULL, $attr + ['placeholder' => ts('To')]);
}
}
// extend addresses with proximity search
- if (!empty($config->geocodeMethod)) {
- $form->addElement('text', 'prox_distance', ts('Find contacts within'), array('class' => 'six'));
- $form->addElement('select', 'prox_distance_unit', NULL, array(
+ if (CRM_Utils_GeocodeProvider::getUsableClassName()) {
+ $form->addElement('text', 'prox_distance', ts('Find contacts within'), ['class' => 'six']);
+ $form->addElement('select', 'prox_distance_unit', NULL, [
'miles' => ts('Miles'),
'kilos' => ts('Kilometers'),
- ));
+ ]);
$form->addRule('prox_distance', ts('Please enter positive number as a distance'), 'numeric');
}
- $form->addSelect('world_region', array('entity' => 'address', 'context' => 'search'));
+ $form->addSelect('world_region', ['entity' => 'address', 'context' => 'search']);
// select for location type
$locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
- $form->add('select', 'location_type', ts('Address Location'), $locationType, FALSE, array(
+ $form->add('select', 'location_type', ts('Address Location'), $locationType, FALSE, [
'multiple' => TRUE,
'class' => 'crm-select2',
'placeholder' => ts('Primary'),
- ));
+ ]);
// custom data extending addresses
- CRM_Core_BAO_Query::addCustomFormFields($form, array('Address'));
+ CRM_Core_BAO_Query::addCustomFormFields($form, ['Address']);
}
/**
@@ -395,10 +443,10 @@ public static function changeLog(&$form) {
// block for change log
$form->addElement('text', 'changed_by', ts('Modified By'), NULL);
- $dates = array(1 => ts('Added'), 2 => ts('Modified'));
- $form->addRadio('log_date', NULL, $dates, array('allowClear' => TRUE), ' ');
+ $dates = [1 => ts('Added'), 2 => ts('Modified')];
+ $form->addRadio('log_date', NULL, $dates, ['allowClear' => TRUE]);
- CRM_Core_Form_Date::buildDateRange($form, 'log_date', 1, '_low', '_high', ts('From'), FALSE, FALSE);
+ CRM_Core_Form_Date::buildDateRange($form, 'log_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
}
/**
@@ -414,23 +462,23 @@ public static function task(&$form) {
public static function relationship(&$form) {
$form->add('hidden', 'hidden_relationship', 1);
- $allRelationshipType = array();
+ $allRelationshipType = [];
$allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
- $form->add('select', 'relation_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType, FALSE, array('class' => 'crm-select2'));
+ $form->add('select', 'relation_type_id', ts('Relationship Type'), ['' => ts('- select -')] + $allRelationshipType, FALSE, ['multiple' => TRUE, 'class' => 'crm-select2']);
$form->addElement('text', 'relation_target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
// relation status
- $relStatusOption = array(ts('Active'), ts('Inactive'), ts('All'));
+ $relStatusOption = [ts('Active'), ts('Inactive'), ts('All')];
$form->addRadio('relation_status', ts('Relationship Status'), $relStatusOption);
- $form->setDefaults(array('relation_status' => 0));
+ $form->setDefaults(['relation_status' => 0]);
// relation permission
- $relPermissionOption = array(ts('Any'), ts('Yes'), ts('No'));
- $form->addRadio('relation_permission', ts('Permissioned Relationship?'), $relPermissionOption);
- $form->setDefaults(array('relation_permission' => 0));
+ $allRelationshipPermissions = CRM_Contact_BAO_Relationship::buildOptions('is_permission_a_b');
+ $form->add('select', 'relation_permission', ts('Permissioned Relationship'),
+ ['' => ts('- select -')] + $allRelationshipPermissions, FALSE, ['multiple' => TRUE, 'class' => 'crm-select2']);
//add the target group
if ($form->_group) {
$form->add('select', 'relation_target_group', ts('Target Contact(s) in Group'), $form->_group, FALSE,
- array('id' => 'relation_target_group', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'relation_target_group', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
}
CRM_Core_Form_Date::buildDateRange($form, 'relation_start_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
@@ -442,30 +490,30 @@ public static function relationship(&$form) {
CRM_Core_Form_Date::buildDateRange($form, 'relation_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
// add all the custom searchable fields
- CRM_Core_BAO_Query::addCustomFormFields($form, array('Relationship'));
+ CRM_Core_BAO_Query::addCustomFormFields($form, ['Relationship']);
}
/**
- * @param $form
+ * @param CRM_Core_Form_Search $form
*/
public static function demographics(&$form) {
$form->add('hidden', 'hidden_demographics', 1);
// radio button for gender
- $genderOptions = array();
+ $genderOptions = [];
$gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
foreach ($gender as $key => $var) {
$genderOptions[$key] = $form->createElement('radio', NULL,
ts('Gender'), $var, $key,
- array('id' => "civicrm_gender_{$var}_{$key}")
+ ['id' => "civicrm_gender_{$var}_{$key}"]
);
}
$form->addGroup($genderOptions, 'gender_id', ts('Gender'))->setAttribute('allowClear', TRUE);
- $form->add('text', 'age_low', ts('Min Age'), array('size' => 6));
+ $form->add('number', 'age_low', ts('Min Age'), ['class' => 'four', 'min' => 0]);
$form->addRule('age_low', ts('Please enter a positive integer'), 'positiveInteger');
- $form->add('text', 'age_high', ts('Max Age'), array('size' => 6));
+ $form->add('number', 'age_high', ts('Max Age'), ['class' => 'four', 'min' => 0]);
$form->addRule('age_high', ts('Please enter a positive integer'), 'positiveInteger');
- $form->addDate('age_asof_date', ts('Age as of Date'), FALSE, array('formatType' => 'searchDate'));
+ $form->add('datepicker', 'age_asof_date', ts('As of'), NULL, FALSE, ['time' => FALSE]);
CRM_Core_Form_Date::buildDateRange($form, 'birth_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
@@ -481,16 +529,16 @@ public static function demographics(&$form) {
public static function notes(&$form) {
$form->add('hidden', 'hidden_notes', 1);
- $options = array(
+ $options = [
2 => ts('Body Only'),
3 => ts('Subject Only'),
6 => ts('Both'),
- );
+ ];
$form->addRadio('note_option', '', $options);
$form->addElement('text', 'note', ts('Note Text'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
- $form->setDefaults(array('note_option' => 6));
+ $form->setDefaults(['note_option' => 6]);
}
/**
@@ -500,7 +548,7 @@ public static function notes(&$form) {
*/
public static function custom(&$form) {
$form->add('hidden', 'hidden_custom', 1);
- $extends = array_merge(array('Contact', 'Individual', 'Household', 'Organization'),
+ $extends = array_merge(['Contact', 'Individual', 'Household', 'Organization'],
CRM_Contact_BAO_ContactType::subTypes()
);
$groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE,
diff --git a/CRM/Contact/Form/Search/Custom.php b/CRM/Contact/Form/Search/Custom.php
index e82d7ad71f2c..fad711ba9017 100644
--- a/CRM/Contact/Form/Search/Custom.php
+++ b/CRM/Contact/Form/Search/Custom.php
@@ -1,9 +1,9 @@
_customClass = new $this->_customSearchClass($this->_formValues);
+ $this->addFormRule(array($this->_customClass, 'formRule'), $this);
+
// CRM-12747
if (isset($this->_customClass->_permissionedComponent) &&
!self::isPermissioned($this->_customClass->_permissionedComponent)
@@ -91,6 +93,13 @@ public function preProcess() {
}
}
+ /**
+ * Add local and global form rules.
+ */
+ public function addRules() {
+ $this->addFormRule(array($this->_customClass, 'formRule'));
+ }
+
/**
* Set the default values of various form elements.
*
@@ -127,6 +136,7 @@ public function buildQuickForm() {
*
* @return string
*/
+
/**
* @return string
*/
diff --git a/CRM/Contact/Form/Search/Custom/ActivitySearch.php b/CRM/Contact/Form/Search/Custom/ActivitySearch.php
index 066da42b7aab..afda78618c2c 100644
--- a/CRM/Contact/Form/Search/Custom/ActivitySearch.php
+++ b/CRM/Contact/Form/Search/Custom/ActivitySearch.php
@@ -1,9 +1,9 @@
_formValues = $formValues;
+ $this->_formValues = self::formatSavedSearchFields($formValues);
/**
* Define the columns for search result rows
*/
- $this->_columns = array(
+ $this->_columns = [
ts('Name') => 'sort_name',
ts('Status') => 'activity_status',
ts('Activity Type') => 'activity_type',
@@ -61,7 +61,7 @@ public function __construct(&$formValues) {
ts('Duration') => 'duration',
ts('Details') => 'details',
ts('Assignee') => 'assignee',
- );
+ ];
$this->_groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
'activity_status',
@@ -107,7 +107,7 @@ public function buildForm(&$form) {
);
// Select box for Activity Type
- $activityType = array('' => ' - select activity - ') + CRM_Core_PseudoConstant::activityType();
+ $activityType = ['' => ' - select activity - '] + CRM_Core_PseudoConstant::activityType();
$form->add('select', 'activity_type_id', ts('Activity Type'),
$activityType,
@@ -115,7 +115,7 @@ public function buildForm(&$form) {
);
// textbox for Activity Status
- $activityStatus = array('' => ' - select status - ') + CRM_Core_PseudoConstant::activityStatus();
+ $activityStatus = ['' => ' - select status - '] + CRM_Core_PseudoConstant::activityStatus();
$form->add('select', 'activity_status_id', ts('Activity Status'),
$activityStatus,
@@ -123,8 +123,8 @@ public function buildForm(&$form) {
);
// Activity Date range
- $form->addDate('start_date', ts('Activity Date From'), FALSE, array('formatType' => 'custom'));
- $form->addDate('end_date', ts('...through'), FALSE, array('formatType' => 'custom'));
+ $form->add('datepicker', 'start_date', ts('Activity Date From'), [], FALSE, ['time' => FALSE]);
+ $form->add('datepicker', 'end_date', ts('...through'), [], FALSE, ['time' => FALSE]);
// Contact Name field
$form->add('text', 'sort_name', ts('Contact Name'));
@@ -133,7 +133,7 @@ public function buildForm(&$form) {
* If you are using the sample template, this array tells the template fields to render
* for the search form.
*/
- $form->assign('elements', array(
+ $form->assign('elements', [
'contact_type',
'activity_subject',
'activity_type_id',
@@ -141,7 +141,7 @@ public function buildForm(&$form) {
'start_date',
'end_date',
'sort_name',
- ));
+ ]);
}
/**
@@ -296,7 +296,7 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $clauses = array();
+ $clauses = [];
// add contact name search; search on primary name, source contact, assignee
$contactname = $this->_formValues['sort_name'];
@@ -328,26 +328,16 @@ public function where($includeContactIDs = FALSE) {
$clauses[] = "activity.activity_type_id = {$this->_formValues['activity_type_id']}";
}
- $startDate = $this->_formValues['start_date'];
- if (!empty($startDate)) {
- $startDate .= '00:00:00';
- $startDateFormatted = CRM_Utils_Date::processDate($startDate);
- if ($startDateFormatted) {
- $clauses[] = "activity.activity_date_time >= $startDateFormatted";
- }
+ if (!empty($this->_formValues['start_date'])) {
+ $clauses[] = "activity.activity_date_time >= '{$this->_formValues['start_date']} 00:00:00'";
}
- $endDate = $this->_formValues['end_date'];
- if (!empty($endDate)) {
- $endDate .= '23:59:59';
- $endDateFormatted = CRM_Utils_Date::processDate($endDate);
- if ($endDateFormatted) {
- $clauses[] = "activity.activity_date_time <= $endDateFormatted";
- }
+ if (!empty($this->_formValues['end_date'])) {
+ $clauses[] = "activity.activity_date_time <= '{$this->_formValues['end_date']} 23:59:59'";
}
if ($includeContactIDs) {
- $contactIDs = array();
+ $contactIDs = [];
foreach ($this->_formValues as $id => $value) {
if ($value &&
substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX
@@ -429,4 +419,28 @@ public function buildACLClause($tableAlias = 'contact') {
list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
}
+ /**
+ * Format saved search fields for this custom group.
+ *
+ * Note this is a function to facilitate the transition to jcalendar for
+ * saved search groups. In time it can be stripped out again.
+ *
+ * @param array $formValues
+ *
+ * @return array
+ */
+ public static function formatSavedSearchFields($formValues) {
+ $dateFields = [
+ 'start_date',
+ 'end_date',
+ ];
+ foreach ($formValues as $element => $value) {
+ if (in_array($element, $dateFields) && !empty($value)) {
+ $formValues[$element] = date('Y-m-d', strtotime($value));
+ }
+ }
+
+ return $formValues;
+ }
+
}
diff --git a/CRM/Contact/Form/Search/Custom/Base.php b/CRM/Contact/Form/Search/Custom/Base.php
index 19c1a91a4df4..b4edd5986d43 100644
--- a/CRM/Contact/Form/Search/Custom/Base.php
+++ b/CRM/Contact/Form/Search/Custom/Base.php
@@ -1,9 +1,9 @@
$value) {
if ($value &&
substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX
@@ -200,17 +200,17 @@ public function addSortOffset(&$sql, $offset, $rowcount, $sort) {
* @throws Exception
*/
public function validateUserSQL(&$sql, $onlyWhere = FALSE) {
- $includeStrings = array('contact_a');
- $excludeStrings = array('insert', 'delete', 'update');
+ $includeStrings = ['contact_a'];
+ $excludeStrings = ['insert', 'delete', 'update'];
if (!$onlyWhere) {
- $includeStrings += array('select', 'from', 'where', 'civicrm_contact');
+ $includeStrings += ['select', 'from', 'where', 'civicrm_contact'];
}
foreach ($includeStrings as $string) {
if (stripos($sql, $string) === FALSE) {
CRM_Core_Error::fatal(ts('Could not find \'%1\' string in SQL clause.',
- array(1 => $string)
+ [1 => $string]
));
}
}
@@ -218,7 +218,7 @@ public function validateUserSQL(&$sql, $onlyWhere = FALSE) {
foreach ($excludeStrings as $string) {
if (preg_match('/(\s' . $string . ')|(' . $string . '\s)/i', $sql)) {
CRM_Core_Error::fatal(ts('Found illegal \'%1\' string in SQL clause.',
- array(1 => $string)
+ [1 => $string]
));
}
}
@@ -257,4 +257,18 @@ public function setTitle($title) {
}
}
+ /**
+ * Validate form input.
+ *
+ * @param array $fields
+ * @param array $files
+ * @param CRM_Core_Form $self
+ *
+ * @return array
+ * Input errors from the form.
+ */
+ public function formRule($fields, $files, $self) {
+ return [];
+ }
+
}
diff --git a/CRM/Contact/Form/Search/Custom/Basic.php b/CRM/Contact/Form/Search/Custom/Basic.php
index f5028b0f2658..63a55860c0d7 100644
--- a/CRM/Contact/Form/Search/Custom/Basic.php
+++ b/CRM/Contact/Form/Search/Custom/Basic.php
@@ -1,9 +1,9 @@
_columns = array(
+ $this->_columns = [
'' => 'contact_type',
ts('Name') => 'sort_name',
ts('Address') => 'street_address',
@@ -54,10 +54,10 @@ public function __construct(&$formValues) {
ts('Country') => 'country',
ts('Email') => 'email',
ts('Phone') => 'phone',
- );
+ ];
$params = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
- $returnProperties = array();
+ $returnProperties = [];
$returnProperties['contact_sub_type'] = 1;
$addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
@@ -65,14 +65,13 @@ public function __construct(&$formValues) {
);
foreach ($this->_columns as $name => $field) {
- if (in_array($field, array(
- 'street_address',
- 'city',
- 'state_province',
- 'postal_code',
- 'country',
- )) && empty($addressOptions[$field])
- ) {
+ if (in_array($field, [
+ 'street_address',
+ 'city',
+ 'state_province',
+ 'postal_code',
+ 'country',
+ ]) && empty($addressOptions[$field])) {
unset($this->_columns[$name]);
continue;
}
@@ -88,21 +87,21 @@ public function __construct(&$formValues) {
* @param CRM_Core_Form $form
*/
public function buildForm(&$form) {
- $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements();
- $form->add('select', 'contact_type', ts('Find...'), $contactTypes, FALSE, array('class' => 'crm-select2 huge'));
+ $contactTypes = ['' => ts('- any contact type -')] + CRM_Contact_BAO_ContactType::getSelectElements();
+ $form->add('select', 'contact_type', ts('Find...'), $contactTypes, FALSE, ['class' => 'crm-select2 huge']);
// add select for groups
- $group = array('' => ts('- any group -')) + CRM_Core_PseudoConstant::nestedGroup();
- $form->addElement('select', 'group', ts('in'), $group, array('class' => 'crm-select2 huge'));
+ $group = ['' => ts('- any group -')] + CRM_Core_PseudoConstant::nestedGroup();
+ $form->addElement('select', 'group', ts('in'), $group, ['class' => 'crm-select2 huge']);
// add select for categories
- $tag = array('' => ts('- any tag -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
- $form->addElement('select', 'tag', ts('Tagged'), $tag, array('class' => 'crm-select2 huge'));
+ $tag = ['' => ts('- any tag -')] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
+ $form->addElement('select', 'tag', ts('Tagged'), $tag, ['class' => 'crm-select2 huge']);
// text for sort_name
$form->add('text', 'sort_name', ts('Name'));
- $form->assign('elements', array('sort_name', 'contact_type', 'group', 'tag'));
+ $form->assign('elements', ['sort_name', 'contact_type', 'group', 'tag']);
}
/**
diff --git a/CRM/Contact/Form/Search/Custom/ContribSYBNT.php b/CRM/Contact/Form/Search/Custom/ContribSYBNT.php
index 5af0eefca4fd..326388909005 100644
--- a/CRM/Contact/Form/Search/Custom/ContribSYBNT.php
+++ b/CRM/Contact/Form/Search/Custom/ContribSYBNT.php
@@ -1,9 +1,9 @@
_formValues = $formValues;
+ $this->_formValues = self::formatSavedSearchFields($formValues);
$this->_permissionedComponent = 'CiviContribute';
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Name') => 'display_name',
ts('Contribution Count') => 'donation_count',
ts('Contribution Amount') => 'donation_amount',
- );
+ ];
- $this->_amounts = array(
+ $this->_amounts = [
'min_amount_1' => ts('Min Amount One'),
'max_amount_1' => ts('Max Amount One'),
'min_amount_2' => ts('Min Amount Two'),
'max_amount_2' => ts('Max Amount Two'),
'exclude_min_amount' => ts('Exclusion Min Amount'),
'exclude_max_amount' => ts('Exclusion Max Amount'),
- );
+ ];
- $this->_dates = array(
+ $this->_dates = [
'start_date_1' => ts('Start Date One'),
'end_date_1' => ts('End Date One'),
'start_date_2' => ts('Start Date Two'),
'end_date_2' => ts('End Date Two'),
'exclude_start_date' => ts('Exclusion Start Date'),
'exclude_end_date' => ts('Exclusion End Date'),
- );
+ ];
- $this->_checkboxes = array('is_first_amount' => ts('First Donation?'));
+ $this->_checkboxes = ['is_first_amount' => ts('First Donation?')];
foreach ($this->_amounts as $name => $title) {
$this->{$name} = CRM_Utils_Array::value($name, $this->_formValues);
@@ -83,7 +83,7 @@ public function __construct(&$formValues) {
foreach ($this->_dates as $name => $title) {
if (!empty($this->_formValues[$name])) {
- $this->{$name} = CRM_Utils_Date::processDate($this->_formValues[$name]);
+ $this->{$name} = $this->_formValues[$name];
}
}
}
@@ -101,7 +101,7 @@ public function buildForm(&$form) {
}
foreach ($this->_dates as $name => $title) {
- $form->addDate($name, $title, FALSE, array('formatType' => 'custom'));
+ $form->add('datepicker', $name, $title, [], FALSE, ['time' => FALSE]);
}
foreach ($this->_checkboxes as $name => $title) {
@@ -192,10 +192,8 @@ public function all(
";
if ($justIDs) {
- CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS CustomSearch_SYBNT_temp");
- $query = "CREATE TEMPORARY TABLE CustomSearch_SYBNT_temp AS ({$sql})";
- $dao = CRM_Core_DAO::executeQuery($query);
- $sql = "SELECT contact_a.id as contact_id FROM CustomSearch_SYBNT_temp as contact_a";
+ $tempTable = CRM_Utils_SQL_TempTable::build()->createWithQuery($sql);
+ $sql = "SELECT contact_a.id as contact_id FROM {$tempTable->getName()} as contact_a";
}
return $sql;
}
@@ -243,25 +241,25 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $clauses = array();
+ $clauses = [];
if (!empty($this->start_date_1)) {
- $clauses[] = "contrib_1.receive_date >= {$this->start_date_1}";
+ $clauses[] = CRM_Core_DAO::composeQuery('contrib_1.receive_date >= %1', [1 => [$this->start_date_1, 'String']]);
}
if (!empty($this->end_date_1)) {
- $clauses[] = "contrib_1.receive_date <= {$this->end_date_1}";
+ $clauses[] = CRM_Core_DAO::composeQuery('contrib_1.receive_date <= %1', [1 => [$this->end_date_1, 'String']]);
}
if (!empty($this->start_date_2) || !empty($this->end_date_2)) {
$clauses[] = "contrib_2.is_test = 0";
if (!empty($this->start_date_2)) {
- $clauses[] = "contrib_2.receive_date >= {$this->start_date_2}";
+ $clauses[] = CRM_Core_DAO::composeQuery('contrib_2.receive_date >= %1', [1 => [$this->start_date_2, 'String']]);
}
if (!empty($this->end_date_2)) {
- $clauses[] = "contrib_2.receive_date <= {$this->end_date_2}";
+ $clauses[] = CRM_Core_DAO::composeQuery('contrib_2.receive_date <= %1', [1 => [$this->end_date_2, 'String']]);
}
}
@@ -277,13 +275,13 @@ public function where($includeContactIDs = FALSE) {
$sql = "CREATE TEMPORARY TABLE XG_CustomSearch_SYBNT ( contact_id int primary key) ENGINE=HEAP";
CRM_Core_DAO::executeQuery($sql);
- $excludeClauses = array();
+ $excludeClauses = [];
if ($this->exclude_start_date) {
- $excludeClauses[] = "c.receive_date >= {$this->exclude_start_date}";
+ $excludeClauses[] = CRM_Core_DAO::composeQuery('c.receive_date >= %1', [1 => [$this->exclude_start_date, 'String']]);
}
if ($this->exclude_end_date) {
- $excludeClauses[] = "c.receive_date <= {$this->exclude_end_date}";
+ $excludeClauses[] = CRM_Core_DAO::composeQuery('c.receive_date <= %1', [1 => [$this->exclude_end_date, 'String']]);
}
$excludeClause = NULL;
@@ -291,7 +289,7 @@ public function where($includeContactIDs = FALSE) {
$excludeClause = ' AND ' . implode(' AND ', $excludeClauses);
}
- $having = array();
+ $having = [];
if ($this->exclude_min_amount) {
$having[] = "sum(c.total_amount) >= {$this->exclude_min_amount}";
}
@@ -317,7 +315,7 @@ public function where($includeContactIDs = FALSE) {
$havingClause
";
- $dao = CRM_Core_DAO::executeQuery($query);
+ CRM_Core_DAO::executeQuery($query);
}
// now ensure we dont consider donors that are not first time
@@ -329,7 +327,7 @@ public function where($includeContactIDs = FALSE) {
WHERE c.is_test = 0
AND c.receive_date < {$this->start_date_1}
";
- $dao = CRM_Core_DAO::executeQuery($query);
+ CRM_Core_DAO::executeQuery($query);
}
$clauses[] = " xg.contact_id IS NULL ";
@@ -346,7 +344,7 @@ public function where($includeContactIDs = FALSE) {
* @return string
*/
public function having($includeContactIDs = FALSE) {
- $clauses = array();
+ $clauses = [];
$min = CRM_Utils_Array::value('min_amount', $this->_formValues);
if ($min) {
$clauses[] = "sum(contrib_1.total_amount) >= $min";
@@ -400,4 +398,32 @@ public function buildACLClause($tableAlias = 'contact') {
list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
}
+ /**
+ * Format saved search fields for this custom group.
+ *
+ * Note this is a function to facilitate the transition to jcalendar for
+ * saved search groups. In time it can be stripped out again.
+ *
+ * @param array $formValues
+ *
+ * @return array
+ */
+ public static function formatSavedSearchFields($formValues) {
+ $dateFields = [
+ 'start_date_1',
+ 'end_date_1',
+ 'start_date_2',
+ 'end_date_2',
+ 'exclude_start_date',
+ 'exclude_end_date',
+ ];
+ foreach ($formValues as $element => $value) {
+ if (in_array($element, $dateFields) && !empty($value)) {
+ $formValues[$element] = date('Y-m-d', strtotime($value));
+ }
+ }
+
+ return $formValues;
+ }
+
}
diff --git a/CRM/Contact/Form/Search/Custom/ContributionAggregate.php b/CRM/Contact/Form/Search/Custom/ContributionAggregate.php
index db14a49ea737..f776f8448e2d 100644
--- a/CRM/Contact/Form/Search/Custom/ContributionAggregate.php
+++ b/CRM/Contact/Form/Search/Custom/ContributionAggregate.php
@@ -1,9 +1,9 @@
_formValues = $formValues;
// Define the columns for search result rows
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Name') => 'sort_name',
ts('Contribution Count') => 'donation_count',
ts('Contribution Amount') => 'donation_amount',
- );
+ ];
// define component access permission needed
$this->_permissionedComponent = 'CiviContribute';
@@ -86,14 +86,14 @@ public function buildForm(&$form) {
CRM_Core_Form_Date::buildDateRange($form, 'contribution_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE);
$form->addSelect('financial_type_id',
- array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search')
+ ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search']
);
/**
* If you are using the sample template, this array tells the template fields to render
* for the search form.
*/
- $form->assign('elements', array('min_amount', 'max_amount'));
+ $form->assign('elements', ['min_amount', 'max_amount']);
}
/**
@@ -195,16 +195,22 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $clauses = array(
+ $clauses = [
"contrib.contact_id = contact_a.id",
"contrib.is_test = 0",
- );
+ ];
+
+ foreach ([
+ 'contribution_date_relative',
+ 'contribution_date_low',
+ 'contribution_date_high',
+ ] as $dateFieldName) {
+ $dateParams[$dateFieldName] = CRM_Utils_Array::value(
+ $dateFieldName,
+ $this->_formValues
+ );
+ }
- $dateParams = array(
- 'contribution_date_relative' => $this->_formValues['contribution_date_relative'],
- 'contribution_date_low' => $this->_formValues['contribution_date_low'],
- 'contribution_date_high' => $this->_formValues['contribution_date_high'],
- );
foreach (CRM_Contact_BAO_Query::convertFormValues($dateParams) as $values) {
list($name, $op, $value) = $values;
if (strstr($name, '_low')) {
@@ -216,7 +222,7 @@ public function where($includeContactIDs = FALSE) {
}
if ($includeContactIDs) {
- $contactIDs = array();
+ $contactIDs = [];
foreach ($this->_formValues as $id => $value) {
if ($value &&
substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX
@@ -248,7 +254,7 @@ public function where($includeContactIDs = FALSE) {
* @return string
*/
public function having($includeContactIDs = FALSE) {
- $clauses = array();
+ $clauses = [];
$min = CRM_Utils_Array::value('min_amount', $this->_formValues);
if ($min) {
$min = CRM_Utils_Rule::cleanMoney($min);
diff --git a/CRM/Contact/Form/Search/Custom/DateAdded.php b/CRM/Contact/Form/Search/Custom/DateAdded.php
index 04a392cda569..27c954641238 100644
--- a/CRM/Contact/Form/Search/Custom/DateAdded.php
+++ b/CRM/Contact/Form/Search/Custom/DateAdded.php
@@ -1,9 +1,9 @@
_formValues = self::formatSavedSearchFields($formValues);
- $this->_includeGroups = CRM_Utils_Array::value('includeGroups', $formValues, array());
- $this->_excludeGroups = CRM_Utils_Array::value('excludeGroups', $formValues, array());
+ $this->_includeGroups = CRM_Utils_Array::value('includeGroups', $formValues, []);
+ $this->_excludeGroups = CRM_Utils_Array::value('excludeGroups', $formValues, []);
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Contact Type') => 'contact_type',
ts('Name') => 'sort_name',
ts('Date Added') => 'date_added',
- );
+ ];
}
/**
* @param CRM_Core_Form $form
*/
public function buildForm(&$form) {
- $form->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'custom'));
- $form->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'custom'));
+ $form->add('datepicker', 'start_date', ts('Start Date'), [], FALSE, ['time' => FALSE]);
+ $form->add('datepicker', 'end_date', ts('End Date'), [], FALSE, ['time' => FALSE]);
$groups = CRM_Core_PseudoConstant::nestedGroup();
- $select2style = array(
+ $select2style = [
'multiple' => TRUE,
'style' => 'width: 100%; max-width: 60em;',
'class' => 'crm-select2',
'placeholder' => ts('- select -'),
- );
+ ];
$form->add('select', 'includeGroups',
ts('Include Group(s)'),
@@ -100,7 +103,7 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('start_date', 'end_date', 'includeGroups', 'excludeGroups'));
+ $form->assign('elements', ['start_date', 'end_date', 'includeGroups', 'excludeGroups']);
}
/**
@@ -136,9 +139,9 @@ public function all(
$includeContactIDs = FALSE, $justIDs = FALSE
) {
- $this->_includeGroups = CRM_Utils_Array::value('includeGroups', $this->_formValues, array());
+ $this->_includeGroups = CRM_Utils_Array::value('includeGroups', $this->_formValues, []);
- $this->_excludeGroups = CRM_Utils_Array::value('excludeGroups', $this->_formValues, array());
+ $this->_excludeGroups = CRM_Utils_Array::value('excludeGroups', $this->_formValues, []);
$this->_allSearch = FALSE;
$this->_groups = FALSE;
@@ -177,27 +180,24 @@ public function all(
*/
public function from() {
//define table name
- $randomNum = md5(uniqid());
- $this->_tableName = "civicrm_temp_custom_{$randomNum}";
+ $datesTable = CRM_Utils_SQL_TempTable::build()->setCategory('dates')->setMemory();
+ $this->_datesTable = $datesTable->getName();
+ $xgTable = CRM_Utils_SQL_TempTable::build()->setCategory('xg')->setMemory();
+ $this->_xgTable = $xgTable->getName();
+ $igTable = CRM_Utils_SQL_TempTable::build()->setCategory('ig')->setMemory();
+ $this->_igTable = $igTable->getName();
//grab the contacts added in the date range first
- $sql = "CREATE TEMPORARY TABLE dates_{$this->_tableName} ( id int primary key, date_added date ) ENGINE=HEAP";
- if ($this->_debug > 0) {
- print "-- Date range query:
";
- print "$sql;";
- print "
";
- }
- CRM_Core_DAO::executeQuery($sql);
+ $datesTable->createWithColumns('id int primary key, date_added date');
- $startDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['start_date']));
+ $startDate = !empty($this->_formValues['start_date']) ? $this->_formValues['start_date'] : date('Y-m-d');
$endDateFix = NULL;
if (!empty($this->_formValues['end_date'])) {
- $endDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['end_date']));
# tack 11:59pm on to make search inclusive of the end date
- $endDateFix = "AND date_added <= '" . substr($endDate, 0, 10) . " 23:59:00'";
+ $endDateFix = "AND date_added <= '{$this->_formValues['end_date']} 23:59:00'";
}
- $dateRange = "INSERT INTO dates_{$this->_tableName} ( id, date_added )
+ $dateRange = "INSERT INTO {$this->_datesTable} ( id, date_added )
SELECT
civicrm_contact.id,
min(civicrm_log.modified_date) AS date_added
@@ -208,22 +208,16 @@ public function from() {
GROUP BY
civicrm_contact.id
HAVING
- date_added >= '$startDate'
+ date_added >= '$startDate 00:00:00'
$endDateFix";
- if ($this->_debug > 0) {
- print "-- Date range query:
";
- print "$dateRange;";
- print "
";
- }
-
CRM_Core_DAO::executeQuery($dateRange, CRM_Core_DAO::$_nullArray);
// Only include groups in the search query of one or more Include OR Exclude groups has been selected.
// CRM-6356
if ($this->_groups) {
//block for Group search
- $smartGroup = array();
+ $smartGroup = [];
$group = new CRM_Contact_DAO_Group();
$group->is_active = 1;
$group->find();
@@ -249,16 +243,14 @@ public function from() {
$xGroups = 0;
}
- $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}";
- CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
- $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP";
- CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
+ $xgTable->drop();
+ $xgTable->createWithColumns('contact_id int primary key');
//used only when exclude group is selected
if ($xGroups != 0) {
- $excludeGroup = "INSERT INTO Xg_{$this->_tableName} ( contact_id )
+ $excludeGroup = "INSERT INTO {$this->_xgTable} ( contact_id )
SELECT DISTINCT civicrm_group_contact.contact_id
- FROM civicrm_group_contact, dates_{$this->_tableName} AS d
+ FROM civicrm_group_contact, {$this->_datesTable} AS d
WHERE
d.id = civicrm_group_contact.contact_id AND
civicrm_group_contact.status = 'Added' AND
@@ -277,31 +269,21 @@ public function from() {
SELECT contact_id FROM civicrm_group_contact
WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')";
- $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) $smartSql";
+ $smartGroupQuery = " INSERT IGNORE INTO {$this->_xgTable}(contact_id) $smartSql";
CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray);
}
}
}
- $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}";
- CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
- $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName}
- ( id int PRIMARY KEY AUTO_INCREMENT,
+ $igTable->drop();
+ $igTable->createWithColumns('id int PRIMARY KEY AUTO_INCREMENT,
contact_id int,
- group_names varchar(64)) ENGINE=HEAP";
-
- if ($this->_debug > 0) {
- print "-- Include groups query:
";
- print "$sql;";
- print "
";
- }
+ group_names varchar(64)');
- CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
-
- $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)
+ $includeGroup = "INSERT INTO {$this->_igTable} (contact_id, group_names)
SELECT d.id as contact_id, civicrm_group.name as group_name
- FROM dates_{$this->_tableName} AS d
+ FROM {$this->_datesTable} AS d
INNER JOIN civicrm_group_contact
ON civicrm_group_contact.contact_id = d.id
LEFT JOIN civicrm_group
@@ -309,8 +291,8 @@ public function from() {
//used only when exclude group is selected
if ($xGroups != 0) {
- $includeGroup .= " LEFT JOIN Xg_{$this->_tableName}
- ON d.id = Xg_{$this->_tableName}.contact_id";
+ $includeGroup .= " LEFT JOIN {$this->_xgTable}
+ ON d.id = {$this->_xgTable}.contact_id";
}
$includeGroup .= " WHERE
civicrm_group_contact.status = 'Added' AND
@@ -318,13 +300,7 @@ public function from() {
//used only when exclude group is selected
if ($xGroups != 0) {
- $includeGroup .= " AND Xg_{$this->_tableName}.contact_id IS null";
- }
-
- if ($this->_debug > 0) {
- print "-- Include groups query:
";
- print "$includeGroup;";
- print "
";
+ $includeGroup .= " AND {$this->_xgTable}.contact_id IS null";
}
CRM_Core_DAO::executeQuery($includeGroup, CRM_Core_DAO::$_nullArray);
@@ -339,7 +315,7 @@ public function from() {
$smartSql .= " AND contact_a.id IN (
SELECT id AS contact_id
- FROM dates_{$this->_tableName} )";
+ FROM {$this->_datesTable} )";
$smartSql .= " AND contact_a.id NOT IN (
SELECT contact_id FROM civicrm_group_contact
@@ -347,30 +323,20 @@ public function from() {
//used only when exclude group is selected
if ($xGroups != 0) {
- $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM Xg_{$this->_tableName})";
+ $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM {$this->_xgTable})";
}
$smartGroupQuery = " INSERT IGNORE INTO
- Ig_{$this->_tableName}(contact_id)
+ {$this->_igTable}(contact_id)
$smartSql";
CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray);
- if ($this->_debug > 0) {
- print "-- Smart group query:
";
- print "$smartGroupQuery;";
- print "
";
- }
- $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}
+ $insertGroupNameQuery = "UPDATE IGNORE {$this->_igTable}
SET group_names = (SELECT title FROM civicrm_group
WHERE civicrm_group.id = $values)
- WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL
- AND Ig_{$this->_tableName}.group_names IS NULL";
+ WHERE {$this->_igTable}.contact_id IS NOT NULL
+ AND {$this->_igTable}.group_names IS NULL";
CRM_Core_DAO::executeQuery($insertGroupNameQuery, CRM_Core_DAO::$_nullArray);
- if ($this->_debug > 0) {
- print "-- Smart group query:
";
- print "$insertGroupNameQuery;";
- print "
";
- }
}
}
}
@@ -380,12 +346,12 @@ public function from() {
/* We need to join to this again to get the date_added value */
- $from .= " INNER JOIN dates_{$this->_tableName} d ON (contact_a.id = d.id) {$this->_aclFrom}";
+ $from .= " INNER JOIN {$this->_datesTable} d ON (contact_a.id = d.id) {$this->_aclFrom}";
// Only include groups in the search query of one or more Include OR Exclude groups has been selected.
// CRM-6356
if ($this->_groups) {
- $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)";
+ $from .= " INNER JOIN {$this->_igTable} temptable1 ON (contact_a.id = temptable1.contact_id)";
}
return $from;
@@ -437,13 +403,13 @@ public function count() {
public function __destruct() {
//drop the temp. tables if they exist
- if (!empty($this->_includeGroups)) {
- $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}";
+ if ($this->_igTable && !empty($this->_includeGroups)) {
+ $sql = "DROP TEMPORARY TABLE IF EXISTS {$this->_igTable}";
CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
}
- if (!empty($this->_excludeGroups)) {
- $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}";
+ if ($this->_xgTable && !empty($this->_excludeGroups)) {
+ $sql = "DROP TEMPORARY TABLE IF EXISTS {$this->_xgTable}";
CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
}
}
@@ -455,4 +421,27 @@ public function buildACLClause($tableAlias = 'contact') {
list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
}
+ /**
+ * Format saved search fields for this custom group.
+ *
+ * Note this is a function to facilitate the transition to jcalendar for
+ * saved search groups. In time it can be stripped out again.
+ *
+ * @param array $formValues
+ *
+ * @return array
+ */
+ public static function formatSavedSearchFields($formValues) {
+ $dateFields = [
+ 'start_date',
+ 'end_date',
+ ];
+ foreach ($formValues as $element => $value) {
+ if (in_array($element, $dateFields) && !empty($value)) {
+ $formValues[$element] = date('Y-m-d', strtotime($value));
+ }
+ }
+ return $formValues;
+ }
+
}
diff --git a/CRM/Contact/Form/Search/Custom/EventAggregate.php b/CRM/Contact/Form/Search/Custom/EventAggregate.php
index 2947696c3aa6..441688dab657 100644
--- a/CRM/Contact/Form/Search/Custom/EventAggregate.php
+++ b/CRM/Contact/Form/Search/Custom/EventAggregate.php
@@ -1,9 +1,9 @@
_formValues = $formValues;
- $this->_permissionedComponent = array('CiviContribute', 'CiviEvent');
+ $this->_formValues = self::formatSavedSearchFields($formValues);
+ $this->_permissionedComponent = ['CiviContribute', 'CiviEvent'];
/**
* Define the columns for search result rows
*/
- $this->_columns = array(
+ $this->_columns = [
ts('Event') => 'event_name',
ts('Type') => 'event_type',
ts('Number of Participant') => 'participant_count',
@@ -57,7 +57,7 @@ public function __construct(&$formValues) {
ts('Fee') => 'fee',
ts('Net Payment') => 'net_payment',
ts('Participant') => 'participant',
- );
+ ];
}
/**
@@ -83,23 +83,23 @@ public function buildForm(&$form) {
$form->addElement('checkbox', "event_type_id[$eventId]", 'Event Type', $eventName);
}
$events = CRM_Event_BAO_Event::getEvents(1);
- $form->add('select', 'event_id', ts('Event Name'), array('' => ts('- select -')) + $events);
+ $form->add('select', 'event_id', ts('Event Name'), ['' => ts('- select -')] + $events);
- $form->addDate('start_date', ts('Payments Date From'), FALSE, array('formatType' => 'custom'));
- $form->addDate('end_date', ts('...through'), FALSE, array('formatType' => 'custom'));
+ $form->add('datepicker', 'start_date', ts('Payments Date From'), [], FALSE, ['time' => FALSE]);
+ $form->add('datepicker', 'end_date', ts('...through'), [], FALSE, ['time' => FALSE]);
/**
* If you are using the sample template, this array tells the template fields to render
* for the search form.
*/
- $form->assign('elements', array(
- 'paid_online',
- 'start_date',
- 'end_date',
- 'show_payees',
- 'event_type_id',
- 'event_id',
- ));
+ $form->assign('elements', [
+ 'paid_online',
+ 'start_date',
+ 'end_date',
+ 'show_payees',
+ 'event_type_id',
+ 'event_id',
+ ]);
}
/**
@@ -226,7 +226,7 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $clauses = array();
+ $clauses = [];
$clauses[] = "civicrm_participant.status_id in ( 1 )";
$clauses[] = "civicrm_contribution.is_test = 0";
@@ -237,14 +237,13 @@ public function where($includeContactIDs = FALSE) {
$clauses[] = "civicrm_contribution.payment_instrument_id <> 0";
}
- $startDate = CRM_Utils_Date::processDate($this->_formValues['start_date']);
- if ($startDate) {
- $clauses[] = "civicrm_contribution.receive_date >= $startDate";
+ // As we only allow date to be submitted we need to set default times so midnight for start time and just before midnight for end time.
+ if ($this->_formValues['start_date']) {
+ $clauses[] = "civicrm_contribution.receive_date >= '{$this->_formValues['start_date']} 00:00:00'";
}
- $endDate = CRM_Utils_Date::processDate($this->_formValues['end_date']);
- if ($endDate) {
- $clauses[] = "civicrm_contribution.receive_date <= {$endDate}235959";
+ if ($this->_formValues['end_date']) {
+ $clauses[] = "civicrm_contribution.receive_date <= '{$this->_formValues['end_date']} 23:59:59'";
}
if (!empty($this->_formValues['event_id'])) {
@@ -252,7 +251,7 @@ public function where($includeContactIDs = FALSE) {
}
if ($includeContactIDs) {
- $contactIDs = array();
+ $contactIDs = [];
foreach ($this->_formValues as $id => $value) {
if ($value &&
substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX
@@ -277,8 +276,8 @@ public function where($includeContactIDs = FALSE) {
return implode(' AND ', $clauses);
}
-
/* This function does a query to get totals for some of the search result columns and returns a totals array. */
+
/**
* @return array
*/
@@ -310,7 +309,7 @@ public function summary() {
$dao = CRM_Core_DAO::executeQuery($sql,
CRM_Core_DAO::$_nullArray
);
- $totals = array();
+ $totals = [];
while ($dao->fetch()) {
$totals['payment_amount'] = $dao->payment_amount;
$totals['fee'] = $dao->fee;
@@ -374,4 +373,28 @@ public function buildACLClause($tableAlias = 'contact') {
list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
}
+ /**
+ * Format saved search fields for this custom group.
+ *
+ * Note this is a function to facilitate the transition to jcalendar for
+ * saved search groups. In time it can be stripped out again.
+ *
+ * @param array $formValues
+ *
+ * @return array
+ */
+ public static function formatSavedSearchFields($formValues) {
+ $dateFields = [
+ 'start_date',
+ 'end_date',
+ ];
+ foreach ($formValues as $element => $value) {
+ if (in_array($element, $dateFields) && !empty($value)) {
+ $formValues[$element] = date('Y-m-d', strtotime($value));
+ }
+ }
+
+ return $formValues;
+ }
+
}
diff --git a/CRM/Contact/Form/Search/Custom/FullText.php b/CRM/Contact/Form/Search/Custom/FullText.php
index f52c1bde2734..28f61bbb1918 100644
--- a/CRM/Contact/Form/Search/Custom/FullText.php
+++ b/CRM/Contact/Form/Search/Custom/FullText.php
@@ -1,9 +1,9 @@
_partialQueries = array(
+ $this->_partialQueries = [
new CRM_Contact_Form_Search_Custom_FullText_Contact(),
new CRM_Contact_Form_Search_Custom_FullText_Activity(),
new CRM_Contact_Form_Search_Custom_FullText_Case(),
new CRM_Contact_Form_Search_Custom_FullText_Contribution(),
new CRM_Contact_Form_Search_Custom_FullText_Participant(),
new CRM_Contact_Form_Search_Custom_FullText_Membership(),
- );
+ ];
$formValues['table'] = $this->getFieldValue($formValues, 'table', 'String');
$this->_table = $formValues['table'];
@@ -95,8 +99,8 @@ public function __construct(&$formValues) {
$this->_text = $formValues['text'];
if (!$this->_table) {
- $this->_limitClause = array($this->_limitNumberPlus1, NULL);
- $this->_limitRowClause = $this->_limitDetailClause = array($this->_limitNumber, NULL);
+ $this->_limitClause = [$this->_limitNumberPlus1, NULL];
+ $this->_limitRowClause = $this->_limitDetailClause = [$this->_limitNumber, NULL];
}
else {
// when there is table specified, we would like to use the pager. But since
@@ -107,8 +111,8 @@ public function __construct(&$formValues) {
$pageId = CRM_Utils_Array::value('crmPID', $_REQUEST, 1);
$offset = ($pageId - 1) * $rowCount;
$this->_limitClause = NULL;
- $this->_limitRowClause = array($rowCount, NULL);
- $this->_limitDetailClause = array($rowCount, $offset);
+ $this->_limitRowClause = [$rowCount, NULL];
+ $this->_limitDetailClause = [$rowCount, $offset];
}
$this->_formValues = $formValues;
@@ -147,10 +151,10 @@ public function initialize() {
}
public function buildTempTable() {
- $randomNum = md5(uniqid());
- $this->_tableName = "civicrm_temp_custom_details_{$randomNum}";
+ $table = CRM_Utils_SQL_TempTable::build()->setCategory('custom')->setMemory();
+ $this->_tableName = $table->getName();
- $this->_tableFields = array(
+ $this->_tableFields = [
'id' => 'int unsigned NOT NULL AUTO_INCREMENT',
'table_name' => 'varchar(16)',
'contact_id' => 'int unsigned',
@@ -196,11 +200,11 @@ public function buildTempTable() {
'membership_status' => 'varchar(255)',
// We may have multiple files to list on one record.
// The temporary-table approach can't store full details for all of them
- 'file_ids' => 'varchar(255)', // comma-separate id listing
- );
+ // comma-separate id listing
+ 'file_ids' => 'varchar(255)',
+ ];
$sql = "
-CREATE TEMPORARY TABLE {$this->_tableName} (
";
foreach ($this->_tableFields as $name => $desc) {
@@ -209,21 +213,19 @@ public function buildTempTable() {
$sql .= "
PRIMARY KEY ( id )
-) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
";
- CRM_Core_DAO::executeQuery($sql);
+ $table->createWithColumns($sql);
- $this->_entityIDTableName = "civicrm_temp_custom_entityID_{$randomNum}";
+ $entityIdTable = CRM_Utils_SQL_TempTable::build()->setCategory('custom')->setMemory();
+ $this->_entityIDTableName = $entityIdTable->getName();
$sql = "
-CREATE TEMPORARY TABLE {$this->_entityIDTableName} (
id int unsigned NOT NULL AUTO_INCREMENT,
entity_id int unsigned NOT NULL,
UNIQUE INDEX unique_entity_id ( entity_id ),
PRIMARY KEY ( id )
-) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
";
- CRM_Core_DAO::executeQuery($sql);
+ $entityIdTable->createWithColumns($sql);
if (!empty($this->_formValues['is_unit_test'])) {
$this->_tableNameForTest = $this->_tableName;
@@ -258,7 +260,7 @@ public function filterACLContacts() {
CRM_Contact_BAO_Contact_Permission::cache($contactID);
- $params = array(1 => array($contactID, 'Integer'));
+ $params = [1 => [$contactID, 'Integer']];
$sql = "
DELETE t.*
@@ -304,7 +306,7 @@ public function buildForm(&$form) {
);
// also add a select box to allow the search to be constrained
- $tables = array('' => ts('All tables'));
+ $tables = ['' => ts('All tables')];
foreach ($this->_partialQueries as $partialQuery) {
/** @var $partialQuery CRM_Contact_Form_Search_Custom_FullText_AbstractPartialQuery */
if ($partialQuery->isActive()) {
@@ -321,7 +323,7 @@ public function buildForm(&$form) {
// set form defaults
if (!empty($form->_formValues)) {
- $defaults = array();
+ $defaults = [];
if (isset($form->_formValues['text'])) {
$defaults['text'] = $form->_formValues['text'];
@@ -348,10 +350,10 @@ public function buildForm(&$form) {
* @return array
*/
public function &columns() {
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Name') => 'sort_name',
- );
+ ];
return $this->_columns;
}
@@ -362,10 +364,10 @@ public function &columns() {
public function summary() {
$this->initialize();
- $summary = array();
+ $summary = [];
foreach ($this->_partialQueries as $partialQuery) {
/** @var $partialQuery CRM_Contact_Form_Search_Custom_FullText_AbstractPartialQuery */
- $summary[$partialQuery->getName()] = array();
+ $summary[$partialQuery->getName()] = [];
}
// now iterate through the table and add entries to the relevant section
@@ -378,7 +380,7 @@ public function summary() {
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
$roleIds = CRM_Event_PseudoConstant::participantRole();
while ($dao->fetch()) {
- $row = array();
+ $row = [];
foreach ($this->_tableFields as $name => $dontCare) {
if ($name != 'activity_type_id') {
$row[$name] = $dao->$name;
@@ -389,7 +391,7 @@ public function summary() {
}
if (isset($row['participant_role'])) {
$participantRole = explode(CRM_Core_DAO::VALUE_SEPARATOR, $row['participant_role']);
- $viewRoles = array();
+ $viewRoles = [];
foreach ($participantRole as $v) {
$viewRoles[] = $roleIds[$v];
}
@@ -409,7 +411,7 @@ public function summary() {
$summary[$dao->table_name][] = $row;
}
- $summary['Count'] = array();
+ $summary['Count'] = [];
foreach (array_keys($summary) as $table) {
$summary['Count'][$table] = CRM_Utils_Array::value($table, $this->_foundRows);
if ($summary['Count'][$table] >= self::LIMIT) {
@@ -513,7 +515,7 @@ public function templateFile() {
* @return array
*/
public function setDefaultValues() {
- return array();
+ return [];
}
/**
diff --git a/CRM/Contact/Form/Search/Custom/FullText/AbstractPartialQuery.php b/CRM/Contact/Form/Search/Custom/FullText/AbstractPartialQuery.php
index f5f5ddc2bea9..fc4dc667fc5e 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/AbstractPartialQuery.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/AbstractPartialQuery.php
@@ -1,9 +1,9 @@
fetch()) {
if (!array_key_exists($dao->table_name, $tables)) {
- $tables[$dao->table_name] = array(
+ $tables[$dao->table_name] = [
'id' => 'entity_id',
- 'fields' => array(),
- );
+ 'fields' => [],
+ ];
}
$tables[$dao->table_name]['fields'][$dao->column_name] = NULL;
}
@@ -175,15 +175,15 @@ public function runQueries($queryText, &$tables, $entityIDTableName, $limit) {
continue;
}
- $query = $tableValues + array(
+ $query = $tableValues + [
'text' => CRM_Utils_QueryFormatter::singleton()
- ->format($queryText, CRM_Utils_QueryFormatter::LANG_SOLR),
- );
+ ->format($queryText, CRM_Utils_QueryFormatter::LANG_SOLR),
+ ];
list($intLimit, $intOffset) = $this->parseLimitOffset($limit);
$files = $searcher->search($query, $intLimit, $intOffset);
- $matches = array();
+ $matches = [];
foreach ($files as $file) {
- $matches[] = array('entity_id' => $file['xparent_id']);
+ $matches[] = ['entity_id' => $file['xparent_id']];
}
if ($matches) {
$insertSql = CRM_Utils_SQL_Insert::into($entityIDTableName)->usingReplace()->rows($matches)->toSQL();
@@ -191,8 +191,10 @@ public function runQueries($queryText, &$tables, $entityIDTableName, $limit) {
}
}
else {
- $fullTextFields = array(); // array (string $sqlColumnName)
- $clauses = array(); // array (string $sqlExpression)
+ // array (string $sqlColumnName)
+ $fullTextFields = [];
+ // array (string $sqlExpression)
+ $clauses = [];
foreach ($tableValues['fields'] as $fieldName => $fieldType) {
if ($fieldType == 'Int') {
@@ -242,10 +244,10 @@ public function runQueries($queryText, &$tables, $entityIDTableName, $limit) {
}
}
- return array(
+ return [
'count' => CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM {$entityIDTableName}"),
'files' => $files,
- );
+ ];
}
/**
@@ -277,16 +279,16 @@ public function moveFileIDs($toTable, $parentIdColumn, $files) {
return;
}
- $filesIndex = CRM_Utils_Array::index(array('xparent_id', 'file_id'), $files);
+ $filesIndex = CRM_Utils_Array::index(['xparent_id', 'file_id'], $files);
// ex: $filesIndex[$xparent_id][$file_id] = array(...the file record...);
$dao = CRM_Core_DAO::executeQuery("
SELECT distinct {$parentIdColumn}
FROM {$toTable}
WHERE table_name = %1
- ", array(
- 1 => array($this->getName(), 'String'),
- ));
+ ", [
+ 1 => [$this->getName(), 'String'],
+ ]);
while ($dao->fetch()) {
if (empty($filesIndex[$dao->{$parentIdColumn}])) {
continue;
@@ -295,11 +297,11 @@ public function moveFileIDs($toTable, $parentIdColumn, $files) {
CRM_Core_DAO::executeQuery("UPDATE {$toTable}
SET file_ids = %1
WHERE table_name = %2 AND {$parentIdColumn} = %3
- ", array(
- 1 => array(implode(',', array_keys($filesIndex[$dao->{$parentIdColumn}])), 'String'),
- 2 => array($this->getName(), 'String'),
- 3 => array($dao->{$parentIdColumn}, 'Int'),
- ));
+ ", [
+ 1 => [implode(',', array_keys($filesIndex[$dao->{$parentIdColumn}])), 'String'],
+ 2 => [$this->getName(), 'String'],
+ 3 => [$dao->{$parentIdColumn}, 'Int'],
+ ]);
}
}
@@ -338,7 +340,7 @@ public function parseLimitOffset($limit) {
if (!$intOffset) {
$intOffset = 0;
}
- return array($intLimit, $intOffset);
+ return [$intLimit, $intOffset];
}
}
diff --git a/CRM/Contact/Form/Search/Custom/FullText/Activity.php b/CRM/Contact/Form/Search/Custom/FullText/Activity.php
index deb1ff7e4087..9af565f7bb42 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/Activity.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/Activity.php
@@ -1,9 +1,9 @@
matchText('civicrm_contact c', array('sort_name', 'display_name', 'nick_name'), $queryText)})
+ ({$this->matchText('civicrm_contact c', ['sort_name', 'display_name', 'nick_name'], $queryText)})
OR
({$this->matchText('civicrm_email e', 'email', $queryText)} AND ca.activity_type_id = ov.value AND ov.name IN ('Inbound Email', 'Email') )
)
@@ -105,20 +105,20 @@ public function prepareQueries($queryText, $entityIDTableName) {
$contactSQL[] = "
SELECT distinct ca.id
FROM civicrm_activity ca
-WHERE ({$this->matchText('civicrm_activity ca', array('subject', 'details'), $queryText)})
+WHERE ({$this->matchText('civicrm_activity ca', ['subject', 'details'], $queryText)})
AND (ca.is_deleted = 0 OR ca.is_deleted IS NULL)
";
- $final = array();
+ $final = [];
- $tables = array(
- 'civicrm_activity' => array('fields' => array()),
- 'file' => array(
+ $tables = [
+ 'civicrm_activity' => ['fields' => []],
+ 'file' => [
'xparent_table' => 'civicrm_activity',
- ),
+ ],
'sql' => $contactSQL,
'final' => $final,
- );
+ ];
$this->fillCustomInfo($tables, "( 'Activity' )");
return $tables;;
diff --git a/CRM/Contact/Form/Search/Custom/FullText/Case.php b/CRM/Contact/Form/Search/Custom/FullText/Case.php
index dc586169739f..bf3f7eede706 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/Case.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/Case.php
@@ -1,9 +1,9 @@
matchText('civicrm_contact c', array('sort_name', 'display_name', 'nick_name'), $queryText)})
+WHERE ({$this->matchText('civicrm_contact c', ['sort_name', 'display_name', 'nick_name'], $queryText)})
AND (cc.is_deleted = 0 OR cc.is_deleted IS NULL)
";
@@ -106,13 +106,13 @@ public function prepareQueries($queryText, $entityIDTableName) {
GROUP BY et.entity_id
";
- $tables = array(
- 'civicrm_case' => array('fields' => array()),
- 'file' => array(
+ $tables = [
+ 'civicrm_case' => ['fields' => []],
+ 'file' => [
'xparent_table' => 'civicrm_case',
- ),
+ ],
'sql' => $contactSQL,
- );
+ ];
return $tables;
}
diff --git a/CRM/Contact/Form/Search/Custom/FullText/Contact.php b/CRM/Contact/Form/Search/Custom/FullText/Contact.php
index 0849903b04f7..4930e99cd160 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/Contact.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/Contact.php
@@ -1,9 +1,9 @@
array(
+ $tables = [
+ 'civicrm_contact' => [
'id' => 'id',
- 'fields' => array(
+ 'fields' => [
'sort_name' => NULL,
'nick_name' => NULL,
'display_name' => NULL,
- ),
- ),
- 'civicrm_address' => array(
+ ],
+ ],
+ 'civicrm_address' => [
'id' => 'contact_id',
- 'fields' => array(
+ 'fields' => [
'street_address' => NULL,
'city' => NULL,
'postal_code' => NULL,
- ),
- ),
- 'civicrm_email' => array(
+ ],
+ ],
+ 'civicrm_email' => [
'id' => 'contact_id',
- 'fields' => array('email' => NULL),
- ),
- 'civicrm_phone' => array(
+ 'fields' => ['email' => NULL],
+ ],
+ 'civicrm_phone' => [
'id' => 'contact_id',
- 'fields' => array('phone' => NULL),
- ),
- 'civicrm_note' => array(
+ 'fields' => ['phone' => NULL],
+ ],
+ 'civicrm_note' => [
'id' => 'entity_id',
'entity_table' => 'civicrm_contact',
- 'fields' => array(
+ 'fields' => [
'subject' => NULL,
'note' => NULL,
- ),
- ),
- 'file' => array(
+ ],
+ ],
+ 'file' => [
'xparent_table' => 'civicrm_contact',
- ),
+ ],
'sql' => $contactSQL,
'final' => $final,
- );
+ ];
// get the custom data info
$this->fillCustomInfo($tables,
diff --git a/CRM/Contact/Form/Search/Custom/FullText/Contribution.php b/CRM/Contact/Form/Search/Custom/FullText/Contribution.php
index 7553ed395199..293b728a6186 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/Contribution.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/Contribution.php
@@ -1,9 +1,9 @@
matchText('civicrm_contact c', array('sort_name', 'display_name', 'nick_name'), $queryText)})
+WHERE ({$this->matchText('civicrm_contact c', ['sort_name', 'display_name', 'nick_name'], $queryText)})
";
- $tables = array(
- 'civicrm_contribution' => array(
+ $tables = [
+ 'civicrm_contribution' => [
'id' => 'id',
- 'fields' => array(
+ 'fields' => [
'source' => NULL,
'amount_level' => NULL,
'trxn_Id' => NULL,
'invoice_id' => NULL,
- 'check_number' => 'Int', // Odd: This is really a VARCHAR, so why are we searching like an INT?
+ // Odd: This is really a VARCHAR, so why are we searching like an INT?
+ 'check_number' => 'Int',
'total_amount' => 'Int',
- ),
- ),
- 'file' => array(
+ ],
+ ],
+ 'file' => [
'xparent_table' => 'civicrm_contribution',
- ),
+ ],
'sql' => $contactSQL,
- 'civicrm_note' => array(
+ 'civicrm_note' => [
'id' => 'entity_id',
'entity_table' => 'civicrm_contribution',
- 'fields' => array(
+ 'fields' => [
'subject' => NULL,
'note' => NULL,
- ),
- ),
- );
+ ],
+ ],
+ ];
// get the custom data info
$this->fillCustomInfo($tables, "( 'Contribution' )");
diff --git a/CRM/Contact/Form/Search/Custom/FullText/Membership.php b/CRM/Contact/Form/Search/Custom/FullText/Membership.php
index f1666bb5d7bb..f81694b6cf50 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/Membership.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/Membership.php
@@ -1,9 +1,9 @@
matchText('civicrm_contact c', array('sort_name', 'display_name', 'nick_name'), $queryText)})
+WHERE ({$this->matchText('civicrm_contact c', ['sort_name', 'display_name', 'nick_name'], $queryText)})
";
- $tables = array(
- 'civicrm_membership' => array(
+ $tables = [
+ 'civicrm_membership' => [
'id' => 'id',
- 'fields' => array('source' => NULL),
- ),
- 'file' => array(
+ 'fields' => ['source' => NULL],
+ ],
+ 'file' => [
'xparent_table' => 'civicrm_membership',
- ),
+ ],
'sql' => $contactSQL,
- );
+ ];
// get the custom data info
$this->fillCustomInfo($tables, "( 'Membership' )");
diff --git a/CRM/Contact/Form/Search/Custom/FullText/Participant.php b/CRM/Contact/Form/Search/Custom/FullText/Participant.php
index d73a1d1402f0..20bbbd3e4deb 100644
--- a/CRM/Contact/Form/Search/Custom/FullText/Participant.php
+++ b/CRM/Contact/Form/Search/Custom/FullText/Participant.php
@@ -1,9 +1,9 @@
matchText('civicrm_contact c', array('sort_name', 'display_name', 'nick_name'), $queryText)})
+WHERE ({$this->matchText('civicrm_contact c', ['sort_name', 'display_name', 'nick_name'], $queryText)})
";
- $tables = array(
- 'civicrm_participant' => array(
+ $tables = [
+ 'civicrm_participant' => [
'id' => 'id',
- 'fields' => array(
+ 'fields' => [
'source' => NULL,
'fee_level' => NULL,
'fee_amount' => 'Int',
- ),
- ),
- 'file' => array(
+ ],
+ ],
+ 'file' => [
'xparent_table' => 'civicrm_participant',
- ),
+ ],
'sql' => $contactSQL,
- 'civicrm_note' => array(
+ 'civicrm_note' => [
'id' => 'entity_id',
'entity_table' => 'civicrm_participant',
- 'fields' => array(
+ 'fields' => [
'subject' => NULL,
'note' => NULL,
- ),
- ),
- );
+ ],
+ ],
+ ];
// get the custom data info
$this->fillCustomInfo($tables, "( 'Participant' )");
diff --git a/CRM/Contact/Form/Search/Custom/Group.php b/CRM/Contact/Form/Search/Custom/Group.php
index 9637fb606699..76c7efbc369a 100644
--- a/CRM/Contact/Form/Search/Custom/Group.php
+++ b/CRM/Contact/Form/Search/Custom/Group.php
@@ -1,9 +1,9 @@
_formValues = $formValues;
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Contact Type') => 'contact_type',
ts('Name') => 'sort_name',
ts('Group Name') => 'gname',
ts('Tag Name') => 'tname',
- );
+ ];
- $this->_includeGroups = CRM_Utils_Array::value('includeGroups', $this->_formValues, array());
- $this->_excludeGroups = CRM_Utils_Array::value('excludeGroups', $this->_formValues, array());
- $this->_includeTags = CRM_Utils_Array::value('includeTags', $this->_formValues, array());
- $this->_excludeTags = CRM_Utils_Array::value('excludeTags', $this->_formValues, array());
+ $this->_includeGroups = CRM_Utils_Array::value('includeGroups', $this->_formValues, []);
+ $this->_excludeGroups = CRM_Utils_Array::value('excludeGroups', $this->_formValues, []);
+ $this->_includeTags = CRM_Utils_Array::value('includeTags', $this->_formValues, []);
+ $this->_excludeTags = CRM_Utils_Array::value('excludeTags', $this->_formValues, []);
//define variables
$this->_allSearch = FALSE;
@@ -95,19 +95,19 @@ public function buildForm(&$form) {
$groups = CRM_Core_PseudoConstant::nestedGroup();
- $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
+ $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
if (count($groups) == 0 || count($tags) == 0) {
CRM_Core_Session::setStatus(ts("At least one Group and Tag must be present for Custom Group / Tag search."), ts('Missing Group/Tag'));
$url = CRM_Utils_System::url('civicrm/contact/search/custom/list', 'reset=1');
CRM_Utils_System::redirect($url);
}
- $select2style = array(
+ $select2style = [
'multiple' => TRUE,
'style' => 'width: 100%; max-width: 60em;',
'class' => 'crm-select2',
'placeholder' => ts('- select -'),
- );
+ ];
$form->add('select', 'includeGroups',
ts('Include Group(s)'),
@@ -123,10 +123,10 @@ public function buildForm(&$form) {
$select2style
);
- $andOr = array(
+ $andOr = [
'1' => ts('Show contacts that meet the Groups criteria AND the Tags criteria'),
'0' => ts('Show contacts that meet the Groups criteria OR the Tags criteria'),
- );
+ ];
$form->addRadio('andOr', ts('AND/OR'), $andOr, NULL, ' ', TRUE);
$form->add('select', 'includeTags',
@@ -147,7 +147,7 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('includeGroups', 'excludeGroups', 'andOr', 'includeTags', 'excludeTags'));
+ $form->assign('elements', ['includeGroups', 'excludeGroups', 'andOr', 'includeTags', 'excludeTags']);
}
/**
@@ -247,7 +247,7 @@ public function from() {
$this->_tableName = "civicrm_temp_custom_{$randomNum}";
//block for Group search
- $smartGroup = array();
+ $smartGroup = [];
if ($this->_groups || $this->_allSearch) {
$group = new CRM_Contact_DAO_Group();
$group->is_active = 1;
@@ -260,6 +260,12 @@ public function from() {
}
$includedGroups = implode(',', $allGroups);
+ //CRM-15049 - Include child group ids.
+ $childGroupIds = CRM_Contact_BAO_Group::getChildGroupIds($this->_includeGroups);
+ if (count($childGroupIds) > 0) {
+ $this->_includeGroups = array_merge($this->_includeGroups, $childGroupIds);
+ }
+
if (!empty($this->_includeGroups)) {
$iGroups = implode(',', $this->_includeGroups);
}
@@ -497,8 +503,8 @@ public function from() {
/*
* Set from statement depending on array sel
*/
- $whereitems = array();
- foreach (array('Ig', 'It') as $inc) {
+ $whereitems = [];
+ foreach (['Ig', 'It'] as $inc) {
if ($this->_andOr == 1) {
if ($$inc) {
$from .= " INNER JOIN {$inc}_{$this->_tableName} temptable$inc ON (contact_a.id = temptable$inc.contact_id)";
@@ -514,7 +520,7 @@ public function from() {
}
}
$this->_where = $whereitems ? "(" . implode(' OR ', $whereitems) . ')' : '(1)';
- foreach (array('Xg', 'Xt') as $exc) {
+ foreach (['Xg', 'Xt'] as $exc) {
if ($$exc) {
$from .= " LEFT JOIN {$exc}_{$this->_tableName} temptable$exc ON (contact_a.id = temptable$exc.contact_id)";
$this->_where .= " AND temptable$exc.contact_id IS NULL";
@@ -541,7 +547,7 @@ public function from() {
*/
public function where($includeContactIDs = FALSE) {
if ($includeContactIDs) {
- $contactIDs = array();
+ $contactIDs = [];
foreach ($this->_formValues as $id => $value) {
if ($value &&
diff --git a/CRM/Contact/Form/Search/Custom/MultipleValues.php b/CRM/Contact/Form/Search/Custom/MultipleValues.php
index af2ed673370d..2737366bdb1e 100644
--- a/CRM/Contact/Form/Search/Custom/MultipleValues.php
+++ b/CRM/Contact/Form/Search/Custom/MultipleValues.php
@@ -1,9 +1,9 @@
_tag = CRM_Utils_Array::value('tag', $this->_formValues);
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Contact Type') => 'contact_type',
ts('Name') => 'sort_name',
- );
+ ];
$this->_customGroupIDs = CRM_Utils_Array::value('custom_group', $formValues);
@@ -70,7 +70,7 @@ public function __construct(&$formValues) {
* Add all the fields for chosen groups
*/
public function addColumns() {
- $this->_tables = array();
+ $this->_tables = [];
foreach ($this->_groupTree as $groupID => $group) {
if (empty($this->_customGroupIDs[$groupID])) {
continue;
@@ -82,7 +82,7 @@ public function addColumns() {
foreach ($group['fields'] as $fieldID => $field) {
$this->_columns[$field['label']] = "custom_{$field['id']}";
if (!array_key_exists($group['table_name'], $this->_tables)) {
- $this->_tables[$group['table_name']] = array();
+ $this->_tables[$group['table_name']] = [];
}
$this->_tables[$group['table_name']][$field['id']] = $field['column_name'];
}
@@ -98,16 +98,16 @@ public function buildForm(&$form) {
$form->add('text', 'sort_name', ts('Contact Name'), TRUE);
- $contactTypes = array('' => ts('- any contact type -')) + CRM_Contact_BAO_ContactType::getSelectElements();
- $form->add('select', 'contact_type', ts('Find...'), $contactTypes, array('class' => 'crm-select2 huge'));
+ $contactTypes = ['' => ts('- any contact type -')] + CRM_Contact_BAO_ContactType::getSelectElements();
+ $form->add('select', 'contact_type', ts('Find...'), $contactTypes, ['class' => 'crm-select2 huge']);
// add select for groups
- $group = array('' => ts('- any group -')) + CRM_Core_PseudoConstant::group();
- $form->addElement('select', 'group', ts('in'), $group, array('class' => 'crm-select2 huge'));
+ $group = ['' => ts('- any group -')] + CRM_Core_PseudoConstant::group();
+ $form->addElement('select', 'group', ts('in'), $group, ['class' => 'crm-select2 huge']);
// add select for tags
- $tag = array('' => ts('- any tag -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
- $form->addElement('select', 'tag', ts('Tagged'), $tag, array('class' => 'crm-select2 huge'));
+ $tag = ['' => ts('- any tag -')] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
+ $form->addElement('select', 'tag', ts('Tagged'), $tag, ['class' => 'crm-select2 huge']);
if (empty($this->_groupTree)) {
CRM_Core_Error::statusBounce(ts("Atleast one Custom Group must be present, for Custom Group search."),
@@ -178,7 +178,7 @@ public function all($offset = 0, $rowcount = 0, $sort = NULL, $includeContactIDs
";
}
- $customClauses = array();
+ $customClauses = [];
foreach ($this->_tables as $tableName => $fields) {
foreach ($fields as $fieldID => $fieldName) {
$customClauses[] = "{$tableName}.{$fieldName} as custom_{$fieldID}";
@@ -198,7 +198,7 @@ public function all($offset = 0, $rowcount = 0, $sort = NULL, $includeContactIDs
public function from() {
$this->buildACLClause('contact_a');
$from = "FROM civicrm_contact contact_a {$this->_aclFrom}";
- $customFrom = array();
+ $customFrom = [];
// lets do an INNER JOIN so we get only relevant values rather than all values
if (!empty($this->_tables)) {
foreach ($this->_tables as $tableName => $fields) {
@@ -228,8 +228,8 @@ public function from() {
*/
public function where($includeContactIDs = FALSE) {
$count = 1;
- $clause = array();
- $params = array();
+ $clause = [];
+ $params = [];
$name = CRM_Utils_Array::value('sort_name',
$this->_formValues
);
@@ -237,7 +237,7 @@ public function where($includeContactIDs = FALSE) {
if (strpos($name, '%') === FALSE) {
$name = "%{$name}%";
}
- $params[$count] = array($name, 'String');
+ $params[$count] = [$name, 'String'];
$clause[] = "contact_a.sort_name LIKE %{$count}";
$count++;
}
@@ -246,7 +246,7 @@ public function where($includeContactIDs = FALSE) {
$this->_formValues
);
if ($contact_type != NULL) {
- $contactType = explode('__', $contact_type);
+ $contactType = explode('__', $contact_type, 2);
if (count($contactType) > 1) {
$clause[] = "contact_a.contact_type = '$contactType[0]' AND contact_a.contact_sub_type = '$contactType[1]'";
}
diff --git a/CRM/Contact/Form/Search/Custom/PostalMailing.php b/CRM/Contact/Form/Search/Custom/PostalMailing.php
index 07f6378b801a..fc6998dbe7f7 100644
--- a/CRM/Contact/Form/Search/Custom/PostalMailing.php
+++ b/CRM/Contact/Form/Search/Custom/PostalMailing.php
@@ -1,9 +1,9 @@
_columns = array(
+ $this->_columns = [
// If possible, don't use aliases for the columns you select.
// You can prefix columns with table aliases, if needed.
//
@@ -59,21 +60,21 @@ public function __construct(&$formValues) {
// If you don't do this, the patch of CRM-16587 might cause database
// errors.
ts('State') => 'state_province.name',
- );
+ ];
}
/**
* @param CRM_Core_Form $form
*/
public function buildForm(&$form) {
- $groups = array('' => ts('- select group -')) + CRM_Core_PseudoConstant::nestedGroup(FALSE);
- $form->addElement('select', 'group_id', ts('Group'), $groups, array('class' => 'crm-select2 huge'));
+ $groups = ['' => ts('- select group -')] + CRM_Core_PseudoConstant::nestedGroup(FALSE);
+ $form->addElement('select', 'group_id', ts('Group'), $groups, ['class' => 'crm-select2 huge']);
/**
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('group_id'));
+ $form->assign('elements', ['group_id']);
}
/**
@@ -148,15 +149,15 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $params = array();
+ $params = [];
$count = 1;
- $clause = array();
+ $clause = [];
$groupID = CRM_Utils_Array::value('group_id',
$this->_formValues
);
if ($groupID) {
- $params[$count] = array($groupID, 'Integer');
+ $params[$count] = [$groupID, 'Integer'];
$clause[] = "cgc.group_id = %{$count}";
}
diff --git a/CRM/Contact/Form/Search/Custom/PriceSet.php b/CRM/Contact/Form/Search/Custom/PriceSet.php
index 78ad2a2540f7..3253fffb8131 100644
--- a/CRM/Contact/Form/Search/Custom/PriceSet.php
+++ b/CRM/Contact/Form/Search/Custom/PriceSet.php
@@ -1,9 +1,9 @@
_columns as $dontCare => $fieldName) {
- if (in_array($fieldName, array(
+ if (in_array($fieldName, [
'contact_id',
'participant_id',
'display_name',
- ))) {
+ ])) {
continue;
}
$sql .= "{$fieldName} int default 0,\n";
@@ -133,12 +133,12 @@ public function fillTable() {
$dao = CRM_Core_DAO::executeQuery($sql);
// first store all the information by option value id
- $rows = array();
+ $rows = [];
while ($dao->fetch()) {
$contactID = $dao->contact_id;
$participantID = $dao->participant_id;
if (!isset($rows[$participantID])) {
- $rows[$participantID] = array();
+ $rows[$participantID] = [];
}
$rows[$participantID][] = "price_field_{$dao->price_field_value_id} = {$dao->qty}";
@@ -146,12 +146,14 @@ public function fillTable() {
foreach (array_keys($rows) as $participantID) {
$values = implode(',', $rows[$participantID]);
- $sql = "
+ if ($values) {
+ $sql = "
UPDATE {$this->_tableName}
SET $values
WHERE participant_id = $participantID;
";
- CRM_Core_DAO::executeQuery($sql);
+ CRM_Core_DAO::executeQuery($sql);
+ }
}
}
@@ -174,9 +176,9 @@ public function priceSetDAO($eventID = NULL) {
AND p.entity_id = e.id
";
- $params = array();
+ $params = [];
if ($eventID) {
- $params[1] = array($eventID, 'Integer');
+ $params[1] = [$eventID, 'Integer'];
$sql .= " AND e.id = $eventID";
}
@@ -194,7 +196,7 @@ public function priceSetDAO($eventID = NULL) {
public function buildForm(&$form) {
$dao = $this->priceSetDAO();
- $event = array();
+ $event = [];
while ($dao->fetch()) {
$event[$dao->id] = $dao->title;
}
@@ -219,15 +221,15 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('event_id'));
+ $form->assign('elements', ['event_id']);
}
public function setColumns() {
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Participant ID') => 'participant_id',
ts('Name') => 'display_name',
- );
+ ];
if (!$this->_eventID) {
return;
@@ -290,10 +292,10 @@ public function all(
contact_a.display_name as display_name";
foreach ($this->_columns as $dontCare => $fieldName) {
- if (in_array($fieldName, array(
+ if (in_array($fieldName, [
'contact_id',
'display_name',
- ))) {
+ ])) {
continue;
}
$selectClause .= ",\ntempTable.{$fieldName} as {$fieldName}";
diff --git a/CRM/Contact/Form/Search/Custom/Proximity.php b/CRM/Contact/Form/Search/Custom/Proximity.php
index 8375adee013f..dc517d92c8ec 100644
--- a/CRM/Contact/Form/Search/Custom/Proximity.php
+++ b/CRM/Contact/Form/Search/Custom/Proximity.php
@@ -1,9 +1,9 @@
_formValues)) {
// add the country and state
- if (!empty($this->_formValues['country_id'])) {
- $this->_formValues['country'] = CRM_Core_PseudoConstant::country($this->_formValues['country_id']);
- }
-
- if (!empty($this->_formValues['state_province_id'])) {
- $this->_formValues['state_province'] = CRM_Core_PseudoConstant::stateProvince($this->_formValues['state_province_id']);
- }
-
- // use the address to get the latitude and longitude
- CRM_Utils_Geocode_Google::format($this->_formValues);
-
- if (!is_numeric(CRM_Utils_Array::value('geo_code_1', $this->_formValues)) ||
- !is_numeric(CRM_Utils_Array::value('geo_code_2', $this->_formValues)) ||
- !isset($this->_formValues['distance'])
- ) {
- CRM_Core_Error::fatal(ts('Could not geocode input'));
- }
-
+ self::addGeocodingData($this->_formValues);
$this->_latitude = $this->_formValues['geo_code_1'];
$this->_longitude = $this->_formValues['geo_code_2'];
@@ -88,14 +74,23 @@ public function __construct(&$formValues) {
$this->_tag = CRM_Utils_Array::value('tag', $this->_formValues);
- $this->_columns = array(
+ $this->_columns = [
ts('Name') => 'sort_name',
ts('Street Address') => 'street_address',
ts('City') => 'city',
ts('Postal Code') => 'postal_code',
ts('State') => 'state_province',
ts('Country') => 'country',
- );
+ ];
+ }
+
+ /**
+ * Get the query object for this selector.
+ *
+ * @return CRM_Contact_BAO_Query
+ */
+ public function getQueryObj() {
+ return $this->_query;
}
/**
@@ -108,7 +103,7 @@ public function buildForm(&$form) {
$form->add('text', 'distance', ts('Distance'), NULL, TRUE);
- $proxUnits = array('km' => ts('km'), 'miles' => ts('miles'));
+ $proxUnits = ['km' => ts('km'), 'miles' => ts('miles')];
$form->add('select', 'prox_distance_unit', ts('Units'), $proxUnits, TRUE);
$form->add('text',
@@ -126,20 +121,23 @@ public function buildForm(&$form) {
ts('Postal Code')
);
- $defaults = array();
+ $defaults = [];
if ($countryDefault) {
$defaults['country_id'] = $countryDefault;
}
$form->addChainSelect('state_province_id');
- $country = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
- $form->add('select', 'country_id', ts('Country'), $country, TRUE, array('class' => 'crm-select2'));
+ $country = ['' => ts('- select -')] + CRM_Core_PseudoConstant::country();
+ $form->add('select', 'country_id', ts('Country'), $country, TRUE, ['class' => 'crm-select2']);
+
+ $form->add('text', 'geo_code_1', ts('Latitude'));
+ $form->add('text', 'geo_code_2', ts('Longitude'));
- $group = array('' => ts('- any group -')) + CRM_Core_PseudoConstant::nestedGroup();
- $form->addElement('select', 'group', ts('Group'), $group, array('class' => 'crm-select2 huge'));
+ $group = ['' => ts('- any group -')] + CRM_Core_PseudoConstant::nestedGroup();
+ $form->addElement('select', 'group', ts('Group'), $group, ['class' => 'crm-select2 huge']);
- $tag = array('' => ts('- any tag -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
- $form->addElement('select', 'tag', ts('Tag'), $tag, array('class' => 'crm-select2 huge'));
+ $tag = ['' => ts('- any tag -')] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
+ $form->addElement('select', 'tag', ts('Tag'), $tag, ['class' => 'crm-select2 huge']);
/**
* You can define a custom title for the search form
@@ -150,7 +148,7 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array(
+ $form->assign('elements', [
'distance',
'prox_distance_unit',
'street_address',
@@ -160,7 +158,7 @@ public function buildForm(&$form) {
'state_province_id',
'group',
'tag',
- ));
+ ]);
}
/**
@@ -176,20 +174,7 @@ public function all(
$offset = 0, $rowcount = 0, $sort = NULL,
$includeContactIDs = FALSE, $justIDs = FALSE
) {
- if ($justIDs) {
- $selectClause = "contact_a.id as contact_id";
- }
- else {
- $selectClause = "
-contact_a.id as contact_id ,
-contact_a.sort_name as sort_name ,
-address.street_address as street_address,
-address.city as city ,
-address.postal_code as postal_code ,
-state_province.name as state_province,
-country.name as country
-";
- }
+ $selectClause = $justIDs ? "contact_a.id as contact_id" : NULL;
return $this->sql($selectClause,
$offset, $rowcount, $sort,
@@ -198,31 +183,70 @@ public function all(
}
/**
+ * Override sql() function to use the Query object rather than generating on the form.
+ *
+ * @param string $selectClause
+ * @param int $offset
+ * @param int $rowcount
+ * @param null $sort
+ * @param bool $includeContactIDs
+ * @param null $groupBy
+ *
* @return string
*/
- public function from() {
- $this->buildACLClause('contact_a');
- $f = "
-FROM civicrm_contact contact_a
-LEFT JOIN civicrm_address address ON ( address.contact_id = contact_a.id AND
- address.is_primary = 1 )
-LEFT JOIN civicrm_state_province state_province ON state_province.id = address.state_province_id
-LEFT JOIN civicrm_country country ON country.id = address.country_id {$this->_aclFrom}
-";
-
- // This prevents duplicate rows when contacts have more than one tag any you select "any tag"
- if ($this->_tag) {
- $f .= "
-LEFT JOIN civicrm_entity_tag t ON (t.entity_table='civicrm_contact' AND contact_a.id = t.entity_id)
-";
+ public function sql(
+ $selectClause,
+ $offset = 0,
+ $rowcount = 0,
+ $sort = NULL,
+ $includeContactIDs = FALSE,
+ $groupBy = NULL
+ ) {
+
+ $isCountOnly = FALSE;
+ if ($selectClause === 'count(distinct contact_a.id) as total') {
+ $isCountOnly = TRUE;
}
- if ($this->_group) {
- $f .= "
-LEFT JOIN civicrm_group_contact cgc ON ( cgc.contact_id = contact_a.id AND cgc.status = 'Added')
-";
+
+ $searchParams = [
+ ['prox_distance_unit', '=', $this->_formValues['prox_distance_unit'], 0, 0],
+ ['prox_distance', '=', $this->_formValues['distance'], 0, 0],
+ ['prox_geo_code_1', '=', $this->_formValues['geo_code_1'], 0, 0],
+ ['prox_geo_code_2', '=', $this->_formValues['geo_code_2'], 0, 0],
+ ];
+ if (!empty($this->_formValues['group'])) {
+ $searchParams[] = ['group', '=', ['IN', (array) $this->_formValues['group']][1], 0, 0];
+ }
+ if (!empty($this->_formValues['tag'])) {
+ $searchParams[] = ['contact_tags', '=', ['IN', (array) $this->_formValues['tag']][1], 0, 0];
}
- return $f;
+ $display = array_fill_keys(['city', 'state_province', 'country', 'postal_code', 'street_address', 'display_name', 'sort_name'], 1);
+ if ($selectClause === 'contact_a.id as contact_id') {
+ // Not sure when this would happen but calling all with 'justIDs' gets us here.
+ $display = ['contact_id' => 1];
+ }
+
+ $this->_query = new CRM_Contact_BAO_Query($searchParams, $display);
+ return $this->_query->searchQuery(
+ $offset,
+ $rowcount,
+ $sort,
+ $isCountOnly,
+ $includeContactIDs,
+ FALSE,
+ $isCountOnly,
+ $returnQuery = TRUE
+ );
+
+ }
+
+ /**
+ * @return string
+ */
+ public function from() {
+ //unused
+ return '';
}
/**
@@ -231,33 +255,8 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $params = array();
- $clause = array();
-
- $where = CRM_Contact_BAO_ProximityQuery::where($this->_latitude,
- $this->_longitude,
- $this->_distance,
- 'address'
- );
-
- if ($this->_tag) {
- $where .= "
-AND t.tag_id = {$this->_tag}
-";
- }
- if ($this->_group) {
- $where .= "
-AND cgc.group_id = {$this->_group}
- ";
- }
-
- $where .= " AND contact_a.is_deleted != 1 ";
-
- if ($this->_aclWhere) {
- $where .= " AND {$this->_aclWhere} ";
- }
-
- return $this->whereClause($where, $params);
+ //unused
+ return '';
}
/**
@@ -277,7 +276,7 @@ public function setDefaultValues() {
$config = CRM_Core_Config::singleton();
$countryDefault = $config->defaultContactCountry;
$stateprovinceDefault = $config->defaultContactStateProvince;
- $defaults = array();
+ $defaults = [];
if ($countryDefault) {
if ($countryDefault == '1228' || $countryDefault == '1226') {
@@ -314,10 +313,42 @@ public function setTitle($title) {
}
/**
- * @param string $tableAlias
+ * Validate form input.
+ *
+ * @param array $fields
+ * @param array $files
+ * @param CRM_Core_Form $self
+ *
+ * @return array
+ * Input errors from the form.
+ */
+ public function formRule($fields, $files, $self) {
+ $this->addGeocodingData($fields);
+
+ if (!is_numeric(CRM_Utils_Array::value('geo_code_1', $fields)) ||
+ !is_numeric(CRM_Utils_Array::value('geo_code_2', $fields)) ||
+ !isset($fields['distance'])
+ ) {
+ $errorMessage = ts('Could not determine co-ordinates for provided data');
+ return array_fill_keys(['street_address', 'city', 'postal_code', 'country_id', 'state_province_id'], $errorMessage);
+ }
+ return [];
+ }
+
+ /**
+ * Add the geocoding data to the fields supplied.
+ *
+ * @param array $fields
*/
- public function buildACLClause($tableAlias = 'contact') {
- list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
+ protected function addGeocodingData(&$fields) {
+ if (!empty($fields['country_id'])) {
+ $fields['country'] = CRM_Core_PseudoConstant::country($fields['country_id']);
+ }
+
+ if (!empty($fields['state_province_id'])) {
+ $fields['state_province'] = CRM_Core_PseudoConstant::stateProvince($fields['state_province_id']);
+ }
+ CRM_Core_BAO_Address::addGeocoderData($fields);
}
}
diff --git a/CRM/Contact/Form/Search/Custom/RandomSegment.php b/CRM/Contact/Form/Search/Custom/RandomSegment.php
index a0125ed0538b..36addc77c6c9 100644
--- a/CRM/Contact/Form/Search/Custom/RandomSegment.php
+++ b/CRM/Contact/Form/Search/Custom/RandomSegment.php
@@ -1,9 +1,9 @@
_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Contact Type') => 'contact_type',
ts('Name') => 'sort_name',
ts('Email') => 'email',
- );
+ ];
$this->initialize();
}
@@ -87,12 +87,12 @@ public function buildForm(&$form) {
$groups = CRM_Core_PseudoConstant::nestedGroup();
- $select2style = array(
+ $select2style = [
'multiple' => TRUE,
'style' => 'width: 100%; max-width: 60em;',
'class' => 'crm-select2',
'placeholder' => ts('- select -'),
- );
+ ];
$form->add('select', 'includeGroups',
ts('Include Group(s)'),
@@ -114,7 +114,7 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('segmentSize', 'includeGroups', 'excludeGroups'));
+ $form->assign('elements', ['segmentSize', 'includeGroups', 'excludeGroups']);
}
/**
@@ -162,7 +162,7 @@ public function from() {
$this->_tableName = "civicrm_temp_custom_{$randomNum}";
//block for Group search
- $smartGroup = array();
+ $smartGroup = [];
$group = new CRM_Contact_DAO_Group();
$group->is_active = 1;
$group->find();
@@ -372,6 +372,7 @@ public function setTitle($title) {
/**
* @return mixed
*/
+
/**
* @return mixed
*/
diff --git a/CRM/Contact/Form/Search/Custom/Sample.php b/CRM/Contact/Form/Search/Custom/Sample.php
index c5e2067c5878..a148f5ca3d48 100644
--- a/CRM/Contact/Form/Search/Custom/Sample.php
+++ b/CRM/Contact/Form/Search/Custom/Sample.php
@@ -1,9 +1,9 @@
_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Contact Type') => 'contact_type',
ts('Name') => 'sort_name',
ts('State') => 'state_province',
- );
+ ];
}
/**
@@ -69,7 +70,7 @@ public function buildForm(&$form) {
TRUE
);
- $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince();
+ $stateProvince = ['' => ts('- any state/province -')] + CRM_Core_PseudoConstant::stateProvince();
$form->addElement('select', 'state_province_id', ts('State/Province'), $stateProvince);
/**
@@ -81,17 +82,17 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('household_name', 'state_province_id'));
+ $form->assign('elements', ['household_name', 'state_province_id']);
}
/**
* @return array
*/
public function summary() {
- $summary = array(
+ $summary = [
'summary' => 'This is a summary',
'total' => 50.0,
- );
+ ];
return $summary;
}
@@ -158,11 +159,11 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $params = array();
+ $params = [];
$where = "contact_a.contact_type = 'Household'";
$count = 1;
- $clause = array();
+ $clause = [];
$name = CRM_Utils_Array::value('household_name',
$this->_formValues
);
@@ -170,7 +171,7 @@ public function where($includeContactIDs = FALSE) {
if (strpos($name, '%') === FALSE) {
$name = "%{$name}%";
}
- $params[$count] = array($name, 'String');
+ $params[$count] = [$name, 'String'];
$clause[] = "contact_a.household_name LIKE %{$count}";
$count++;
}
@@ -185,7 +186,7 @@ public function where($includeContactIDs = FALSE) {
}
if ($state) {
- $params[$count] = array($state, 'Integer');
+ $params[$count] = [$state, 'Integer'];
$clause[] = "state_province.id = %{$count}";
}
@@ -211,7 +212,7 @@ public function templateFile() {
* @return array
*/
public function setDefaultValues() {
- return array_merge(array('household_name' => ''), $this->_formValues);
+ return array_merge(['household_name' => ''], $this->_formValues);
}
/**
diff --git a/CRM/Contact/Form/Search/Custom/TagContributions.php b/CRM/Contact/Form/Search/Custom/TagContributions.php
index 3987ce399b59..df0e60488fe1 100644
--- a/CRM/Contact/Form/Search/Custom/TagContributions.php
+++ b/CRM/Contact/Form/Search/Custom/TagContributions.php
@@ -1,9 +1,9 @@
_formValues = $formValues;
+ $this->_formValues = self::formatSavedSearchFields($formValues);
$this->_permissionedComponent = 'CiviContribute';
/**
* Define the columns for search result rows
*/
- $this->_columns = array(
+ $this->_columns = [
ts('Contact ID') => 'contact_id',
ts('Full Name') => 'sort_name',
ts('First Name') => 'first_name',
ts('Last Name') => 'last_name',
ts('Tag') => 'tag_name',
ts('Totals') => 'amount',
- );
+ ];
}
/**
@@ -73,16 +73,16 @@ public function buildForm(&$form) {
* Define the search form fields here
*/
- $form->addDate('start_date', ts('Contribution Date From'), FALSE, array('formatType' => 'custom'));
- $form->addDate('end_date', ts('...through'), FALSE, array('formatType' => 'custom'));
- $tag = array('' => ts('- any tag -')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
+ $form->add('datepicker', 'start_date', ts('Contribution Date From'), [], FALSE, ['time' => FALSE]);
+ $form->add('datepicker', 'end_date', ts('...through'), [], FALSE, ['time' => FALSE]);
+ $tag = ['' => ts('- any tag -')] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
$form->addElement('select', 'tag', ts('Tagged'), $tag);
/**
* If you are using the sample template, this array tells the template fields to render
* for the search form.
*/
- $form->assign('elements', array('start_date', 'end_date', 'tag'));
+ $form->assign('elements', ['start_date', 'end_date', 'tag']);
}
/**
@@ -169,25 +169,24 @@ public function from() {
* WHERE clause is an array built from any required JOINS plus conditional filters based on search criteria field values
*
*/
+
/**
* @param bool $includeContactIDs
*
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $clauses = array();
+ $clauses = [];
$clauses[] = "contact_a.contact_type = 'Individual'";
$clauses[] = "civicrm_contribution.contact_id = contact_a.id";
- $startDate = CRM_Utils_Date::processDate($this->_formValues['start_date']);
- if ($startDate) {
- $clauses[] = "civicrm_contribution.receive_date >= $startDate";
+ if ($this->_formValues['start_date']) {
+ $clauses[] = "civicrm_contribution.receive_date >= '{$this->_formValues['start_date']} 00:00:00'";
}
- $endDate = CRM_Utils_Date::processDate($this->_formValues['end_date']);
- if ($endDate) {
- $clauses[] = "civicrm_contribution.receive_date <= $endDate";
+ if ($this->_formValues['end_date']) {
+ $clauses[] = "civicrm_contribution.receive_date <= '{$this->_formValues['end_date']} 23:59:59'";
}
$tag = CRM_Utils_Array::value('tag', $this->_formValues);
@@ -200,7 +199,7 @@ public function where($includeContactIDs = FALSE) {
}
if ($includeContactIDs) {
- $contactIDs = array();
+ $contactIDs = [];
foreach ($this->_formValues as $id => $value) {
if ($value &&
substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX
@@ -220,7 +219,6 @@ public function where($includeContactIDs = FALSE) {
return implode(' AND ', $clauses);
}
-
/*
* Functions below generally don't need to be modified
*/
@@ -282,4 +280,27 @@ public function buildACLClause($tableAlias = 'contact') {
list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
}
+ /**
+ * Format saved search fields for this custom group.
+ *
+ * Note this is a function to facilitate the transition to jcalendar for
+ * saved search groups. In time it can be stripped out again.
+ *
+ * @param array $formValues
+ *
+ * @return array
+ */
+ public static function formatSavedSearchFields($formValues) {
+ $dateFields = [
+ 'start_date',
+ 'end_date',
+ ];
+ foreach ($formValues as $element => $value) {
+ if (in_array($element, $dateFields) && !empty($value)) {
+ $formValues[$element] = date('Y-m-d', strtotime($value));
+ }
+ }
+ return $formValues;
+ }
+
}
diff --git a/CRM/Contact/Form/Search/Custom/ZipCodeRange.php b/CRM/Contact/Form/Search/Custom/ZipCodeRange.php
index 349d57d81898..3b341bcb2818 100644
--- a/CRM/Contact/Form/Search/Custom/ZipCodeRange.php
+++ b/CRM/Contact/Form/Search/Custom/ZipCodeRange.php
@@ -1,9 +1,9 @@
_columns = array(
+ $this->_columns = [
// If possible, don't use aliases for the columns you select.
// You can prefix columns with table aliases, if needed.
//
@@ -53,7 +54,7 @@ public function __construct(&$formValues) {
ts('Name') => 'sort_name',
ts('Email') => 'email',
ts('Zip') => 'postal_code',
- );
+ ];
}
/**
@@ -81,14 +82,14 @@ public function buildForm(&$form) {
* if you are using the standard template, this array tells the template what elements
* are part of the search criteria
*/
- $form->assign('elements', array('postal_code_low', 'postal_code_high'));
+ $form->assign('elements', ['postal_code_low', 'postal_code_high']);
}
/**
* @return array
*/
public function summary() {
- $summary = array();
+ $summary = [];
return $summary;
}
@@ -161,7 +162,7 @@ public function from() {
* @return string
*/
public function where($includeContactIDs = FALSE) {
- $params = array();
+ $params = [];
$low = CRM_Utils_Array::value('postal_code_low',
$this->_formValues
@@ -179,10 +180,10 @@ public function where($includeContactIDs = FALSE) {
}
$where = "ROUND(address.postal_code) >= %1 AND ROUND(address.postal_code) <= %2";
- $params = array(
- 1 => array(trim($low), 'Integer'),
- 2 => array(trim($high), 'Integer'),
- );
+ $params = [
+ 1 => [trim($low), 'Integer'],
+ 2 => [trim($high), 'Integer'],
+ ];
if ($this->_aclWhere) {
$where .= " AND {$this->_aclWhere} ";
diff --git a/CRM/Contact/Form/Search/Interface.php b/CRM/Contact/Form/Search/Interface.php
index 071962c0bc1c..1728708bc7bd 100644
--- a/CRM/Contact/Form/Search/Interface.php
+++ b/CRM/Contact/Form/Search/Interface.php
@@ -1,9 +1,9 @@
_contactIds = array();
- $form->_contactTypes = array();
+ public static function preProcessCommon(&$form) {
+ $form->_contactIds = [];
+ $form->_contactTypes = [];
+
+ $useTable = (CRM_Utils_System::getClassName($form->controller->getStateMachine()) == 'CRM_Export_StateMachine_Standalone');
- $isStandAlone = (in_array('task', $form->urlPath));
+ $isStandAlone = in_array('task', $form->urlPath) || in_array('standalone', $form->urlPath);
if ($isStandAlone) {
list($form->_task, $title) = CRM_Contact_Task::getTaskAndTitleByClass(get_class($form));
if (!array_key_exists($form->_task, CRM_Contact_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()))) {
- CRM_Core_Error::fatal(ts('You do not have enough permission to do this task.'));
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
}
- $form->_contactIds = explode(',', CRM_Utils_Request::retrieve('cids', 'String', $form, TRUE));
+ $form->_contactIds = explode(',', CRM_Utils_Request::retrieve('cids', 'CommaSeparatedIntegers', $form, TRUE));
if (empty($form->_contactIds)) {
- CRM_Core_Error::statusBounce(ts("You did't selected any contact to perform this task."));
+ CRM_Core_Error::statusBounce(ts('No Contacts Selected'));
}
$form->setTitle($title);
}
@@ -150,35 +154,30 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->assign('taskName', CRM_Utils_Array::value($form->_task, $crmContactTaskTasks));
if ($useTable) {
- $form->_componentTable = CRM_Core_DAO::createTempTableName('civicrm_task_action', TRUE, $qfKey);
- $sql = " DROP TABLE IF EXISTS {$form->_componentTable}";
- CRM_Core_DAO::executeQuery($sql);
-
- $sql = "CREATE TABLE {$form->_componentTable} ( contact_id int primary key) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
- CRM_Core_DAO::executeQuery($sql);
+ $tempTable = CRM_Utils_SQL_TempTable::build()->setCategory('tskact')->setDurable()->setId($qfKey);
+ $form->_componentTable = $tempTable->getName();
+ $tempTable->drop();
+ $tempTable->createWithColumns('contact_id int primary key');
}
// all contacts or action = save a search
if ((CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_all') ||
($form->_task == CRM_Contact_Task::SAVE_SEARCH)
) {
- $sortByCharacter = $form->get('sortByCharacter');
- $cacheKey = ($sortByCharacter && $sortByCharacter != 'all') ? "{$cacheKey}_alphabet" : $cacheKey;
-
// since we don't store all contacts in prevnextcache, when user selects "all" use query to retrieve contacts
// rather than prevnext cache table for most of the task actions except export where we rebuild query to fetch
// final result set
if ($useTable) {
- $allCids = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey, "getall");
+ $allCids = Civi::service('prevnext')->getSelection($cacheKey, "getall");
}
else {
- $allCids[$cacheKey] = $form->getContactIds();
+ $allCids[$cacheKey] = self::getContactIds($form);
}
- $form->_contactIds = array();
+ $form->_contactIds = [];
if ($useTable) {
$count = 0;
- $insertString = array();
+ $insertString = [];
foreach ($allCids[$cacheKey] as $cid => $ignore) {
$count++;
$insertString[] = " ( {$cid} ) ";
@@ -186,7 +185,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$string = implode(',', $insertString);
$sql = "REPLACE INTO {$form->_componentTable} ( contact_id ) VALUES $string";
CRM_Core_DAO::executeQuery($sql);
- $insertString = array();
+ $insertString = [];
}
}
if (!empty($insertString)) {
@@ -210,7 +209,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
elseif (CRM_Utils_Array::value('radio_ts', self::$_searchFormValues) == 'ts_sel') {
// selected contacts only
// need to perform action on only selected contacts
- $insertString = array();
+ $insertString = [];
// refire sql in case of custom search
if ($form->_action == CRM_Core_Action::COPY) {
@@ -230,7 +229,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
}
else {
// fetching selected contact ids of passed cache key
- $selectedCids = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
+ $selectedCids = Civi::service('prevnext')->getSelection($cacheKey);
foreach ($selectedCids[$cacheKey] as $selectedCid => $ignore) {
if ($useTable) {
$insertString[] = " ( {$selectedCid} ) ";
@@ -270,7 +269,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
) {
$sel = CRM_Utils_Array::value('radio_ts', self::$_searchFormValues);
$form->assign('searchtype', $sel);
- $result = CRM_Core_BAO_PrevNextCache::getSelectedContacts();
+ $result = self::getSelectedContactNames();
$form->assign("value", $result);
}
@@ -283,47 +282,50 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
}
/**
- * Get the contact id for custom search.
+ * Get the contact ids for:
+ * - "Select Records: All xx records"
+ * - custom search (FIXME: does this still apply to custom search?).
+ * When we call this function we are not using the prev/next cache
*
- * we are not using prev/next table in case of custom search
+ * @param $form CRM_Core_Form
+ *
+ * @return array $contactIds
*/
- public function getContactIds() {
+ public static function getContactIds($form) {
// need to perform action on all contacts
// fire the query again and get the contact id's + display name
$sortID = NULL;
- if ($this->get(CRM_Utils_Sort::SORT_ID)) {
- $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
- $this->get(CRM_Utils_Sort::SORT_DIRECTION)
+ if ($form->get(CRM_Utils_Sort::SORT_ID)) {
+ $sortID = CRM_Utils_Sort::sortIDValue($form->get(CRM_Utils_Sort::SORT_ID),
+ $form->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
- $selectorName = $this->controller->selectorName();
- require_once str_replace('_', DIRECTORY_SEPARATOR, $selectorName) . '.php';
+ $selectorName = $form->controller->selectorName();
- $fv = $this->get('formValues');
- $customClass = $this->get('customSearchClass');
- require_once 'CRM/Core/BAO/Mapping.php';
+ $fv = $form->get('formValues');
+ $customClass = $form->get('customSearchClass');
$returnProperties = CRM_Core_BAO_Mapping::returnProperties(self::$_searchFormValues);
$selector = new $selectorName($customClass, $fv, NULL, $returnProperties);
- $params = $this->get('queryParams');
+ $params = $form->get('queryParams');
// fix for CRM-5165
- $sortByCharacter = $this->get('sortByCharacter');
+ $sortByCharacter = $form->get('sortByCharacter');
if ($sortByCharacter && $sortByCharacter != 1) {
- $params[] = array('sortByCharacter', '=', $sortByCharacter, 0, 0);
+ $params[] = ['sortByCharacter', '=', $sortByCharacter, 0, 0];
}
- $queryOperator = $this->get('queryOperator');
+ $queryOperator = $form->get('queryOperator');
if (!$queryOperator) {
$queryOperator = 'AND';
}
- $dao = $selector->contactIDQuery($params, $this->_action, $sortID,
+ $dao = $selector->contactIDQuery($params, $sortID,
CRM_Utils_Array::value('display_relationship_type', $fv),
$queryOperator
);
- $contactIds = array();
+ $contactIds = [];
while ($dao->fetch()) {
$contactIds[$dao->contact_id] = $dao->contact_id;
}
@@ -331,7 +333,6 @@ public function getContactIds() {
return $contactIds;
}
-
/**
* Set default values for the form. Relationship that in edit/view action.
*
@@ -340,7 +341,7 @@ public function getContactIds() {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
return $defaults;
}
@@ -376,19 +377,18 @@ public function postProcess() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- 'icon' => 'fa-times',
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ 'icon' => 'fa-times',
+ ],
+ ]);
}
/**
@@ -414,10 +414,10 @@ public function mergeContactIdsByHousehold() {
// Get Head of Household & Household Member relationships
$relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
$relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
- $householdRelationshipTypes = array(
+ $householdRelationshipTypes = [
$relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH],
$relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH],
- );
+ ];
$relID = implode(',', $this->_contactIds);
@@ -453,24 +453,46 @@ public function mergeContactIdsByHousehold() {
$this->_contactIds[] = $householdsDAO->household_id;
}
}
- $householdsDAO->free();
}
// If contact list has changed, households will probably be at the end of
// the list. Sort it again by sort_name.
if (implode(',', $this->_contactIds) != $relID) {
- $result = civicrm_api3('Contact', 'get', array(
- 'return' => array('id'),
- 'id' => array('IN' => $this->_contactIds),
- 'options' => array(
+ $result = civicrm_api3('Contact', 'get', [
+ 'return' => ['id'],
+ 'id' => ['IN' => $this->_contactIds],
+ 'options' => [
'limit' => 0,
'sort' => "sort_name",
- ),
- ));
+ ],
+ ]);
$this->_contactIds = array_keys($result['values']);
}
}
+ /**
+ * @return array
+ * List of contact names.
+ * NOTE: These are raw values from the DB. In current data-model, that means
+ * they are pre-encoded HTML.
+ */
+ private static function getSelectedContactNames() {
+ $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
+ $cacheKey = "civicrm search {$qfKey}";
+
+ $cids = [];
+ // Gymanstic time!
+ foreach (Civi::service('prevnext')->getSelection($cacheKey) as $cacheKey => $values) {
+ $cids = array_unique(array_merge($cids, array_keys($values)));
+ }
+
+ $result = CRM_Utils_SQL_Select::from('civicrm_contact')
+ ->where('id IN (#cids)', ['cids' => $cids])
+ ->execute()
+ ->fetchMap('id', 'sort_name');
+ return $result;
+ }
+
/**
* Given this task's list of targets, produce a hidden group.
*
@@ -483,17 +505,18 @@ public function createHiddenGroup() {
$searchParams = $this->controller->exportValues();
if ($searchParams['radio_ts'] == 'ts_sel') {
// Create a static group.
- $randID = md5(time() . rand(1, 1000)); // groups require a unique name
+ // groups require a unique name
+ $randID = md5(time() . rand(1, 1000));
$grpTitle = "Hidden Group {$randID}";
$grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
if (!$grpID) {
- $groupParams = array(
+ $groupParams = [
'title' => $grpTitle,
'is_active' => 1,
'is_hidden' => 1,
- 'group_type' => array('2' => 1),
- );
+ 'group_type' => ['2' => 1],
+ ];
$group = CRM_Contact_BAO_Group::create($groupParams);
$grpID = $group->id;
@@ -501,31 +524,33 @@ public function createHiddenGroup() {
CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
$newGroupTitle = "Hidden Group {$grpID}";
- $groupParams = array(
+ $groupParams = [
'id' => $grpID,
'name' => CRM_Utils_String::titleToVar($newGroupTitle),
'title' => $newGroupTitle,
- 'group_type' => array('2' => 1),
- );
+ 'group_type' => ['2' => 1],
+ ];
CRM_Contact_BAO_Group::create($groupParams);
}
// note at this point its a static group
- return array($grpID, NULL);
+ return [$grpID, NULL];
}
else {
// Create a smart group.
$ssId = $this->get('ssID');
- $hiddenSmartParams = array(
- 'group_type' => array('2' => 1),
- 'form_values' => $this->get('formValues'),
+ $hiddenSmartParams = [
+ 'group_type' => ['2' => 1],
+ // queryParams have been preprocessed esp WRT any entity reference fields - see +
+ // https://github.com/civicrm/civicrm-core/pull/13250
+ 'form_values' => $this->get('queryParams'),
'saved_search_id' => $ssId,
'search_custom_id' => $this->get('customSearchID'),
'search_context' => $this->get('context'),
- );
+ ];
list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
- return array($smartGroupId, $savedSearchId);
+ return [$smartGroupId, $savedSearchId];
}
}
diff --git a/CRM/Contact/Form/Task/AddToGroup.php b/CRM/Contact/Form/Task/AddToGroup.php
index c77d358534c0..2958f6e98eff 100644
--- a/CRM/Contact/Form/Task/AddToGroup.php
+++ b/CRM/Contact/Form/Task/AddToGroup.php
@@ -1,9 +1,9 @@
_id) {
- $this->addRadio('group_option', ts('Group Options'), $options, array('onclick' => "return showElements();"));
+ $this->addRadio('group_option', ts('Group Options'), $options, ['onclick' => "return showElements();"]);
$this->add('text', 'title', ts('Group Name:') . ' ',
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title')
);
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_Group', $this->_id, 'title')
+ 'objectExists', ['CRM_Contact_DAO_Group', $this->_id, 'title']
);
$this->add('textarea', 'description', ts('Description:') . ' ',
@@ -115,9 +115,9 @@ public function buildQuickForm() {
}
// add select for groups
- $group = array('' => ts('- select group -')) + CRM_Core_PseudoConstant::nestedGroup();
+ $group = ['' => ts('- select group -')] + CRM_Core_PseudoConstant::nestedGroup();
- $groupElement = $this->add('select', 'group_id', ts('Select Group'), $group, FALSE, array('class' => 'crm-select2 huge'));
+ $groupElement = $this->add('select', 'group_id', ts('Select Group'), $group, FALSE, ['class' => 'crm-select2 huge']);
$this->_title = $group[$this->_id];
@@ -125,13 +125,13 @@ public function buildQuickForm() {
$groupElement->freeze();
// also set the group title
- $groupValues = array('id' => $this->_id, 'title' => $this->_title);
+ $groupValues = ['id' => $this->_id, 'title' => $this->_title];
$this->assign_by_ref('group', $groupValues);
}
// Set dynamic page title for 'Add Members Group (confirm)'
if ($this->_id) {
- CRM_Utils_System::setTitle(ts('Add Contacts: %1', array(1 => $this->_title)));
+ CRM_Utils_System::setTitle(ts('Add Contacts: %1', [1 => $this->_title]));
}
else {
CRM_Utils_System::setTitle(ts('Add Contacts to A Group'));
@@ -148,7 +148,7 @@ public function buildQuickForm() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if ($this->_context === 'amtg') {
$defaults['group_id'] = $this->_id;
@@ -162,7 +162,7 @@ public function setDefaultValues() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_task_AddToGroup', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_task_AddToGroup', 'formRule']);
}
/**
@@ -174,7 +174,7 @@ public function addRules() {
* list of errors to be posted back to the form
*/
public static function formRule($params) {
- $errors = array();
+ $errors = [];
if (!empty($params['group_option']) && empty($params['title'])) {
$errors['title'] = "Group Name is a required field";
@@ -193,7 +193,7 @@ public function postProcess() {
$params = $this->controller->exportValues();
$groupOption = CRM_Utils_Array::value('group_option', $params, NULL);
if ($groupOption) {
- $groupParams = array();
+ $groupParams = [];
$groupParams['title'] = $params['title'];
$groupParams['description'] = $params['description'];
$groupParams['visibility'] = "User and User Admin Only";
@@ -219,24 +219,24 @@ public function postProcess() {
list($total, $added, $notAdded) = CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $groupID);
- $status = array(
- ts('%count contact added to group', array(
- 'count' => $added,
- 'plural' => '%count contacts added to group',
- )),
- );
+ $status = [
+ ts('%count contact added to group', [
+ 'count' => $added,
+ 'plural' => '%count contacts added to group',
+ ]),
+ ];
if ($notAdded) {
- $status[] = ts('%count contact was already in group', array(
- 'count' => $notAdded,
- 'plural' => '%count contacts were already in group',
- ));
+ $status[] = ts('%count contact was already in group', [
+ 'count' => $notAdded,
+ 'plural' => '%count contacts were already in group',
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts('Added Contact to %1', array(
- 1 => $groupName,
- 'count' => $added,
- 'plural' => 'Added Contacts to %1',
- )), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts('Added Contact to %1', [
+ 1 => $groupName,
+ 'count' => $added,
+ 'plural' => 'Added Contacts to %1',
+ ]), 'success', ['expires' => 0]);
if ($this->_context === 'amtg') {
CRM_Core_Session::singleton()
diff --git a/CRM/Contact/Form/Task/AddToHousehold.php b/CRM/Contact/Form/Task/AddToHousehold.php
index 7c2598bc8e89..c72e9a096522 100644
--- a/CRM/Contact/Form/Task/AddToHousehold.php
+++ b/CRM/Contact/Form/Task/AddToHousehold.php
@@ -1,9 +1,9 @@
get('contactType');
- CRM_Utils_System::setTitle(ts('Add Contacts to %1', array(1 => $contactType)));
- $this->addElement('text', 'name', ts('Find Target %1', array(1 => $contactType)));
+ CRM_Utils_System::setTitle(ts('Add Contacts to %1', [1 => $contactType]));
+ $this->addElement('text', 'name', ts('Find Target %1', [1 => $contactType]));
$this->add('select',
'relationship_type_id',
ts('Relationship Type'),
- array(
+ [
'' => ts('- select -'),
- ) +
+ ] +
CRM_Contact_BAO_Relationship::getRelationType($contactType), TRUE
);
$searchRows = $this->get('searchRows');
$searchCount = $this->get('searchCount');
if ($searchRows) {
- $checkBoxes = array();
+ $checkBoxes = [];
$chekFlag = 0;
foreach ($searchRows as $id => $row) {
if (!$chekFlag) {
@@ -81,21 +81,21 @@ public function buildQuickForm() {
$this->assign('searchCount', $searchCount);
$this->assign('searchDone', $this->get('searchDone'));
$this->assign('contact_type_display', ts($contactType));
- $this->addElement('submit', $this->getButtonName('refresh'), ts('Search'), array('class' => 'crm-form-submit'));
- $this->addElement('submit', $this->getButtonName('cancel'), ts('Cancel'), array('class' => 'crm-form-submit'));
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Add to %1', array(1 => $contactType)),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addElement('submit', $this->getButtonName('refresh'), ts('Search'), ['class' => 'crm-form-submit']);
+ $this->addElement('submit', $this->getButtonName('cancel'), ts('Cancel'), ['class' => 'crm-form-submit']);
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Add to %1', [1 => $contactType]),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
+
/**
* Add relationships from form.
*/
@@ -106,10 +106,10 @@ public function addRelationships() {
return;
}
$relationshipTypeParts = explode('_', $this->params['relationship_type_id']);
- $params = array(
+ $params = [
'relationship_type_id' => $relationshipTypeParts[0],
'is_active' => 1,
- );
+ ];
$secondaryRelationshipSide = $relationshipTypeParts[1];
$primaryRelationshipSide = $relationshipTypeParts[2];
$primaryFieldName = 'contact_id_' . $primaryRelationshipSide;
@@ -125,33 +125,33 @@ public function addRelationships() {
$relatedContactName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$primaryFieldName],
'display_name');
- $status = array(
- ts('%count %2 %3 relationship created', array(
+ $status = [
+ ts('%count %2 %3 relationship created', [
'count' => $outcome['valid'],
'plural' => '%count %2 %3 relationships created',
2 => $relationshipLabel,
3 => $relatedContactName,
- )),
- );
+ ]),
+ ];
if ($outcome['duplicate']) {
- $status[] = ts('%count was skipped because the contact is already %2 %3', array(
+ $status[] = ts('%count was skipped because the contact is already %2 %3', [
'count' => $outcome['duplicate'],
'plural' => '%count were skipped because the contacts are already %2 %3',
2 => $relationshipLabel,
3 => $relatedContactName,
- ));
+ ]);
}
if ($outcome['invalid']) {
- $status[] = ts('%count relationship was not created because the contact is not of the right type for this relationship', array(
+ $status[] = ts('%count relationship was not created because the contact is not of the right type for this relationship', [
'count' => $outcome['invalid'],
'plural' => '%count relationships were not created because the contact is not of the right type for this relationship',
- ));
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts('Relationship created.', array(
+ CRM_Core_Session::setStatus($status, ts('Relationship created.', [
'count' => $outcome['valid'],
'plural' => 'Relationships created.',
- )), 'success', array('expires' => 0));
+ ]), 'success', ['expires' => 0]);
}
@@ -164,20 +164,20 @@ public function addRelationships() {
*/
public function search(&$form, &$params) {
//max records that will be listed
- $searchValues = array();
+ $searchValues = [];
if (!empty($params['rel_contact'])) {
if (isset($params['rel_contact_id']) &&
is_numeric($params['rel_contact_id'])
) {
- $searchValues[] = array('contact_id', '=', $params['rel_contact_id'], 0, 1);
+ $searchValues[] = ['contact_id', '=', $params['rel_contact_id'], 0, 1];
}
else {
- $searchValues[] = array('sort_name', 'LIKE', $params['rel_contact'], 0, 1);
+ $searchValues[] = ['sort_name', 'LIKE', $params['rel_contact'], 0, 1];
}
}
$contactTypeAdded = FALSE;
- $excludedContactIds = array();
+ $excludedContactIds = [];
if (isset($form->_contactId)) {
$excludedContactIds[] = $form->_contactId;
}
@@ -200,18 +200,18 @@ public function search(&$form, &$params) {
$form->set('contact_type', $type);
$form->set('contact_sub_type', $subType);
if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') {
- $searchValues[] = array('contact_type', '=', $type, 0, 0);
+ $searchValues[] = ['contact_type', '=', $type, 0, 0];
$contactTypeAdded = TRUE;
}
if ($subType) {
- $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0);
+ $searchValues[] = ['contact_sub_type', '=', $subType, 0, 0];
}
}
}
if (!$contactTypeAdded && !empty($params['contact_type'])) {
- $searchValues[] = array('contact_type', '=', $params['contact_type'], 0, 0);
+ $searchValues[] = ['contact_type', '=', $params['contact_type'], 0, 0];
}
// get the count of contact
@@ -224,7 +224,7 @@ public function search(&$form, &$params) {
$result = $query->searchQuery(0, 50, NULL);
$config = CRM_Core_Config::singleton();
- $searchRows = array();
+ $searchRows = [];
//variable is set if only one record is foun and that record already has relationship with the contact
$duplicateRelationship = 0;
diff --git a/CRM/Contact/Form/Task/AddToTag.php b/CRM/Contact/Form/Task/AddToTag.php
index 3ef04b3fc260..db80cfc11985 100644
--- a/CRM/Contact/Form/Task/AddToTag.php
+++ b/CRM/Contact/Form/Task/AddToTag.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Task_AddToTag', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_AddToTag', 'formRule']);
}
/**
@@ -82,7 +82,7 @@ public function addRules() {
* @return array
*/
public static function formRule($form, $rule) {
- $errors = array();
+ $errors = [];
if (empty($form['tag']) && empty($form['contact_taglist'])) {
$errors['_qf_default'] = ts("Please select at least one tag.");
}
@@ -95,7 +95,7 @@ public static function formRule($form, $rule) {
public function postProcess() {
//get the submitted values in an array
$params = $this->controller->exportValues($this->_name);
- $contactTags = $tagList = array();
+ $contactTags = $tagList = [];
// check if contact tags exists
if (!empty($params['tag'])) {
@@ -132,22 +132,22 @@ public function postProcess() {
// merge contact and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($contactTags, $tagList);
- $this->_name = array();
+ $this->_name = [];
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $added, $notAdded) = CRM_Core_BAO_EntityTag::addEntitiesToTag($this->_contactIds, $key,
'civicrm_contact', FALSE);
- $status = array(ts('%count contact tagged', array('count' => $added, 'plural' => '%count contacts tagged')));
+ $status = [ts('%count contact tagged', ['count' => $added, 'plural' => '%count contacts tagged'])];
if ($notAdded) {
- $status[] = ts('%count contact already had this tag', array(
- 'count' => $notAdded,
- 'plural' => '%count contacts already had this tag',
- ));
+ $status[] = ts('%count contact already had this tag', [
+ 'count' => $notAdded,
+ 'plural' => '%count contacts already had this tag',
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts("Added Tag %1", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts("Added Tag %1", [1 => $this->_tags[$key]]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Contact/Form/Task/AlterPreferences.php b/CRM/Contact/Form/Task/AlterPreferences.php
index ef487ae253ab..cd596f0c9822 100644
--- a/CRM/Contact/Form/Task/AlterPreferences.php
+++ b/CRM/Contact/Form/Task/AlterPreferences.php
@@ -1,9 +1,9 @@
addRadio('actionTypeOption', ts('actionTypeOption'), $options);
@@ -57,7 +57,7 @@ public function buildQuickForm() {
}
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_Task_AlterPreferences', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_AlterPreferences', 'formRule']);
}
/**
@@ -68,7 +68,7 @@ public function addRules() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults['actionTypeOption'] = 0;
return $defaults;
@@ -81,7 +81,7 @@ public function setDefaultValues() {
* @return array
*/
public static function formRule($form, $rule) {
- $errors = array();
+ $errors = [];
if (empty($form['pref']) && empty($form['contact_taglist'])) {
$errors['_qf_default'] = ts("Please select at least one privacy option.");
}
@@ -115,19 +115,19 @@ public function postProcess() {
}
// Status message
$privacyOptions = CRM_Core_SelectValues::privacy();
- $status = array();
+ $status = [];
foreach ($privacyValues as $privacy_key => $privacy_value) {
$label = $privacyOptions[$privacy_key];
- $status[] = $privacyValueNew ? ts("Added '%1'", array(1 => $label)) : ts("Removed '%1'", array(1 => $label));
+ $status[] = $privacyValueNew ? ts("Added '%1'", [1 => $label]) : ts("Removed '%1'", [1 => $label]);
}
$status = '
' . implode('
', $status) . '
';
if ($count > 1) {
- $title = ts('%1 Contacts Updated', array(1 => $count));
+ $title = ts('%1 Contacts Updated', [1 => $count]);
}
else {
$name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact_id, 'display_name');
- $title = ts('%1 Updated', array(1 => $name));
+ $title = ts('%1 Updated', [1 => $name]);
}
CRM_Core_Session::setStatus($status, $title, 'success');
diff --git a/CRM/Contact/Form/Task/Batch.php b/CRM/Contact/Form/Task/Batch.php
index ca607f04d6ab..d0bc8ac47756 100644
--- a/CRM/Contact/Form/Task/Batch.php
+++ b/CRM/Contact/Form/Task/Batch.php
@@ -1,9 +1,9 @@
_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -101,25 +105,24 @@ public function buildQuickForm() {
//FIX ME: phone ext field is added at the end and it gets removed because of below code
//$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Update Contact(s)'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Update Contact(s)'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_contactIds);
// if below fields are missing we should not reset sort name / display name
// CRM-6794
- $preserveDefaultsArray = array(
+ $preserveDefaultsArray = [
'first_name',
'last_name',
'middle_name',
@@ -127,7 +130,7 @@ public function buildQuickForm() {
'prefix_id',
'suffix_id',
'household_name',
- );
+ ];
foreach ($this->_contactIds as $contactId) {
$profileFields = $this->_fields;
@@ -147,11 +150,11 @@ public function buildQuickForm() {
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_BatchUpdateProfile_next') {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple contacts."), ts('Some Fields Excluded'), 'info');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple contacts."), ts('Some Fields Excluded'), 'info');
}
$this->addDefaultButtons(ts('Update Contacts'));
- $this->addFormRule(array('CRM_Contact_Form_Task_Batch', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_Batch', 'formRule']);
}
/**
@@ -165,9 +168,9 @@ public function setDefaultValues() {
return NULL;
}
- $defaults = $sortName = array();
+ $defaults = $sortName = [];
foreach ($this->_contactIds as $contactId) {
- $details[$contactId] = array();
+ $details[$contactId] = [];
//build sortname
$sortName[$contactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
@@ -193,8 +196,8 @@ public function setDefaultValues() {
* true if no errors, else array of errors
*/
public static function formRule($fields) {
- $errors = array();
- $externalIdentifiers = array();
+ $errors = [];
+ $externalIdentifiers = [];
foreach ($fields['field'] as $componentId => $field) {
foreach ($field as $fieldName => $fieldValue) {
if ($fieldName == 'external_identifier') {
@@ -217,6 +220,9 @@ public static function formRule($fields) {
public function postProcess() {
$params = $this->exportValues();
+ // @todo extract submit functions &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test
+ // handling of custom data, specifically checkbox fields.
$ufGroupId = $this->get('ufGroupId');
$notify = NULL;
$inValidSubtypeCnt = 0;
@@ -245,10 +251,10 @@ public function postProcess() {
CRM_Core_Session::setStatus('', ts("Updates Saved"), 'success');
if ($inValidSubtypeCnt) {
- CRM_Core_Session::setStatus(ts('Contact Subtype field of 1 contact has not been updated.', array(
- 'plural' => 'Contact Subtype field of %count contacts has not been updated.',
- 'count' => $inValidSubtypeCnt,
- )), ts('Invalid Subtype'));
+ CRM_Core_Session::setStatus(ts('Contact Subtype field of 1 contact has not been updated.', [
+ 'plural' => 'Contact Subtype field of %count contacts has not been updated.',
+ 'count' => $inValidSubtypeCnt,
+ ]), ts('Invalid Subtype'));
}
}
@@ -286,7 +292,7 @@ public static function parseStreetAddress(&$contactValues, &$form) {
return;
}
- $allParseValues = array();
+ $allParseValues = [];
foreach ($contactValues as $key => $value) {
if (strpos($key, $addressFldKey) !== FALSE) {
$locTypeId = substr($key, strlen($addressFldKey) + 1);
diff --git a/CRM/Contact/Form/Task/Delete.php b/CRM/Contact/Form/Task/Delete.php
index 33b4c4bb321c..3411f67d05f0 100644
--- a/CRM/Contact/Form/Task/Delete.php
+++ b/CRM/Contact/Form/Task/Delete.php
@@ -1,9 +1,9 @@
_contactIds = array($cid);
+ $this->_contactIds = [$cid];
$this->_single = TRUE;
$this->assign('totalSelectedContacts', 1);
}
@@ -100,7 +101,7 @@ public function preProcess() {
$this->_sharedAddressMessage = $this->get('sharedAddressMessage');
if (!$this->_restore && !$this->_sharedAddressMessage) {
// we check for each contact for shared contact address
- $sharedContactList = array();
+ $sharedContactList = [];
$sharedAddressCount = 0;
foreach ($this->_contactIds as $contactId) {
// check if a contact that is being deleted has any shared addresses
@@ -114,25 +115,25 @@ public function preProcess() {
}
}
- $this->_sharedAddressMessage = array(
+ $this->_sharedAddressMessage = [
'count' => $sharedAddressCount,
'contactList' => $sharedContactList,
- );
+ ];
if ($sharedAddressCount > 0) {
if (count($this->_contactIds) > 1) {
// more than one contact deleted
- $message = ts('One of the selected contacts has an address record that is shared with 1 other contact.', array(
- 'plural' => 'One or more selected contacts have address records which are shared with %count other contacts.',
- 'count' => $sharedAddressCount,
- ));
+ $message = ts('One of the selected contacts has an address record that is shared with 1 other contact.', [
+ 'plural' => 'One or more selected contacts have address records which are shared with %count other contacts.',
+ 'count' => $sharedAddressCount,
+ ]);
}
else {
// only one contact deleted
- $message = ts('This contact has an address record which is shared with 1 other contact.', array(
- 'plural' => 'This contact has an address record which is shared with %count other contacts.',
- 'count' => $sharedAddressCount,
- ));
+ $message = ts('This contact has an address record which is shared with 1 other contact.', [
+ 'plural' => 'This contact has an address record which is shared with %count other contacts.',
+ 'count' => $sharedAddressCount,
+ ]);
}
CRM_Core_Session::setStatus($message . ' ' . ts('Shared addresses will not be removed or altered but will no longer be shared.'), ts('Shared Addesses Owner'));
}
@@ -150,7 +151,7 @@ public function buildQuickForm() {
if ($this->_single) {
// also fix the user context stack in case the user hits cancel
- $context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'basic');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'basic');
if ($context == 'search' && CRM_Utils_Rule::qfKey($this->_searchKey)) {
$urlParams = "&context=$context&key=$this->_searchKey";
}
@@ -168,7 +169,7 @@ public function buildQuickForm() {
$this->addDefaultButtons($label, 'done');
}
- $this->addFormRule(array('CRM_Contact_Form_Task_Delete', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contact_Form_Task_Delete', 'formRule'], $this);
}
/**
@@ -186,7 +187,7 @@ public function buildQuickForm() {
*/
public static function formRule($fields, $files, $self) {
// CRM-12929
- $error = array();
+ $error = [];
if ($self->_skipUndelete) {
CRM_Financial_BAO_FinancialItem::checkContactPresent($self->_contactIds, $error);
}
@@ -200,7 +201,7 @@ public function postProcess() {
$session = CRM_Core_Session::singleton();
$currentUserId = $session->get('userID');
- $context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'basic');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'basic');
$urlParams = 'force=1';
$urlString = "civicrm/contact/search/$context";
@@ -222,15 +223,15 @@ public function postProcess() {
// Delete/Restore Contacts. Report errors.
$deleted = 0;
- $not_deleted = array();
+ $not_deleted = [];
foreach ($this->_contactIds as $cid) {
$name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name');
if (CRM_Contact_BAO_Contact::checkDomainContact($cid)) {
- $session->setStatus(ts("'%1' cannot be deleted because the information is used for special system purposes.", array(1 => $name)), 'Cannot Delete Domain Contact', 'error');
+ $session->setStatus(ts("'%1' cannot be deleted because the information is used for special system purposes.", [1 => $name]), 'Cannot Delete Domain Contact', 'error');
continue;
}
if ($currentUserId == $cid && !$this->_restore) {
- $session->setStatus(ts("You are currently logged in as '%1'. You cannot delete yourself.", array(1 => $name)), 'Unable To Delete', 'error');
+ $session->setStatus(ts("You are currently logged in as '%1'. You cannot delete yourself.", [1 => $name]), 'Unable To Delete', 'error');
continue;
}
if (CRM_Contact_BAO_Contact::deleteContact($cid, $this->_restore, $this->_skipUndelete)) {
@@ -245,25 +246,25 @@ public function postProcess() {
$title = ts('Deleted');
if ($this->_restore) {
$title = ts('Restored');
- $status = ts('%1 has been restored from the trash.', array(
- 1 => $name,
- 'plural' => '%count contacts restored from trash.',
- 'count' => $deleted,
- ));
+ $status = ts('%1 has been restored from the trash.', [
+ 1 => $name,
+ 'plural' => '%count contacts restored from trash.',
+ 'count' => $deleted,
+ ]);
}
elseif ($this->_skipUndelete) {
- $status = ts('%1 has been permanently deleted.', array(
- 1 => $name,
- 'plural' => '%count contacts permanently deleted.',
- 'count' => $deleted,
- ));
+ $status = ts('%1 has been permanently deleted.', [
+ 1 => $name,
+ 'plural' => '%count contacts permanently deleted.',
+ 'count' => $deleted,
+ ]);
}
else {
- $status = ts('%1 has been moved to the trash.', array(
- 1 => $name,
- 'plural' => '%count contacts moved to trash.',
- 'count' => $deleted,
- ));
+ $status = ts('%1 has been moved to the trash.', [
+ 1 => $name,
+ 'plural' => '%count contacts moved to trash.',
+ 'count' => $deleted,
+ ]);
}
$session->setStatus($status, $title, 'success');
}
@@ -283,7 +284,7 @@ public function postProcess() {
}
$message .= '
';
- $session->setStatus($message, ts('Shared Addesses Owner Deleted'), 'info', array('expires' => 0));
+ $session->setStatus($message, ts('Shared Addesses Owner Deleted'), 'info', ['expires' => 0]);
$this->set('sharedAddressMessage', NULL);
}
diff --git a/CRM/Contact/Form/Task/Email.php b/CRM/Contact/Form/Task/Email.php
index efc5ac5616b8..d8dd851e3349 100644
--- a/CRM/Contact/Form/Task/Email.php
+++ b/CRM/Contact/Form/Task/Email.php
@@ -1,9 +1,9 @@
_caseId = CRM_Utils_Request::retrieve('caseid', 'String', $this, FALSE);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$cid = CRM_Utils_Request::retrieve('cid', 'String', $this, FALSE);
// Allow request to specify email id rather than contact id
$toEmailId = CRM_Utils_Request::retrieve('email_id', 'String', $this);
if ($toEmailId) {
- $toEmail = civicrm_api('email', 'getsingle', array('version' => 3, 'id' => $toEmailId));
+ $toEmail = civicrm_api('email', 'getsingle', ['version' => 3, 'id' => $toEmailId]);
if (!empty($toEmail['email']) && !empty($toEmail['contact_id'])) {
$this->_toEmail = $toEmail;
}
@@ -115,7 +115,7 @@ public function preProcess() {
if ($cid) {
$cid = explode(',', $cid);
- $displayName = array();
+ $displayName = [];
foreach ($cid as $val) {
$displayName[] = CRM_Contact_BAO_Contact::displayName($val);
@@ -131,7 +131,6 @@ public function preProcess() {
if (!$cid && $this->_context != 'standalone') {
parent::preProcess();
}
- CRM_Contact_Form_Task_EmailCommon::bounceIfSimpleMailLimitExceeded(count($this->_contactIds));
$this->assign('single', $this->_single);
if (CRM_Core_Permission::check('administer CiviCRM')) {
@@ -164,6 +163,13 @@ public function postProcess() {
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
+
+ if (isset($this->_caseId) || isset($this->_caseIds)) {
+ // For a single case, list tokens relevant for only that case type
+ $caseTypeId = isset($this->_caseId) ? CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $this->_caseId, 'case_type_id') : NULL;
+ $tokens += CRM_Core_SelectValues::caseTokens($caseTypeId);
+ }
+
return $tokens;
}
diff --git a/CRM/Contact/Form/Task/EmailCommon.php b/CRM/Contact/Form/Task/EmailCommon.php
index 88be4a082bdf..5006f9d5321c 100644
--- a/CRM/Contact/Form/Task/EmailCommon.php
+++ b/CRM/Contact/Form/Task/EmailCommon.php
@@ -1,9 +1,9 @@
_single = TRUE;
}
- $form->_emails = $emails = array();
-
- $contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
- $fromDisplayName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
-
- $form->_contactIds = array($contactID);
- $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
+ $form->_emails = array();
- $form->_onHold = array();
-
- foreach ($contactEmails as $emailId => $item) {
- $email = $item['email'];
- if (!$email && (count($emails) < 1)) {
- // set it if no emails are present at all
- $form->_noEmails = TRUE;
- }
- else {
- if ($email) {
- if (in_array($email, $emails)) {
- // CRM-3624
- continue;
- }
+ // @TODO remove these line and to it somewhere more appropriate. Currently some classes (e.g Case
+ // are having to re-write contactIds afterwards due to this inappropriate variable setting
+ // If we don't have any contact IDs, use the logged in contact ID
+ $form->_contactIds = $form->_contactIds ?: [CRM_Core_Session::getLoggedInContactID()];
- $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
- $form->_onHold[$emailId] = $item['on_hold'];
- $form->_noEmails = FALSE;
- }
- }
- if (!empty($email)) {
- $form->_emails[$emailId] = $emails[$emailId];
- $emails[$emailId] .= $item['locationType'];
+ $fromEmailValues = CRM_Core_BAO_Email::getFromEmail();
- if ($item['is_primary']) {
- $emails[$emailId] .= ' ' . ts('(preferred)');
- }
- $emails[$emailId] = htmlspecialchars($emails[$emailId]);
- }
+ $form->_noEmails = FALSE;
+ if (empty($fromEmailValues)) {
+ $form->_noEmails = TRUE;
}
-
$form->assign('noEmails', $form->_noEmails);
if ($bounce) {
if ($form->_noEmails) {
- CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address'));
+ CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address and no from addresses have been configured.'));
}
}
- // now add domain from addresses
- $domainEmails = self::domainEmails();
- foreach ($domainEmails as $domainEmail => $email) {
- $form->_emails[$domainEmail] = $domainEmail;
+ $form->_emails = $fromEmailValues;
+ $defaults = array();
+ $form->_fromEmails = $fromEmailValues;
+ if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ $defaults['from_email_address'] = current(CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE));
}
- $form->_fromEmails = CRM_Utils_Array::crmArrayMerge($emails, $domainEmails);
- $form->_fromEmails = array_filter($form->_fromEmails);
if (is_numeric(key($form->_fromEmails))) {
// Add signature
$defaultEmail = civicrm_api3('email', 'getsingle', array('id' => key($form->_fromEmails)));
@@ -136,8 +104,8 @@ public static function preProcessFromAddress(&$form, $bounce = TRUE) {
if (!empty($defaultEmail['signature_text'])) {
$defaults['text_message'] = "\n\n--\n" . $defaultEmail['signature_text'];
}
- $form->setDefaults($defaults);
}
+ $form->setDefaults($defaults);
}
/**
@@ -156,6 +124,7 @@ public static function buildQuickForm(&$form) {
if (count($form->_contactIds) > 1) {
$form->_single = FALSE;
}
+ CRM_Contact_Form_Task_EmailCommon::bounceIfSimpleMailLimitExceeded(count($form->_contactIds));
$emailAttributes = array(
'class' => 'huge',
@@ -287,7 +256,7 @@ public static function buildQuickForm(&$form) {
$form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
- $form->add('select', 'fromEmailAddress', ts('From'), $form->_fromEmails, TRUE, array('class' => 'crm-select2 huge'));
+ $form->add('select', 'from_email_address', ts('From'), $form->_fromEmails, TRUE);
CRM_Mailing_BAO_Mailing::commonCompose($form);
@@ -347,7 +316,7 @@ public static function buildQuickForm(&$form) {
);
//add followup date
- $form->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
+ $form->add('datepicker', 'followup_date', ts('in'));
foreach ($fields as $field => $values) {
if (!empty($fields[$field])) {
@@ -427,7 +396,11 @@ public static function postProcess(&$form) {
public static function submit(&$form, $formValues) {
self::saveMessageTemplate($formValues);
- $from = CRM_Utils_Array::value($formValues['fromEmailAddress'], $form->_emails);
+ $from = CRM_Utils_Array::value('from_email_address', $formValues);
+ // dev/core#357 User Emails are keyed by their id so that the Signature is able to be added
+ // If we have had a contact email used here the value returned from the line above will be the
+ // numerical key where as $from for use in the sendEmail in Activity needs to be of format of "To Name"
+ $from = CRM_Utils_Mail::formatFromAddress($from);
$subject = $formValues['subject'];
// CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
@@ -529,7 +502,6 @@ public static function submit(&$form, $formValues) {
$params['followup_activity_type_id'] = $formValues['followup_activity_type_id'];
$params['followup_activity_subject'] = $formValues['followup_activity_subject'];
$params['followup_date'] = $formValues['followup_date'];
- $params['followup_date_time'] = $formValues['followup_date_time'];
$params['target_contact_id'] = $form->_contactIds;
$params['followup_assignee_contact_id'] = explode(',', $formValues['followup_assignee_contact_id']);
$followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activityId, $params);
@@ -554,9 +526,9 @@ public static function submit(&$form, $formValues) {
$count_success = count($form->_toContactDetails);
CRM_Core_Session::setStatus(ts('One message was sent successfully. ', array(
- 'plural' => '%count messages were sent successfully. ',
- 'count' => $count_success,
- )) . $followupStatus, ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $count_success)), 'success');
+ 'plural' => '%count messages were sent successfully. ',
+ 'count' => $count_success,
+ )) . $followupStatus, ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $count_success)), 'success');
}
// Display the name and number of contacts for those email is not sent.
@@ -575,9 +547,9 @@ public static function submit(&$form, $formValues) {
}
$status = '(' . ts('because no email address on file or communication preferences specify DO NOT EMAIL or Contact is deceased or Primary email address is On Hold') . ')
' . implode('
', $not_sent) . '
';
CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array(
- 'count' => count($emailsNotSent),
- 'plural' => '%count Messages Not Sent',
- )), 'info');
+ 'count' => count($emailsNotSent),
+ 'plural' => '%count Messages Not Sent',
+ )), 'info');
}
if (isset($form->_caseId)) {
diff --git a/CRM/Contact/Form/Task/HookSample.php b/CRM/Contact/Form/Task/HookSample.php
index 76fc66491a2f..a93a92a7ed2d 100644
--- a/CRM/Contact/Form/Task/HookSample.php
+++ b/CRM/Contact/Form/Task/HookSample.php
@@ -1,9 +1,9 @@
fetch()) {
- $rows[] = array(
+ $rows[] = [
'id' => $dao->contact_id,
'name' => $dao->name,
'contact_type' => $dao->contact_type,
'email' => $dao->email,
- );
+ ];
}
$this->assign('rows', $rows);
diff --git a/CRM/Contact/Form/Task/Label.php b/CRM/Contact/Form/Task/Label.php
index 24e1dce7fe84..674d1d1ad310 100644
--- a/CRM/Contact/Form/Task/Label.php
+++ b/CRM/Contact/Form/Task/Label.php
@@ -1,9 +1,9 @@
add('select', 'label_name', ts('Select Label'), array('' => ts('- select label -')) + $label, TRUE);
+ $form->add('select', 'label_name', ts('Select Label'), ['' => ts('- select label -')] + $label, TRUE);
// add select for Location Type
$form->addElement('select', 'location_type_id', ts('Select Location'),
- array(
+ [
'' => ts('Primary'),
- ) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), TRUE
+ ] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), TRUE
);
// checkbox for SKIP contacts with Do Not Mail privacy option
@@ -77,17 +77,17 @@ public static function buildLabelForm($form) {
$form->add('checkbox', 'merge_same_address', ts('Merge labels for contacts with the same address'), NULL);
$form->add('checkbox', 'merge_same_household', ts('Merge labels for contacts belonging to the same household'), NULL);
- $form->addButtons(array(
- array(
+ $form->addButtons([
+ [
'type' => 'submit',
'name' => ts('Make Mailing Labels'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Done'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -97,7 +97,7 @@ public static function buildLabelForm($form) {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$format = CRM_Core_BAO_LabelFormat::getDefaultValues();
$defaults['label_name'] = CRM_Utils_Array::value('name', $format);
$defaults['do_not_mail'] = 1;
@@ -126,10 +126,10 @@ public function postProcess() {
}
//build the returnproperties
- $returnProperties = array('display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1);
+ $returnProperties = ['display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1];
$mailingFormat = Civi::settings()->get('mailing_format');
- $mailingFormatProperties = array();
+ $mailingFormatProperties = [];
if ($mailingFormat) {
$mailingFormatProperties = CRM_Utils_Token::getReturnProperties($mailingFormat);
$returnProperties = array_merge($returnProperties, $mailingFormatProperties);
@@ -139,7 +139,7 @@ public function postProcess() {
unset($mailingFormatProperties['addressee']);
}
- $customFormatProperties = array();
+ $customFormatProperties = [];
if (stristr($mailingFormat, 'custom_')) {
foreach ($mailingFormatProperties as $token => $true) {
if (substr($token, 0, 7) == 'custom_') {
@@ -172,38 +172,38 @@ public function postProcess() {
}
//get the contacts information
- $params = array();
+ $params = [];
if (!empty($fv['location_type_id'])) {
$locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$locName = $locType[$fv['location_type_id']];
- $location = array('location' => array("{$locName}" => $address));
+ $location = ['location' => ["{$locName}" => $address]];
$returnProperties = array_merge($returnProperties, $location);
- $params[] = array('location_type', '=', array(1 => $fv['location_type_id']), 0, 0);
+ $params[] = ['location_type', '=', [1 => $fv['location_type_id']], 0, 0];
}
else {
$returnProperties = array_merge($returnProperties, $address);
}
- $rows = array();
+ $rows = [];
foreach ($this->_contactIds as $key => $contactID) {
- $params[] = array(
+ $params[] = [
CRM_Core_Form::CB_PREFIX . $contactID,
'=',
1,
0,
0,
- );
+ ];
}
// fix for CRM-2651
if (!empty($fv['do_not_mail'])) {
- $params[] = array('do_not_mail', '=', 0, 0, 0);
+ $params[] = ['do_not_mail', '=', 0, 0, 0];
}
// fix for CRM-2613
- $params[] = array('is_deceased', '=', 0, 0, 0);
+ $params[] = ['is_deceased', '=', 0, 0, 0];
- $custom = array();
+ $custom = [];
foreach ($returnProperties as $name => $dontCare) {
$cfID = CRM_Core_BAO_CustomField::getKeyID($name);
if ($cfID) {
@@ -226,9 +226,9 @@ public function postProcess() {
'CRM_Contact_Form_Task_Label'
);
- $tokens = array();
+ $tokens = [];
CRM_Utils_Hook::tokens($tokens);
- $tokenFields = array();
+ $tokenFields = [];
foreach ($tokens as $category => $catTokens) {
foreach ($catTokens as $token => $tokenName) {
$tokenFields[] = $token;
@@ -269,8 +269,8 @@ public function postProcess() {
$rows[$value][$field] = $fieldValue;
}
- $valuesothers = array();
- $paramsothers = array('contact_id' => $value);
+ $valuesothers = [];
+ $paramsothers = ['contact_id' => $value];
$valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
if (!empty($fv['location_type_id'])) {
foreach ($valuesothers as $vals) {
@@ -278,12 +278,12 @@ public function postProcess() {
CRM_Utils_Array::value('location_type_id', $fv)
) {
foreach ($vals as $k => $v) {
- if (in_array($k, array(
+ if (in_array($k, [
'email',
'phone',
'im',
'openid',
- ))) {
+ ])) {
if ($k == 'im') {
$rows[$value][$k] = $v['1']['name'];
}
@@ -326,14 +326,14 @@ public function postProcess() {
if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) {
$val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods));
$comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
- $temp = array();
+ $temp = [];
foreach ($val as $vals) {
$temp[] = $comm[$vals];
}
$row['preferred_communication_method'] = implode(', ', $temp);
}
$row['id'] = $id;
- $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields);
+ $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $tokenFields);
// CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
// On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
@@ -346,12 +346,12 @@ public function postProcess() {
}
$formatted = implode("\n", $lines);
}
- $rows[$id] = array($formatted);
+ $rows[$id] = [$formatted];
}
//call function to create labels
self::createLabel($rows, $fv['label_name']);
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
diff --git a/CRM/Contact/Form/Task/LabelCommon.php b/CRM/Contact/Form/Task/LabelCommon.php
index 57376f885c39..74bdc83cb185 100644
--- a/CRM/Contact/Form/Task/LabelCommon.php
+++ b/CRM/Contact/Form/Task/LabelCommon.php
@@ -1,9 +1,9 @@
Output($fileName, 'D');
}
-
/**
* Get the rows for the labels.
*
@@ -80,21 +79,21 @@ public static function createLabel(&$contactRows, &$format, $fileName = 'Mailing
*/
public static function getRows($contactIDs, $locationTypeID, $respectDoNotMail, $mergeSameAddress, $mergeSameHousehold) {
$locName = NULL;
- $rows = array();
+ $rows = [];
//get the address format sequence from the config file
$addressReturnProperties = CRM_Contact_Form_Task_LabelCommon::getAddressReturnProperties();
//build the return properties
- $returnProperties = array('display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1);
+ $returnProperties = ['display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1];
$mailingFormat = Civi::settings()->get('mailing_format');
- $mailingFormatProperties = array();
+ $mailingFormatProperties = [];
if ($mailingFormat) {
$mailingFormatProperties = CRM_Utils_Token::getReturnProperties($mailingFormat);
$returnProperties = array_merge($returnProperties, $mailingFormatProperties);
}
- $customFormatProperties = array();
+ $customFormatProperties = [];
if (stristr($mailingFormat, 'custom_')) {
foreach ($mailingFormatProperties as $token => $true) {
if (substr($token, 0, 7) == 'custom_') {
@@ -113,30 +112,30 @@ public static function getRows($contactIDs, $locationTypeID, $respectDoNotMail,
}
//get the contacts information
- $params = $custom = array();
+ $params = $custom = [];
foreach ($contactIDs as $key => $contactID) {
- $params[] = array(
+ $params[] = [
CRM_Core_Form::CB_PREFIX . $contactID,
'=',
1,
0,
0,
- );
+ ];
}
// fix for CRM-2651
if (!empty($respectDoNotMail['do_not_mail'])) {
- $params[] = array('do_not_mail', '=', 0, 0, 0);
+ $params[] = ['do_not_mail', '=', 0, 0, 0];
}
// fix for CRM-2613
- $params[] = array('is_deceased', '=', 0, 0, 0);
+ $params[] = ['is_deceased', '=', 0, 0, 0];
if ($locationTypeID) {
$locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$locName = $locType[$locationTypeID];
- $location = array('location' => array("{$locName}" => $addressReturnProperties));
+ $location = ['location' => ["{$locName}" => $addressReturnProperties]];
$returnProperties = array_merge($returnProperties, $location);
- $params[] = array('location_type', '=', array($locationTypeID => 1), 0, 0);
+ $params[] = ['location_type', '=', [$locationTypeID => 1], 0, 0];
}
else {
$returnProperties = array_merge($returnProperties, $addressReturnProperties);
@@ -193,8 +192,8 @@ public static function getRows($contactIDs, $locationTypeID, $respectDoNotMail,
$rows[$value][$field] = $fieldValue;
}
- $valuesothers = array();
- $paramsothers = array('contact_id' => $value);
+ $valuesothers = [];
+ $paramsothers = ['contact_id' => $value];
$valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
if ($locationTypeID) {
foreach ($valuesothers as $vals) {
@@ -202,12 +201,12 @@ public static function getRows($contactIDs, $locationTypeID, $respectDoNotMail,
$locationTypeID
) {
foreach ($vals as $k => $v) {
- if (in_array($k, array(
+ if (in_array($k, [
'email',
'phone',
'im',
'openid',
- ))) {
+ ])) {
if ($k == 'im') {
$rows[$value][$k] = $v['1']['name'];
}
@@ -240,7 +239,7 @@ public static function getRows($contactIDs, $locationTypeID, $respectDoNotMail,
}
}
// sigh couldn't extract out tokenfields yet
- return array($rows, $tokenFields);
+ return [$rows, $tokenFields];
}
/**
@@ -269,7 +268,7 @@ public static function getAddressReturnProperties() {
*/
public static function getTokenData(&$contacts) {
$mailingFormat = Civi::settings()->get('mailing_format');
- $tokens = $tokenFields = array();
+ $tokens = $tokenFields = [];
$messageToken = CRM_Utils_Token::getTokens($mailingFormat);
// also get all token values
@@ -298,8 +297,8 @@ public static function getTokenData(&$contacts) {
*/
public function mergeSameHousehold(&$rows) {
// group selected contacts by type
- $individuals = array();
- $households = array();
+ $individuals = [];
+ $households = [];
foreach ($rows as $contact_id => $row) {
if ($row['contact_type'] == 'Household') {
$households[$contact_id] = $row;
diff --git a/CRM/Contact/Form/Task/Map.php b/CRM/Contact/Form/Task/Map.php
index 7f0bc3ad01e2..82e1af323efa 100644
--- a/CRM/Contact/Form/Task/Map.php
+++ b/CRM/Contact/Form/Task/Map.php
@@ -1,9 +1,9 @@
assign('profileGID', $profileGID);
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$type = 'Contact';
if ($cid) {
- $ids = array($cid);
+ $ids = [$cid];
$this->_single = TRUE;
if ($profileGID) {
// this does a check and ensures that the user has permission on this profile
@@ -113,14 +113,13 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
/**
@@ -221,14 +220,14 @@ public static function createMapXML($ids, $locationId, &$page, $addBreadCrumb, $
}
}
- $center = array(
+ $center = [
'lat' => (float ) $sumLat / count($locations),
'lng' => (float ) $sumLng / count($locations),
- );
- $span = array(
+ ];
+ $span = [
'lat' => (float ) ($maxLat - $minLat),
'lng' => (float ) ($maxLng - $minLng),
- );
+ ];
$page->assign_by_ref('center', $center);
$page->assign_by_ref('span', $span);
}
diff --git a/CRM/Contact/Form/Task/Map/Event.php b/CRM/Contact/Form/Task/Map/Event.php
index 257fc1b1a843..496e172f6763 100644
--- a/CRM/Contact/Form/Task/Map/Event.php
+++ b/CRM/Contact/Form/Task/Map/Event.php
@@ -1,9 +1,9 @@
assign('single', FALSE);
$this->assign('skipLocationType', TRUE);
+ $is_public = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $ids, 'is_public');
+ if ($is_public == 0) {
+ CRM_Utils_System::addHTMLHead('');
+ }
}
/**
diff --git a/CRM/Contact/Form/Task/Merge.php b/CRM/Contact/Form/Task/Merge.php
index 9bbdf4e223d5..80359da7af4a 100644
--- a/CRM/Contact/Form/Task/Merge.php
+++ b/CRM/Contact/Form/Task/Merge.php
@@ -1,9 +1,9 @@
_contactIds)) {
$contactIds = array_unique($this->_contactIds);
}
@@ -51,7 +51,7 @@ public function preProcess() {
}
// do check for same contact type.
- $contactTypes = array();
+ $contactTypes = [];
if (!$statusMsg) {
$sql = "SELECT contact_type FROM civicrm_contact WHERE id IN (" . implode(',', $contactIds) . ")";
$contact = CRM_Core_DAO::executeQuery($sql);
diff --git a/CRM/Contact/Form/Task/PDF.php b/CRM/Contact/Form/Task/PDF.php
index 217cf7af1121..67f42d2c30f3 100644
--- a/CRM/Contact/Form/Task/PDF.php
+++ b/CRM/Contact/Form/Task/PDF.php
@@ -1,9 +1,9 @@
_caseId = CRM_Utils_Request::retrieve('caseid', 'Positive', $this, FALSE);
+ $this->_caseId = CRM_Utils_Request::retrieve('caseid', 'CommaSeparatedIntegers', $this, FALSE);
+ if (!empty($this->_caseId) && strpos($this->_caseId, ',')) {
+ $this->_caseIds = explode(',', $this->_caseId);
+ unset($this->_caseId);
+ }
// retrieve contact ID if this is 'single' mode
- $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
+ $cid = CRM_Utils_Request::retrieve('cid', 'CommaSeparatedIntegers', $this, FALSE);
if ($cid) {
// this is true in non-search context / single mode
@@ -73,7 +77,6 @@ public function preProcess() {
if ($cid) {
CRM_Contact_Form_Task_PDFLetterCommon::preProcessSingle($this, $cid);
$this->_single = TRUE;
- $this->_cid = $cid;
}
else {
parent::preProcess();
@@ -85,9 +88,9 @@ public function preProcess() {
* Set default values for the form.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_activityId)) {
- $params = array('id' => $this->_activityId);
+ $params = ['id' => $this->_activityId];
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
$defaults['html_message'] = CRM_Utils_Array::value('details', $defaults);
}
@@ -118,8 +121,9 @@ public function postProcess() {
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
- if (isset($this->_caseId)) {
- $caseTypeId = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $this->_caseId, 'case_type_id');
+ if (isset($this->_caseId) || isset($this->_caseIds)) {
+ // For a single case, list tokens relevant for only that case type
+ $caseTypeId = isset($this->_caseId) ? CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $this->_caseId, 'case_type_id') : NULL;
$tokens += CRM_Core_SelectValues::caseTokens($caseTypeId);
}
return $tokens;
diff --git a/CRM/Contact/Form/Task/PDFLetterCommon.php b/CRM/Contact/Form/Task/PDFLetterCommon.php
index 71df969cb3f3..b52b24d76745 100644
--- a/CRM/Contact/Form/Task/PDFLetterCommon.php
+++ b/CRM/Contact/Form/Task/PDFLetterCommon.php
@@ -1,9 +1,9 @@
string $label).
*/
public static function getLoggingOptions() {
- return array(
+ return [
'none' => ts('Do not record'),
'multiple' => ts('Multiple activities (one per contact)'),
'combined' => ts('One combined activity'),
'combined-attached' => ts('One combined activity plus one file attachment'),
// 'multiple-attached' <== not worth the work
- );
+ ];
}
/**
@@ -58,8 +58,9 @@ public static function getLoggingOptions() {
* @param CRM_Core_Form $form
*/
public static function preProcess(&$form) {
- $messageText = array();
- $messageSubject = array();
+ CRM_Contact_Form_Task_EmailCommon::preProcessFromAddress($form);
+ $messageText = [];
+ $messageSubject = [];
$dao = new CRM_Core_BAO_MessageTemplate();
$dao->is_active = 1;
$dao->find();
@@ -70,7 +71,7 @@ public static function preProcess(&$form) {
$form->assign('message', $messageText);
$form->assign('messageSubject', $messageSubject);
- CRM_Utils_System::setTitle('Print/Merge Document');
+ parent::preProcess($form);
}
/**
@@ -78,193 +79,11 @@ public static function preProcess(&$form) {
* @param int $cid
*/
public static function preProcessSingle(&$form, $cid) {
- $form->_contactIds = array($cid);
+ $form->_contactIds = explode(',', $cid);
// put contact display name in title for single contact mode
- CRM_Utils_System::setTitle(ts('Print/Merge Document for %1', array(1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name'))));
- }
-
- /**
- * Build the form object.
- *
- * @var CRM_Core_Form $form
- */
- public static function buildQuickForm(&$form) {
- // This form outputs a file so should never be submitted via ajax
- $form->preventAjaxSubmit();
-
- //Added for CRM-12682: Add activity subject and campaign fields
- CRM_Campaign_BAO_Campaign::addCampaign($form);
- $form->add(
- 'text',
- 'subject',
- ts('Activity Subject'),
- array('size' => 45, 'maxlength' => 255),
- FALSE
- );
-
- $form->add('static', 'pdf_format_header', NULL, ts('Page Format: %1', array(1 => '')));
- $form->addSelect('format_id', array(
- 'label' => ts('Select Format'),
- 'placeholder' => ts('Default'),
- 'entity' => 'message_template',
- 'field' => 'pdf_format_id',
- 'option_url' => 'civicrm/admin/pdfFormats',
- ));
- $form->add(
- 'select',
- 'paper_size',
- ts('Paper Size'),
- array(0 => ts('- default -')) + CRM_Core_BAO_PaperSize::getList(TRUE),
- FALSE,
- array('onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();")
- );
- $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
- $form->add(
- 'select',
- 'orientation',
- ts('Orientation'),
- CRM_Core_BAO_PdfFormat::getPageOrientations(),
- FALSE,
- array('onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();")
- );
- $form->add(
- 'select',
- 'metric',
- ts('Unit of Measure'),
- CRM_Core_BAO_PdfFormat::getUnits(),
- FALSE,
- array('onChange' => "selectMetric( this.value );")
- );
- $form->add(
- 'text',
- 'margin_left',
- ts('Left Margin'),
- array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
- TRUE
- );
- $form->add(
- 'text',
- 'margin_right',
- ts('Right Margin'),
- array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
- TRUE
- );
- $form->add(
- 'text',
- 'margin_top',
- ts('Top Margin'),
- array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
- TRUE
- );
- $form->add(
- 'text',
- 'margin_bottom',
- ts('Bottom Margin'),
- array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
- TRUE
- );
-
- $config = CRM_Core_Config::singleton();
- /** CRM-15883 Suppressing Stationery path field until we switch from DOMPDF to a library that supports it.
- if ($config->wkhtmltopdfPath == FALSE) {
- $form->add(
- 'text',
- 'stationery',
- ts('Stationery (relative path to PDF you wish to use as the background)'),
- array('size' => 25, 'maxlength' => 900, 'onkeyup' => "showUpdateFormatChkBox();"),
- FALSE
- );
+ if (count($form->_contactIds) === 1) {
+ CRM_Utils_System::setTitle(ts('Print/Merge Document for %1', [1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name')]));
}
- */
- $form->add('checkbox', 'bind_format', ts('Always use this Page Format with the selected Template'));
- $form->add('checkbox', 'update_format', ts('Update Page Format (this will affect all templates that use this format)'));
-
- $form->assign('useThisPageFormat', ts('Always use this Page Format with the new template?'));
- $form->assign('useSelectedPageFormat', ts('Should the new template always use the selected Page Format?'));
- $form->assign('totalSelectedContacts', count($form->_contactIds));
-
- $form->add('select', 'document_type', ts('Document Type'), CRM_Core_SelectValues::documentFormat());
-
- $documentTypes = implode(',', CRM_Core_SelectValues::documentApplicationType());
- $form->addElement('file', "document_file", 'Upload Document', 'size=30 maxlength=255 accept="' . $documentTypes . '"');
- $form->addUploadElement("document_file");
-
- CRM_Mailing_BAO_Mailing::commonCompose($form);
-
- $buttons = array();
- if ($form->get('action') != CRM_Core_Action::VIEW) {
- $buttons[] = array(
- 'type' => 'upload',
- 'name' => ts('Download Document'),
- 'isDefault' => TRUE,
- 'icon' => 'fa-download',
- );
- $buttons[] = array(
- 'type' => 'submit',
- 'name' => ts('Preview'),
- 'subName' => 'preview',
- 'icon' => 'fa-search',
- 'isDefault' => FALSE,
- );
- }
- $buttons[] = array(
- 'type' => 'cancel',
- 'name' => $form->get('action') == CRM_Core_Action::VIEW ? ts('Done') : ts('Cancel'),
- );
- $form->addButtons($buttons);
-
- $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form);
- }
-
- /**
- * Set default values.
- */
- public static function setDefaultValues() {
- $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
- $defaultFormat['format_id'] = $defaultFormat['id'];
- return $defaultFormat;
- }
-
- /**
- * Form rule.
- *
- * @param array $fields
- * The input form values.
- * @param array $files
- * @param array $self
- * Additional values form 'this'.
- *
- * @return bool
- * TRUE if no errors, else array of errors.
- */
- public static function formRule($fields, $files, $self) {
- $errors = array();
- $template = CRM_Core_Smarty::singleton();
-
- // If user uploads non-document file other than odt/docx
- if (empty($fields['template']) &&
- !empty($files['document_file']['tmp_name']) &&
- array_search($files['document_file']['type'], CRM_Core_SelectValues::documentApplicationType()) == NULL
- ) {
- $errors['document_file'] = ts('Invalid document file format');
- }
- //Added for CRM-1393
- if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
- $errors['saveTemplateName'] = ts("Enter name to save message template");
- }
- if (!is_numeric($fields['margin_left'])) {
- $errors['margin_left'] = 'Margin must be numeric';
- }
- if (!is_numeric($fields['margin_right'])) {
- $errors['margin_right'] = 'Margin must be numeric';
- }
- if (!is_numeric($fields['margin_top'])) {
- $errors['margin_top'] = 'Margin must be numeric';
- }
- if (!is_numeric($fields['margin_bottom'])) {
- $errors['margin_bottom'] = 'Margin must be numeric';
- }
- return empty($errors) ? TRUE : $errors;
}
/**
@@ -277,58 +96,7 @@ public static function formRule($fields, $files, $self) {
* [$categories, $html_message, $messageToken, $returnProperties]
*/
public static function processMessageTemplate($formValues) {
- $html_message = CRM_Utils_Array::value('html_message', $formValues);
-
- // process message template
- if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
- $messageTemplate = array(
- 'msg_text' => NULL,
- 'msg_html' => $formValues['html_message'],
- 'msg_subject' => NULL,
- 'is_active' => TRUE,
- );
-
- $messageTemplate['pdf_format_id'] = 'null';
- if (!empty($formValues['bind_format']) && $formValues['format_id']) {
- $messageTemplate['pdf_format_id'] = $formValues['format_id'];
- }
- if (!empty($formValues['saveTemplate']) && $formValues['saveTemplate']) {
- $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
- CRM_Core_BAO_MessageTemplate::add($messageTemplate);
- }
-
- if (!empty($formValues['updateTemplate']) && $formValues['template'] && $formValues['updateTemplate']) {
- $messageTemplate['id'] = $formValues['template'];
-
- unset($messageTemplate['msg_title']);
- CRM_Core_BAO_MessageTemplate::add($messageTemplate);
- }
- }
- elseif (CRM_Utils_Array::value('template', $formValues) > 0) {
- if (!empty($formValues['bind_format']) && $formValues['format_id']) {
- $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}";
- }
- else {
- $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}";
- }
- CRM_Core_DAO::executeQuery($query);
-
- $documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $formValues['template']);
- foreach ((array) $documentInfo as $info) {
- list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($info['fullPath'], $info['mime_type']);
- $formValues['document_file_path'] = $info['fullPath'];
- }
- }
- // extract the content of uploaded document file
- elseif (!empty($formValues['document_file'])) {
- list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($formValues['document_file']['name'], $formValues['document_file']['type']);
- $formValues['document_file_path'] = $formValues['document_file']['name'];
- }
-
- if (!empty($formValues['update_format'])) {
- $bao = new CRM_Core_BAO_PdfFormat();
- $bao->savePdfFormat($formValues, $formValues['format_id']);
- }
+ $html_message = self::processTemplate($formValues);
$categories = self::getTokenCategories();
@@ -338,14 +106,14 @@ public static function processMessageTemplate($formValues) {
$messageToken = CRM_Utils_Token::getTokens($html_message);
- $returnProperties = array();
+ $returnProperties = [];
if (isset($messageToken['contact'])) {
foreach ($messageToken['contact'] as $key => $value) {
$returnProperties[$value] = 1;
}
}
- return array($formValues, $categories, $html_message, $messageToken, $returnProperties);
+ return [$formValues, $categories, $html_message, $messageToken, $returnProperties];
}
/**
@@ -361,16 +129,15 @@ public static function postProcess(&$form) {
$buttonName = $form->controller->getButtonName();
$skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
$skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
- $html = $activityIds = array();
+ $html = $activityIds = [];
- // CRM-16725 Skip creation of activities if user is previewing their PDF letter(s)
- if ($buttonName == '_qf_PDF_upload') {
+ // CRM-21255 - Hrm, CiviCase 4+5 seem to report buttons differently...
+ $c = $form->controller->container();
+ $isLiveMode = ($buttonName == '_qf_PDF_upload') || isset($c['values']['PDF']['buttons']['_qf_PDF_upload']);
- // This seems silly, but the old behavior was to first check `_cid`
- // and then use the provided `$contactIds`. Probably not even necessary,
- // but difficult to audit.
- $contactIds = $form->_cid ? array($form->_cid) : $form->_contactIds;
- $activityIds = self::createActivities($form, $html_message, $contactIds, $formValues['subject'], CRM_Utils_Array::value('campaign_id', $formValues));
+ // CRM-16725 Skip creation of activities if user is previewing their PDF letter(s)
+ if ($isLiveMode) {
+ $activityIds = self::createActivities($form, $html_message, $form->_contactIds, $formValues['subject'], CRM_Utils_Array::value('campaign_id', $formValues));
}
if (!empty($formValues['document_file_path'])) {
@@ -379,7 +146,7 @@ public static function postProcess(&$form) {
foreach ($form->_contactIds as $item => $contactId) {
$caseId = NULL;
- $params = array('contact_id' => $contactId);
+ $params = ['contact_id' => $contactId];
list($contact) = CRM_Utils_Token::getTokenDetails($params,
$returnProperties,
@@ -418,7 +185,7 @@ public static function postProcess(&$form) {
}
$tee = NULL;
- if (Civi::settings()->get('recordGeneratedLetters') === 'combined-attached') {
+ if ($isLiveMode && Civi::settings()->get('recordGeneratedLetters') === 'combined-attached') {
if (count($activityIds) !== 1) {
throw new CRM_Core_Exception("When recordGeneratedLetters=combined-attached, there should only be one activity.");
}
@@ -449,21 +216,21 @@ public static function postProcess(&$form) {
throw new \CRM_Core_Exception("Failed to capture document content (type=$type)!");
}
foreach ($activityIds as $activityId) {
- civicrm_api3('Attachment', 'create', array(
+ civicrm_api3('Attachment', 'create', [
'entity_table' => 'civicrm_activity',
'entity_id' => $activityId,
'name' => $fileName,
'mime_type' => $mimeType,
- 'options' => array(
+ 'options' => [
'move-file' => $tee->getFileName(),
- ),
- ));
+ ],
+ ]);
}
}
$form->postProcessHook();
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
@@ -481,31 +248,38 @@ public static function postProcess(&$form) {
*
* @throws CRM_Core_Exception
*/
- public static function createActivities($form, $html_message, $contactIds, $subject, $campaign_id, $perContactHtml = array()) {
+ public static function createActivities($form, $html_message, $contactIds, $subject, $campaign_id, $perContactHtml = []) {
- $activityParams = array(
+ $activityParams = [
'subject' => $subject,
'campaign_id' => $campaign_id,
'source_contact_id' => CRM_Core_Session::singleton()->getLoggedInContactID(),
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Print PDF Letter'),
'activity_date_time' => date('YmdHis'),
'details' => $html_message,
- );
+ ];
if (!empty($form->_activityId)) {
- $activityParams += array('id' => $form->_activityId);
+ $activityParams += ['id' => $form->_activityId];
}
- $activityIds = array();
+ $activityIds = [];
switch (Civi::settings()->get('recordGeneratedLetters')) {
case 'none':
- return array();
+ return [];
case 'multiple':
// One activity per contact.
- foreach ($contactIds as $contactId) {
- $fullParams = array(
+ foreach ($contactIds as $i => $contactId) {
+ $fullParams = [
'target_contact_id' => $contactId,
- ) + $activityParams;
+ ] + $activityParams;
+ if (!empty($form->_caseId)) {
+ $fullParams['case_id'] = $form->_caseId;
+ }
+ elseif (!empty($form->_caseIds[$i])) {
+ $fullParams['case_id'] = $form->_caseIds[$i];
+ }
+
if (isset($perContactHtml[$contactId])) {
$fullParams['details'] = implode('', $perContactHtml[$contactId]);
}
@@ -518,70 +292,26 @@ public static function createActivities($form, $html_message, $contactIds, $subj
case 'combined':
case 'combined-attached':
// One activity with all contacts.
- $fullParams = array(
+ $fullParams = [
'target_contact_id' => $contactIds,
- ) + $activityParams;
- $activity = CRM_Activity_BAO_Activity::create($fullParams);
- $activityIds[] = $activity->id;
+ ] + $activityParams;
+ if (!empty($form->_caseId)) {
+ $fullParams['case_id'] = $form->_caseId;
+ }
+ elseif (!empty($form->_caseIds)) {
+ $fullParams['case_id'] = $form->_caseIds;
+ }
+ $activity = civicrm_api3('Activity', 'create', $fullParams);
+ $activityIds[] = $activity['id'];
break;
default:
throw new CRM_Core_Exception("Unrecognized option in recordGeneratedLetters: " . Civi::settings()->get('recordGeneratedLetters'));
}
- if (!empty($form->_caseId)) {
- foreach ($activityIds as $activityId) {
- $caseActivityParams = array('activity_id' => $activityId, 'case_id' => $form->_caseId);
- CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
- }
- }
-
return $activityIds;
}
- /**
- * @param $message
- */
- public static function formatMessage(&$message) {
- $newLineOperators = array(
- 'p' => array(
- 'oper' => '
',
- 'pattern' => '/<(\s+)?p(\s+)?>/m',
- ),
- 'br' => array(
- 'oper' => ' ',
- 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
- ),
- );
-
- $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
- foreach ($htmlMsg as $k => & $m) {
- $messages = preg_split($newLineOperators['br']['pattern'], $m);
- foreach ($messages as $key => & $msg) {
- $msg = trim($msg);
- $matches = array();
- if (preg_match('/^( )+/', $msg, $matches)) {
- $spaceLen = strlen($matches[0]) / 6;
- $trimMsg = ltrim($msg, ' ');
- $charLen = strlen($trimMsg);
- $totalLen = $charLen + $spaceLen;
- if ($totalLen > 100) {
- $spacesCount = 10;
- if ($spaceLen > 50) {
- $spacesCount = 20;
- }
- if ($charLen > 100) {
- $spacesCount = 1;
- }
- $msg = str_repeat(' ', $spacesCount) . $trimMsg;
- }
- }
- }
- $m = implode($newLineOperators['br']['oper'], $messages);
- }
- $message = implode($newLineOperators['p']['oper'], $htmlMsg);
- }
-
/**
* Convert from a vague-type/file-extension to mime-type.
*
@@ -590,12 +320,12 @@ public static function formatMessage(&$message) {
* @throws \CRM_Core_Exception
*/
private static function getMimeType($type) {
- $mimeTypes = array(
+ $mimeTypes = [
'pdf' => 'application/pdf',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'odt' => 'application/vnd.oasis.opendocument.text',
'html' => 'text/html',
- );
+ ];
if (isset($mimeTypes[$type])) {
return $mimeTypes[$type];
}
@@ -611,7 +341,7 @@ private static function getMimeType($type) {
*/
protected static function getTokenCategories() {
if (!isset(Civi::$statics[__CLASS__]['token_categories'])) {
- $tokens = array();
+ $tokens = [];
CRM_Utils_Hook::tokens($tokens);
Civi::$statics[__CLASS__]['token_categories'] = array_keys($tokens);
}
diff --git a/CRM/Contact/Form/Task/PickProfile.php b/CRM/Contact/Form/Task/PickProfile.php
index 46a5d67a6c99..a3a061b8dde3 100644
--- a/CRM/Contact/Form/Task/PickProfile.php
+++ b/CRM/Contact/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
_contactIds) > $this->_maxContacts) {
- CRM_Core_Session::setStatus(ts("The maximum number of contacts you can select for Update multiple contacts is %1. You have selected %2. Please select fewer contacts from your search results and try again.", array(
- 1 => $this->_maxContacts,
- 2 => count($this->_contactIds),
- )), ts('Maximum Exceeded'), 'error');
+ CRM_Core_Session::setStatus(ts("The maximum number of contacts you can select for Update multiple contacts is %1. You have selected %2. Please select fewer contacts from your search results and try again.", [
+ 1 => $this->_maxContacts,
+ 2 => count($this->_contactIds),
+ ]), ts('Maximum Exceeded'), 'error');
$validate = TRUE;
}
@@ -106,10 +109,10 @@ public function buildQuickForm() {
if (empty($profiles)) {
$types = implode(' ' . ts('or') . ' ', $this->_contactTypes);
- CRM_Core_Session::setStatus(ts("The contact type selected for Update multiple contacts does not have a corresponding profile. Please set up a profile for %1s and try again.", array(1 => $types)), ts('No Profile Available'), 'error');
+ CRM_Core_Session::setStatus(ts("The contact type selected for Update multiple contacts does not have a corresponding profile. Please set up a profile for %1s and try again.", [1 => $types]), ts('No Profile Available'), 'error');
CRM_Utils_System::redirect($this->_userContext);
}
- $ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'), array('' => ts('- select profile -')) + $profiles, TRUE, array('class' => 'crm-select2 huge'));
+ $ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'), ['' => ts('- select profile -')] + $profiles, TRUE, ['class' => 'crm-select2 huge']);
$this->addDefaultButtons(ts('Continue'));
}
@@ -118,7 +121,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contact_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Contact/Form/Task/Print.php b/CRM/Contact/Form/Task/Print.php
index 4087d2bcb10a..911af3dd8257 100644
--- a/CRM/Contact/Form/Task/Print.php
+++ b/CRM/Contact/Form/Task/Print.php
@@ -1,9 +1,9 @@
_contactIds as $contactId) {
- $params[] = array(
+ $params[] = [
CRM_Core_Form::CB_PREFIX . $contactId,
'=',
1,
0,
0,
- );
+ ];
}
}
@@ -82,8 +82,9 @@ public function preProcess() {
$selectorName = $this->controller->selectorName();
require_once str_replace('_', DIRECTORY_SEPARATOR, $selectorName) . '.php';
- $returnP = isset($returnPropeties) ? $returnPropeties : "";
+ $returnP = isset($returnProperties) ? $returnProperties : "";
$customSearchClass = $this->get('customSearchClass');
+ $this->assign('customSearchID', $this->get('customSearchID'));
$selector = new $selectorName($customSearchClass,
$fv,
$params,
@@ -111,19 +112,18 @@ public function buildQuickForm() {
//
// just need to add a javacript to popup the window for printing
//
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Contact List'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Contact List'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Contact/Form/Task/ProximityCommon.php b/CRM/Contact/Form/Task/ProximityCommon.php
index f1ab27e3d041..6f632cb9de6e 100644
--- a/CRM/Contact/Form/Task/ProximityCommon.php
+++ b/CRM/Contact/Form/Task/ProximityCommon.php
@@ -1,9 +1,9 @@
assign('proximity_search', TRUE);
@@ -74,18 +74,18 @@ static public function buildQuickForm($form, $proxSearch) {
$form->add('text', 'prox_postal_code', ts('Postal Code'), NULL, FALSE);
- $form->addChainSelect('prox_state_province_id', array('required' => $proxRequired));
+ $form->addChainSelect('prox_state_province_id', ['required' => $proxRequired]);
- $country = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
+ $country = ['' => ts('- select -')] + CRM_Core_PseudoConstant::country();
$form->add('select', 'prox_country_id', ts('Country'), $country, $proxRequired);
$form->add('text', 'prox_distance', ts('Distance'), NULL, $proxRequired);
- $proxUnits = array('km' => ts('km'), 'miles' => ts('miles'));
+ $proxUnits = ['km' => ts('km'), 'miles' => ts('miles')];
$form->add('select', 'prox_distance_unit', ts('Units'), $proxUnits, $proxRequired);
// prox_distance_unit
- $form->addFormRule(array('CRM_Contact_Form_Task_ProximityCommon', 'formRule'), $form);
+ $form->addFormRule(['CRM_Contact_Form_Task_ProximityCommon', 'formRule'], $form);
}
/**
@@ -101,13 +101,13 @@ static public function buildQuickForm($form, $proxSearch) {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
// If Distance is present, make sure state, country and city or postal code are populated.
if (!empty($fields['prox_distance'])) {
if (empty($fields['prox_state_province_id']) || empty($fields['prox_country_id'])) {
$errors["prox_state_province_id"] = ts("Country AND State/Province are required to search by distance.");
}
- if (!CRM_Utils_Array::value('prox_postal_code', $fields) AND
+ if (!CRM_Utils_Array::value('prox_postal_code', $fields) and
!CRM_Utils_Array::value('prox_city', $fields)
) {
$errors["prox_distance"] = ts("City OR Postal Code are required to search by distance.");
@@ -125,8 +125,8 @@ public static function formRule($fields, $files, $form) {
* @return array
* the default array reference
*/
- static public function setDefaultValues($form) {
- $defaults = array();
+ public static function setDefaultValues($form) {
+ $defaults = [];
$config = CRM_Core_Config::singleton();
$countryDefault = $config->defaultContactCountry;
diff --git a/CRM/Contact/Form/Task/RemoveFromGroup.php b/CRM/Contact/Form/Task/RemoveFromGroup.php
index 2a7988082b8f..d803f436e7b6 100644
--- a/CRM/Contact/Form/Task/RemoveFromGroup.php
+++ b/CRM/Contact/Form/Task/RemoveFromGroup.php
@@ -1,9 +1,9 @@
ts('- select group -')) + CRM_Core_PseudoConstant::nestedGroup();
- $groupElement = $this->add('select', 'group_id', ts('Select Group'), $group, TRUE, array('class' => 'crm-select2 huge'));
+ $group = ['' => ts('- select group -')] + CRM_Core_PseudoConstant::nestedGroup();
+ $groupElement = $this->add('select', 'group_id', ts('Select Group'), $group, TRUE, ['class' => 'crm-select2 huge']);
CRM_Utils_System::setTitle(ts('Remove Contacts from Group'));
$this->addDefaultButtons(ts('Remove from Group'));
@@ -58,7 +58,7 @@ public function buildQuickForm() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if ($this->get('context') === 'smog') {
$defaults['group_id'] = $this->get('gid');
@@ -75,24 +75,24 @@ public function postProcess() {
list($total, $removed, $notRemoved) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($this->_contactIds, $groupId);
- $status = array(
- ts("%count contact removed from '%2'", array(
+ $status = [
+ ts("%count contact removed from '%2'", [
'count' => $removed,
'plural' => "%count contacts removed from '%2'",
2 => $group[$groupId],
- )),
- );
+ ]),
+ ];
if ($notRemoved) {
- $status[] = ts('1 contact was already not in this group', array(
- 'count' => $notRemoved,
- 'plural' => '%count contacts were already not in this group',
- ));
+ $status[] = ts('1 contact was already not in this group', [
+ 'count' => $notRemoved,
+ 'plural' => '%count contacts were already not in this group',
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts("Removed Contact From Group", array(
- 'plural' => "Removed Contacts From Group",
- 'count' => $removed,
- )), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts("Removed Contact From Group", [
+ 'plural' => "Removed Contacts From Group",
+ 'count' => $removed,
+ ]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Contact/Form/Task/RemoveFromTag.php b/CRM/Contact/Form/Task/RemoveFromTag.php
index f6847cacd41d..3c18e5b3e2e3 100644
--- a/CRM/Contact/Form/Task/RemoveFromTag.php
+++ b/CRM/Contact/Form/Task/RemoveFromTag.php
@@ -1,9 +1,9 @@
addFormRule(array('CRM_Contact_Form_Task_RemoveFromTag', 'formRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_RemoveFromTag', 'formRule']);
}
/**
@@ -77,7 +77,7 @@ public function addRules() {
* @return array
*/
public static function formRule($form, $rule) {
- $errors = array();
+ $errors = [];
if (empty($form['tag']) && empty($form['contact_taglist'])) {
$errors['_qf_default'] = "Please select atleast one tag.";
}
@@ -91,7 +91,7 @@ public function postProcess() {
//get the submitted values in an array
$params = $this->controller->exportValues($this->_name);
- $contactTags = $tagList = array();
+ $contactTags = $tagList = [];
// check if contact tags exists
if (!empty($params['tag'])) {
@@ -120,27 +120,27 @@ public function postProcess() {
// merge contact and taglist tags
$allTags = CRM_Utils_Array::crmArrayMerge($contactTags, $tagList);
- $this->_name = array();
+ $this->_name = [];
foreach ($allTags as $key => $dnc) {
$this->_name[] = $this->_tags[$key];
list($total, $removed, $notRemoved) = CRM_Core_BAO_EntityTag::removeEntitiesFromTag($this->_contactIds, $key,
'civicrm_contact', FALSE);
- $status = array(
- ts('%count contact un-tagged', array(
- 'count' => $removed,
- 'plural' => '%count contacts un-tagged',
- )),
- );
+ $status = [
+ ts('%count contact un-tagged', [
+ 'count' => $removed,
+ 'plural' => '%count contacts un-tagged',
+ ]),
+ ];
if ($notRemoved) {
- $status[] = ts('1 contact already did not have this tag', array(
- 'count' => $notRemoved,
- 'plural' => '%count contacts already did not have this tag',
- ));
+ $status[] = ts('1 contact already did not have this tag', [
+ 'count' => $notRemoved,
+ 'plural' => '%count contacts already did not have this tag',
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts("Removed Tag %1", array(1 => $this->_tags[$key])), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts("Removed Tag %1", [1 => $this->_tags[$key]]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Contact/Form/Task/Result.php b/CRM/Contact/Form/Task/Result.php
index 1f6f8e678a94..22c8bea27382 100644
--- a/CRM/Contact/Form/Task/Result.php
+++ b/CRM/Contact/Form/Task/Result.php
@@ -1,9 +1,9 @@
set('searchRows', '');
$context = $this->get('context');
- if (in_array($context, array(
+ if (in_array($context, [
'smog',
'amtg',
- ))) {
+ ])) {
$urlParams = 'reset=1&force=1&context=smog&gid=';
$urlParams .= ($context == 'smog') ? $this->get('gid') : $this->get('amtgID');
$session->replaceUserContext(CRM_Utils_System::url('civicrm/group/search', $urlParams));
@@ -94,14 +94,13 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Contact/Form/Task/SMS.php b/CRM/Contact/Form/Task/SMS.php
index 0515118b0aed..113c763cd218 100644
--- a/CRM/Contact/Form/Task/SMS.php
+++ b/CRM/Contact/Form/Task/SMS.php
@@ -1,9 +1,9 @@
_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
diff --git a/CRM/Contact/Form/Task/SMSCommon.php b/CRM/Contact/Form/Task/SMSCommon.php
index 9c36efbfb646..eba06f8006ed 100644
--- a/CRM/Contact/Form/Task/SMSCommon.php
+++ b/CRM/Contact/Form/Task/SMSCommon.php
@@ -1,9 +1,9 @@
_activityHolderIds)) {
CRM_Core_Error::statusBounce(ts("The Reply SMS Could only be sent for activities with '%1' subject.",
- array(1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT)
+ [1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT]
));
}
}
@@ -88,11 +87,11 @@ public static function preProcessProvider(&$form) {
*/
public static function buildQuickForm(&$form) {
- $toArray = array();
+ $toArray = [];
$providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc');
- $providerSelect = array();
+ $providerSelect = [];
foreach ($providers as $provider) {
$providerSelect[$provider['id']] = $provider['title'];
}
@@ -101,11 +100,11 @@ public static function buildQuickForm(&$form) {
$cid = $form->get('cid');
if ($cid) {
- $form->_contactIds = array($cid);
+ $form->_contactIds = [$cid];
}
- $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE);
- $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE);
+ $to = $form->add('text', 'to', ts('To'), ['class' => 'huge'], TRUE);
+ $form->add('text', 'activity_subject', ts('Name The SMS'), ['class' => 'huge'], TRUE);
$toSetDefault = TRUE;
if (property_exists($form, '_context') && $form->_context == 'standalone') {
@@ -113,11 +112,11 @@ public static function buildQuickForm(&$form) {
}
// when form is submitted recompute contactIds
- $allToSMS = array();
+ $allToSMS = [];
if ($to->getValue()) {
$allToPhone = explode(',', $to->getValue());
- $form->_contactIds = array();
+ $form->_contactIds = [];
foreach ($allToPhone as $value) {
list($contactId, $phone) = explode('::', $value);
if ($contactId) {
@@ -156,30 +155,30 @@ public static function buildQuickForm(&$form) {
if (!$validActivities) {
$errorMess = "";
if ($extendTargetContacts) {
- $errorMess = ts('One selected activity consists of more than one target contact.', array(
+ $errorMess = ts('One selected activity consists of more than one target contact.', [
'count' => $extendTargetContacts,
'plural' => '%count selected activities consist of more than one target contact.',
- ));
+ ]);
}
if ($invalidActivity) {
$errorMess = ($errorMess ? ' ' : '');
- $errorMess .= ts('The selected activity is invalid.', array(
+ $errorMess .= ts('The selected activity is invalid.', [
'count' => $invalidActivity,
'plural' => '%count selected activities are invalid.',
- ));
+ ]);
}
- CRM_Core_Error::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess)));
+ CRM_Core_Error::statusBounce(ts("%1: SMS Reply will not be sent.", [1 => $errorMess]));
}
}
if (is_array($form->_contactIds) && !empty($form->_contactIds) && $toSetDefault) {
- $returnProperties = array(
+ $returnProperties = [
'sort_name' => 1,
'phone' => 1,
'do_not_sms' => 1,
'is_deceased' => 1,
'display_name' => 1,
- );
+ ];
list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_contactIds,
$returnProperties,
@@ -215,7 +214,7 @@ public static function buildQuickForm(&$form) {
if (!empty($value['phone'])
&& $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) && empty($value['is_deceased'])
) {
- $filter = array('do_not_sms' => 0);
+ $filter = ['do_not_sms' => 0];
$contactPhones = CRM_Core_BAO_Phone::allPhones($contactId, FALSE, 'Mobile', $filter);
if (count($contactPhones) > 0) {
$mobilePhone = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'phone');
@@ -247,10 +246,10 @@ public static function buildQuickForm(&$form) {
}
if ($phone) {
- $toArray[] = array(
+ $toArray[] = [
'text' => '"' . $value['sort_name'] . '" (' . $phone . ')',
'id' => "$contactId::{$phone}",
- );
+ ];
}
}
@@ -294,7 +293,7 @@ public static function buildQuickForm(&$form) {
$form->addDefaultButtons(ts('Send SMS'), 'upload');
}
- $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form);
+ $form->addFormRule(['CRM_Contact_Form_Task_SMSCommon', 'formRule'], $form);
}
/**
@@ -310,7 +309,7 @@ public static function buildQuickForm(&$form) {
* true if no errors, else array of errors
*/
public static function formRule($fields, $dontCare, $self) {
- $errors = array();
+ $errors = [];
$template = CRM_Core_Smarty::singleton();
@@ -322,7 +321,7 @@ public static function formRule($fields, $dontCare, $self) {
$messageCheck = CRM_Utils_Array::value('sms_text_message', $fields);
$messageCheck = str_replace("\r\n", "\n", $messageCheck);
if ($messageCheck && (strlen($messageCheck) > CRM_SMS_Provider::MAX_SMS_CHAR)) {
- $errors['sms_text_message'] = ts("You can configure the SMS message body up to %1 characters", array(1 => CRM_SMS_Provider::MAX_SMS_CHAR));
+ $errors['sms_text_message'] = ts("You can configure the SMS message body up to %1 characters", [1 => CRM_SMS_Provider::MAX_SMS_CHAR]);
}
}
}
@@ -349,11 +348,11 @@ public static function postProcess(&$form) {
// process message template
if (!empty($thisValues['SMSsaveTemplate']) || !empty($thisValues['SMSupdateTemplate'])) {
- $messageTemplate = array(
+ $messageTemplate = [
'msg_text' => $thisValues['sms_text_message'],
'is_active' => TRUE,
'is_sms' => TRUE,
- );
+ ];
if (!empty($thisValues['SMSsaveTemplate'])) {
$messageTemplate['msg_title'] = $thisValues['SMSsaveTemplateName'];
@@ -368,8 +367,8 @@ public static function postProcess(&$form) {
}
// format contact details array to handle multiple sms from same contact
- $formattedContactDetails = array();
- $tempPhones = array();
+ $formattedContactDetails = [];
+ $tempPhones = [];
foreach ($form->_contactIds as $key => $contactId) {
$phone = $form->_toContactPhone[$key];
@@ -400,10 +399,10 @@ public static function postProcess(&$form) {
);
if ($countSuccess > 0) {
- CRM_Core_Session::setStatus(ts('One message was sent successfully.', array(
- 'plural' => '%count messages were sent successfully.',
- 'count' => $countSuccess,
- )), ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $countSuccess)), 'success');
+ CRM_Core_Session::setStatus(ts('One message was sent successfully.', [
+ 'plural' => '%count messages were sent successfully.',
+ 'count' => $countSuccess,
+ ]), ts('Message Sent', ['plural' => 'Messages Sent', 'count' => $countSuccess]), 'success');
}
if (is_array($sent)) {
@@ -414,17 +413,17 @@ public static function postProcess(&$form) {
$status .= '
' . $errMsg . '
';
}
$status .= '';
- CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array(
- 'count' => count($sent),
- 'plural' => '%count Messages Not Sent',
- )), 'info');
+ CRM_Core_Session::setStatus($status, ts('One Message Not Sent', [
+ 'count' => count($sent),
+ 'plural' => '%count Messages Not Sent',
+ ]), 'info');
}
else {
//Display the name and number of contacts for those sms is not sent.
$smsNotSent = array_diff_assoc($allContactIds, $contactIds);
if (!empty($smsNotSent)) {
- $not_sent = array();
+ $not_sent = [];
foreach ($smsNotSent as $index => $contactId) {
$displayName = $form->_allContactDetails[$contactId]['display_name'];
$phone = $form->_allContactDetails[$contactId]['phone'];
@@ -433,13 +432,13 @@ public static function postProcess(&$form) {
}
$status = '(' . ts('because no phone number on file or communication preferences specify DO NOT SMS or Contact is deceased');
if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') {
- $status .= ' ' . ts("or the contact is not part of the activity '%1'", array(1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT));
+ $status .= ' ' . ts("or the contact is not part of the activity '%1'", [1 => self::RECIEVED_SMS_ACTIVITY_SUBJECT]);
}
$status .= ')
' . implode('
', $not_sent) . '
';
- CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array(
- 'count' => count($smsNotSent),
- 'plural' => '%count Messages Not Sent',
- )), 'info');
+ CRM_Core_Session::setStatus($status, ts('One Message Not Sent', [
+ 'count' => count($smsNotSent),
+ 'plural' => '%count Messages Not Sent',
+ ]), 'info');
}
}
}
diff --git a/CRM/Contact/Form/Task/SaveSearch.php b/CRM/Contact/Form/Task/SaveSearch.php
index bff3f0d1291d..1b888a6b53f8 100644
--- a/CRM/Contact/Form/Task/SaveSearch.php
+++ b/CRM/Contact/Form/Task/SaveSearch.php
@@ -1,9 +1,9 @@
controller->exportValues('Basic');
}
+ // Get Task name
+ $modeValue = CRM_Contact_Form_Search::getModeValue(CRM_Utils_Array::value('component_mode', $values, CRM_Contact_BAO_Query::MODE_CONTACTS));
+ $className = $modeValue['taskClassName'];
+ $taskList = $className::taskTitles();
$this->_task = CRM_Utils_Array::value('task', $values);
- $crmContactTaskTasks = CRM_Contact_Task::taskTitles();
- $this->assign('taskName', CRM_Utils_Array::value($this->_task, $crmContactTaskTasks));
+ $this->assign('taskName', CRM_Utils_Array::value($this->_task, $taskList));
}
/**
@@ -135,7 +138,7 @@ public function buildQuickForm() {
$this->assign('partiallySelected', $formValues['radio_ts'] != 'ts_all');
}
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_Group', $groupID, 'title')
+ 'objectExists', ['CRM_Contact_DAO_Group', $groupID, 'title']
);
}
@@ -157,12 +160,9 @@ public function postProcess() {
if (!$this->_id) {
//save record in mapping table
- $mappingParams = array(
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Search Builder',
- 'name'
- ),
- );
+ $mappingParams = [
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
+ ];
$mapping = CRM_Core_BAO_Mapping::add($mappingParams);
$mappingId = $mapping->id;
}
@@ -205,18 +205,15 @@ public function postProcess() {
$savedSearch->search_custom_id = $this->get('customSearchID');
$savedSearch->save();
$this->set('ssID', $savedSearch->id);
- CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", array(1 => $formValues['title'])), ts('Group Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", [1 => $formValues['title']]), ts('Group Saved'), 'success');
// also create a group that is associated with this saved search only if new saved search
- $params = array();
+ $params = [];
$params['title'] = $formValues['title'];
$params['description'] = $formValues['description'];
- if (isset($formValues['group_type']) &&
- is_array($formValues['group_type'])
- ) {
+ if (isset($formValues['group_type']) && is_array($formValues['group_type']) && count($formValues['group_type'])) {
$params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
- array_keys($formValues['group_type'])
- ) . CRM_Core_DAO::VALUE_SEPARATOR;
+ array_keys($formValues['group_type'])) . CRM_Core_DAO::VALUE_SEPARATOR;
}
else {
$params['group_type'] = '';
@@ -236,15 +233,12 @@ public function postProcess() {
// Update mapping with the name and description of the group.
if ($mappingId && $group) {
- $mappingParams = array(
+ $mappingParams = [
'id' => $mappingId,
'name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $group->id, 'name', 'id'),
'description' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $group->id, 'description', 'id'),
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Search Builder',
- 'name'
- ),
- );
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
+ ];
CRM_Core_BAO_Mapping::add($mappingParams);
}
@@ -263,7 +257,7 @@ public function postProcess() {
* return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (empty($defaults['parents'])) {
$defaults['parents'] = CRM_Core_BAO_Domain::getGroupId();
}
diff --git a/CRM/Contact/Form/Task/SaveSearch/Update.php b/CRM/Contact/Form/Task/SaveSearch/Update.php
index a4c42883a8c7..4d6e7446a719 100644
--- a/CRM/Contact/Form/Task/SaveSearch/Update.php
+++ b/CRM/Contact/Form/Task/SaveSearch/Update.php
@@ -1,9 +1,9 @@
$this->_id);
+ $params = ['saved_search_id' => $this->_id];
CRM_Contact_BAO_Group::retrieve($params, $defaults);
return $defaults;
diff --git a/CRM/Contact/Form/Task/Unhold.php b/CRM/Contact/Form/Task/Unhold.php
index 3da999ed314b..add289176475 100644
--- a/CRM/Contact/Form/Task/Unhold.php
+++ b/CRM/Contact/Form/Task/Unhold.php
@@ -27,15 +27,15 @@ public function postProcess() {
$rowCount = $result->affectedRows();
if ($rowCount) {
- CRM_Core_Session::setStatus(ts('%count email was found on hold and updated.', array(
- 'count' => $rowCount,
- 'plural' => '%count emails were found on hold and updated.',
- )), ts('Emails Restored'), 'success');
+ CRM_Core_Session::setStatus(ts('%count email was found on hold and updated.', [
+ 'count' => $rowCount,
+ 'plural' => '%count emails were found on hold and updated.',
+ ]), ts('Emails Restored'), 'success');
}
else {
- CRM_Core_Session::setStatus(ts('The selected contact does not have an email on hold.', array(
- 'plural' => 'None of the selected contacts have an email on hold.',
- )), ts('No Emails to Restore'), 'info');
+ CRM_Core_Session::setStatus(ts('The selected contact does not have an email on hold.', [
+ 'plural' => 'None of the selected contacts have an email on hold.',
+ ]), ts('No Emails to Restore'), 'info');
}
}
else {
diff --git a/CRM/Contact/Form/Task/Useradd.php b/CRM/Contact/Form/Task/Useradd.php
index abcf56f6d89c..303fee2ad5b6 100644
--- a/CRM/Contact/Form/Task/Useradd.php
+++ b/CRM/Contact/Form/Task/Useradd.php
@@ -1,9 +1,9 @@
_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$params['id'] = $params['contact_id'] = $this->_contactId;
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults, $ids);
$this->_displayName = $contact->display_name;
$this->_email = $contact->email;
- CRM_Utils_System::setTitle(ts('Create User Record for %1', array(1 => $this->_displayName)));
+ CRM_Utils_System::setTitle(ts('Create User Record for %1', [1 => $this->_displayName]));
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults['contactID'] = $this->_contactId;
$defaults['name'] = $this->_displayName;
if (!empty($this->_email)) {
@@ -80,32 +80,32 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
- $element = $this->add('text', 'name', ts('Full Name'), array('class' => 'huge'));
+ $element = $this->add('text', 'name', ts('Full Name'), ['class' => 'huge']);
$element->freeze();
- $this->add('text', 'cms_name', ts('Username'), array('class' => 'huge'));
+ $this->add('text', 'cms_name', ts('Username'), ['class' => 'huge']);
$this->addRule('cms_name', 'Username is required', 'required');
- $this->add('password', 'cms_pass', ts('Password'), array('class' => 'huge'));
- $this->add('password', 'cms_confirm_pass', ts('Confirm Password'), array('class' => 'huge'));
+ $this->add('password', 'cms_pass', ts('Password'), ['class' => 'huge']);
+ $this->add('password', 'cms_confirm_pass', ts('Confirm Password'), ['class' => 'huge']);
$this->addRule('cms_pass', 'Password is required', 'required');
- $this->addRule(array('cms_pass', 'cms_confirm_pass'), 'ERROR: Password mismatch', 'compare');
- $this->add('text', 'email', ts('Email:'), array('class' => 'huge'))->freeze();
+ $this->addRule(['cms_pass', 'cms_confirm_pass'], 'ERROR: Password mismatch', 'compare');
+ $this->add('text', 'email', ts('Email:'), ['class' => 'huge'])->freeze();
$this->add('hidden', 'contactID');
//add a rule to check username uniqueness
- $this->addFormRule(array('CRM_Contact_Form_Task_Useradd', 'usernameRule'));
+ $this->addFormRule(['CRM_Contact_Form_Task_Useradd', 'usernameRule']);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'next',
'name' => ts('Add'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
$this->setDefaults($this->setDefaultValues());
}
@@ -130,11 +130,11 @@ public function postProcess() {
*/
public static function usernameRule($params) {
$config = CRM_Core_Config::singleton();
- $errors = array();
- $check_params = array(
+ $errors = [];
+ $check_params = [
'name' => $params['cms_name'],
'mail' => $params['email'],
- );
+ ];
$config->userSystem->checkUserNameEmailExists($check_params, $errors);
return empty($errors) ? TRUE : $errors;
diff --git a/CRM/Contact/Import/Controller.php b/CRM/Contact/Import/Controller.php
index 63fdb0834679..b483639ce785 100644
--- a/CRM/Contact/Import/Controller.php
+++ b/CRM/Contact/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Contact/Import/Field.php b/CRM/Contact/Import/Field.php
index 7e1a4b9423a6..a1abc023439e 100644
--- a/CRM/Contact/Import/Field.php
+++ b/CRM/Contact/Import/Field.php
@@ -1,9 +1,9 @@
uploadDir);
- $errorFiles = array('sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch');
+ $errorFiles = ['sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch'];
// check for post max size avoid when called twice
$snippet = CRM_Utils_Array::value('snippet', $_GET, 0);
@@ -81,10 +81,10 @@ public function preProcess() {
}
closedir($handler);
if (!empty($results)) {
- CRM_Core_Error::fatal(ts('%1 file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', array(
- 1 => implode(', ', $results),
- 2 => $config->uploadDir,
- )));
+ CRM_Core_Error::fatal(ts('%1 file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', [
+ 1 => implode(', ', $results),
+ 2 => $config->uploadDir,
+ ]));
}
$this->_dataSourceIsValid = FALSE;
@@ -146,11 +146,11 @@ public function buildQuickForm() {
$this->assign('urlPathVar', 'snippet=4');
$this->add('select', 'dataSource', ts('Data Source'), $dataSources, TRUE,
- array('onchange' => 'buildDataSourceFormBlock(this.value);')
+ ['onchange' => 'buildDataSourceFormBlock(this.value);']
);
// duplicate handling options
- $duplicateOptions = array();
+ $duplicateOptions = [];
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -171,11 +171,11 @@ public function buildQuickForm() {
$mappingArray = CRM_Core_BAO_Mapping::getMappings('Import Contact');
$this->assign('savedMapping', $mappingArray);
- $this->addElement('select', 'savedMapping', ts('Mapping Option'), array('' => ts('- select -')) + $mappingArray);
+ $this->addElement('select', 'savedMapping', ts('Mapping Option'), ['' => ts('- select -')] + $mappingArray);
- $js = array('onClick' => "buildSubTypes();buildDedupeRules();");
+ $js = ['onClick' => "buildSubTypes();buildDedupeRules();"];
// contact types option
- $contactOptions = array();
+ $contactOptions = [];
if (CRM_Contact_BAO_ContactType::isActive('Individual')) {
$contactOptions[] = $this->createElement('radio',
NULL, NULL, ts('Individual'), CRM_Import_Parser::CONTACT_INDIVIDUAL, $js
@@ -203,31 +203,30 @@ public function buildQuickForm() {
$config = CRM_Core_Config::singleton();
$geoCode = FALSE;
- if (!empty($config->geocodeMethod)) {
+ if (CRM_Utils_GeocodeProvider::getUsableClassName()) {
$geoCode = TRUE;
$this->addElement('checkbox', 'doGeocodeAddress', ts('Geocode addresses during import?'));
}
$this->assign('geoCode', $geoCode);
- $this->addElement('text', 'fieldSeparator', ts('Import Field Separator'), array('size' => 2));
+ $this->addElement('text', 'fieldSeparator', ts('Import Field Separator'), ['size' => 2]);
if (Civi::settings()->get('address_standardization_provider') == 'USPS') {
$this->addElement('checkbox', 'disableUSPS', ts('Disable USPS address validation during import?'));
}
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -240,12 +239,12 @@ public function buildQuickForm() {
*/
public function setDefaultValues() {
$config = CRM_Core_Config::singleton();
- $defaults = array(
+ $defaults = [
'dataSource' => 'CRM_Import_DataSource_CSV',
'onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP,
'contactType' => CRM_Import_Parser::CONTACT_INDIVIDUAL,
'fieldSeparator' => $config->fieldSeparator,
- );
+ ];
if ($loadeMapping = $this->get('loadedMapping')) {
$this->assign('loadedMapping', $loadeMapping);
@@ -268,7 +267,7 @@ private function _getDataSources() {
// Open the data source dir and scan it for class files
global $civicrm_root;
$dataSourceDir = $civicrm_root . DIRECTORY_SEPARATOR . 'CRM' . DIRECTORY_SEPARATOR . 'Import' . DIRECTORY_SEPARATOR . 'DataSource' . DIRECTORY_SEPARATOR;
- $dataSources = array();
+ $dataSources = [];
if (!is_dir($dataSourceDir)) {
CRM_Core_Error::fatal("Import DataSource directory $dataSourceDir does not exist");
}
@@ -278,7 +277,7 @@ private function _getDataSources() {
while (($dataSourceFile = readdir($dataSourceHandle)) !== FALSE) {
$fileType = filetype($dataSourceDir . $dataSourceFile);
- $matches = array();
+ $matches = [];
if (($fileType == 'file' || $fileType == 'link') &&
preg_match('/^(.+)\.php$/', $dataSourceFile, $matches)
) {
@@ -307,14 +306,14 @@ public function postProcess() {
// Setup the params array
$this->_params = $this->controller->exportValues($this->_name);
- $storeParams = array(
+ $storeParams = [
'onDuplicate' => 'onDuplicate',
'dedupe' => 'dedupe',
'contactType' => 'contactType',
'contactSubType' => 'subType',
'dateFormats' => 'dateFormats',
'savedMapping' => 'savedMapping',
- );
+ ];
foreach ($storeParams as $storeName => $storeValueName) {
$$storeName = $this->exportValue($storeValueName);
@@ -343,7 +342,7 @@ public function postProcess() {
// We should have the data in the DB now, parse it
$importTableName = $this->get('importTableName');
$fieldNames = $this->_prepareImportTable($db, $importTableName);
- $mapper = array();
+ $mapper = [];
$parser = new CRM_Contact_Import_Parser_Contact($mapper);
$parser->setMaxLinesToProcess(100);
@@ -404,7 +403,7 @@ private function _prepareImportTable($db, $importTableName) {
AUTO_INCREMENT";
$db->query($alterQuery);
- return array('status' => $statusFieldName, 'pk' => $primaryKeyName);
+ return ['status' => $statusFieldName, 'pk' => $primaryKeyName];
}
/**
diff --git a/CRM/Contact/Import/Form/MapField.php b/CRM/Contact/Import/Form/MapField.php
index 38f13b8a8919..fa24b121655c 100644
--- a/CRM/Contact/Import/Form/MapField.php
+++ b/CRM/Contact/Import/Form/MapField.php
@@ -1,9 +1,9 @@
_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
//Mark Dedupe Rule Fields as required, since it's used in matching contact
foreach (array(
- 'Individual',
- 'Household',
- 'Organization',
- ) as $cType) {
+ 'Individual',
+ 'Household',
+ 'Organization',
+ ) as $cType) {
$ruleParams = array(
'contact_type' => $cType,
'used' => 'Unsupervised',
@@ -608,7 +608,7 @@ public function buildQuickForm() {
'type' => 'cancel',
'name' => ts('Cancel'),
),
- )
+ )
);
}
diff --git a/CRM/Contact/Import/Form/Preview.php b/CRM/Contact/Import/Form/Preview.php
index ca8aff581822..e47a5a10474a 100644
--- a/CRM/Contact/Import/Form/Preview.php
+++ b/CRM/Contact/Import/Form/Preview.php
@@ -1,9 +1,9 @@
assign($property, $this->get($property));
}
- $statusID = $this->get('statusID');
- if (!$statusID) {
- $statusID = md5(uniqid(rand(), TRUE));
- $this->set('statusID', $statusID);
- }
- $statusUrl = CRM_Utils_System::url('civicrm/ajax/status', "id={$statusID}", FALSE, NULL, FALSE);
- $this->assign('statusUrl', $statusUrl);
+ $this->setStatusUrl();
$showColNames = TRUE;
if ('CRM_Import_DataSource_CSV' == $this->get('dataSource') &&
@@ -157,9 +151,9 @@ public function buildQuickForm() {
if (!empty($groups)) {
$this->addElement('select', 'groups', ts('Add imported records to existing group(s)'), $groups, array(
- 'multiple' => "multiple",
- 'class' => 'crm-select2',
- ));
+ 'multiple' => "multiple",
+ 'class' => 'crm-select2',
+ ));
}
//display new tag
@@ -193,7 +187,6 @@ public function buildQuickForm() {
'name' => ts('Import Now'),
'spacing' => ' ',
'isDefault' => TRUE,
- 'js' => array('onclick' => "return verify( );"),
),
array(
'type' => 'cancel',
diff --git a/CRM/Contact/Import/Form/Summary.php b/CRM/Contact/Import/Form/Summary.php
index 031f94c2dc2c..811b3f62e22f 100644
--- a/CRM/Contact/Import/Form/Summary.php
+++ b/CRM/Contact/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -110,7 +110,7 @@ public function preProcess() {
'tagAdditions',
'unMatchCount',
'unparsedAddressCount',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Contact/Import/ImportJob.php b/CRM/Contact/Import/ImportJob.php
index 781b1ad380a0..fff23875c7a7 100644
--- a/CRM/Contact/Import/ImportJob.php
+++ b/CRM/Contact/Import/ImportJob.php
@@ -1,9 +1,9 @@
_newTagName || count($this->_tag)) {
+ if ($this->_newTagName || !empty($this->_tag)) {
$tagAdditions = $this->_tagImportedContactsWithNewTag($contactIds,
$this->_newTagName,
$this->_newTagDesc
@@ -416,7 +416,7 @@ public static function getIncompleteImportTables() {
$result = CRM_Core_DAO::executeQuery($query, array($database));
$incompleteImportTables = array();
while ($importTable = $result->fetch()) {
- if (!$this->isComplete($importTable)) {
+ if (!self::isComplete($importTable)) {
$incompleteImportTables[] = $importTable;
}
}
diff --git a/CRM/Contact/Import/Importer.php b/CRM/Contact/Import/Importer.php
index 6252e8ceecd2..779d994b6ebe 100644
--- a/CRM/Contact/Import/Importer.php
+++ b/CRM/Contact/Import/Importer.php
@@ -1,9 +1,9 @@
" . ts('No processing status reported yet.') . "
');
$this->addElement('checkbox', 'is_pledge_start_date_visible', ts('Show Recurring Donation Start Date?'), NULL);
$this->addElement('checkbox', 'is_pledge_start_date_editable', ts('Allow Edits to Recurring Donation Start date?'), NULL);
}
@@ -196,7 +196,7 @@ public function buildQuickForm() {
//add currency element.
$this->addCurrency('currency', ts('Currency'));
- $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Amount', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contribute_Form_ContributionPage_Amount', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -221,14 +221,14 @@ public function setDefaultValues() {
if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
$this->assign('isQuick', $isQuick);
//$priceField = CRM_Core_DAO::getFieldValue( 'CRM_Price_DAO_PriceField', $priceSetId, 'id', 'price_set_id' );
- $options = $pFIDs = array();
- $priceFieldParams = array('price_set_id' => $priceSetId);
- $priceFields = CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = array(
- 'html_type',
- 'name',
- 'is_active',
- 'label',
- ));
+ $options = $pFIDs = [];
+ $priceFieldParams = ['price_set_id' => $priceSetId];
+ $priceFields = CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = [
+ 'html_type',
+ 'name',
+ 'is_active',
+ 'label',
+ ]);
foreach ($priceFields as $priceField) {
if ($priceField['id'] && $priceField['html_type'] == 'Radio' && $priceField['name'] == 'contribution_amount') {
$defaults['price_field_id'] = $priceField['id'];
@@ -304,7 +304,7 @@ public function setDefaultValues() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
//as for separate membership payment we has to have
//contribution amount section enabled, hence to disable it need to
//check if separate membership payment enabled,
@@ -372,6 +372,11 @@ public static function formRule($fields, $files, $self) {
$errors['pay_later_receipt'] = ts('Please enter the instructions to be sent to the contributor when they choose to \'pay later\'.');
}
}
+ else {
+ if ($fields['amount_block_is_active'] && empty($fields['payment_processor'])) {
+ $errors['payment_processor'] = ts('You have listed fixed contribution options or selected a price set, but no payment option has been selected. Please select at least one payment processor and/or enable the pay later option.');
+ }
+ }
// don't allow price set w/ membership signup, CRM-5095
if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
@@ -423,17 +428,6 @@ public static function formRule($fields, $files, $self) {
$errors['payment_processor'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
}
- if (!empty($fields['is_recur_interval'])) {
- foreach (array_keys($fields['payment_processor']) as $paymentProcessorID) {
- $paymentProcessorTypeId = CRM_Core_DAO::getFieldValue(
- 'CRM_Financial_DAO_PaymentProcessor',
- $paymentProcessorID,
- 'payment_processor_type_id'
- );
- $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, $paymentProcessorTypeId, 'name');
- }
- }
-
return $errors;
}
@@ -463,7 +457,7 @@ public function postProcess() {
$priceSetID = CRM_Utils_Array::value('price_set_id', $params);
// get required fields.
- $fields = array(
+ $fields = [
'id' => $this->_id,
'is_recur' => FALSE,
'min_amount' => "null",
@@ -477,14 +471,14 @@ public function postProcess() {
'default_amount_id' => "null",
'is_allow_other_amount' => FALSE,
'amount_block_is_active' => FALSE,
- );
- $resetFields = array();
+ ];
+ $resetFields = [];
if ($priceSetID) {
- $resetFields = array('min_amount', 'max_amount', 'is_allow_other_amount');
+ $resetFields = ['min_amount', 'max_amount', 'is_allow_other_amount'];
}
if (empty($params['is_recur'])) {
- $resetFields = array_merge($resetFields, array('is_recur_interval', 'recur_frequency_unit'));
+ $resetFields = array_merge($resetFields, ['is_recur_interval', 'recur_frequency_unit']);
}
foreach ($fields as $field => $defaultVal) {
@@ -493,10 +487,10 @@ public function postProcess() {
$val = $defaultVal;
}
- if (in_array($field, array(
+ if (in_array($field, [
'min_amount',
'max_amount',
- ))) {
+ ])) {
$val = CRM_Utils_Rule::cleanMoney($val);
}
@@ -513,17 +507,17 @@ public function postProcess() {
if (CRM_Utils_Array::value('adjust_recur_start_date', $params)) {
$fieldValue = '';
- $pledgeDateFields = array(
+ $pledgeDateFields = [
'calendar_date' => 'pledge_calendar_date',
'calendar_month' => 'pledge_calendar_month',
- );
+ ];
if ($params['pledge_default_toggle'] == 'contribution_date') {
- $fieldValue = json_encode(array('contribution_date' => date('m/d/Y')));
+ $fieldValue = json_encode(['contribution_date' => date('Y-m-d')]);
}
else {
foreach ($pledgeDateFields as $key => $pledgeDateField) {
if (CRM_Utils_Array::value($pledgeDateField, $params) && $params['pledge_default_toggle'] == $key) {
- $fieldValue = json_encode(array($key => $params[$pledgeDateField]));
+ $fieldValue = json_encode([$key => $params[$pledgeDateField]]);
break;
}
}
@@ -590,18 +584,19 @@ public function postProcess() {
$values = CRM_Utils_Array::value('value', $params);
$default = CRM_Utils_Array::value('default', $params);
- $options = array();
+ $options = [];
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (isset($values[$i]) &&
(strlen(trim($values[$i])) > 0)
) {
- $options[] = array(
+ $values[$i] = $params['value'][$i] = CRM_Utils_Rule::cleanMoney(trim($values[$i]));
+ $options[] = [
'label' => trim($labels[$i]),
- 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])),
+ 'value' => $values[$i],
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
- );
+ ];
}
}
/* || !empty($params['price_field_value']) || CRM_Utils_Array::value( 'price_field_other', $params )*/
@@ -655,11 +650,11 @@ public function postProcess() {
}
CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $this->_id, $priceSetId);
if (!empty($options)) {
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_set_id' => $priceSetId,
'name' => 'contribution_amount',
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
$noContriAmount = 1;
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (empty($editedResults['id'])) {
@@ -691,16 +686,16 @@ public function postProcess() {
$priceField = CRM_Price_BAO_PriceField::create($fieldParams);
}
if (!empty($params['is_allow_other_amount']) && empty($params['price_field_other'])) {
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_set_id' => $priceSetId,
'name' => 'other_amount',
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (!$priceFieldID = CRM_Utils_Array::value('id', $editedResults)) {
- $fieldParams = array(
+ $fieldParams = [
'name' => 'other_amount',
'label' => ts('Other Amount'),
'price_set_id' => $priceSetId,
@@ -708,7 +703,7 @@ public function postProcess() {
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $this->_values),
'is_display_amounts' => 0,
'weight' => 3,
- );
+ ];
$fieldParams['option_weight'][1] = 1;
$fieldParams['option_amount'][1] = 1;
if (!$noContriAmount) {
@@ -728,11 +723,11 @@ public function postProcess() {
if (!$noContriAmount) {
$priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldID, 'id', 'price_field_id');
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', $params['amount_label']);
- $fieldParams = array(
+ $fieldParams = [
'is_required' => 1,
'label' => $params['amount_label'],
'id' => $priceFieldID,
- );
+ ];
}
$fieldParams['is_active'] = 1;
$priceField = CRM_Price_BAO_PriceField::add($fieldParams);
@@ -745,11 +740,11 @@ public function postProcess() {
elseif ($priceFieldID = CRM_Utils_Array::value('price_field_other', $params)) {
$priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldID, 'id', 'price_field_id');
if (!$noContriAmount) {
- $fieldParams = array(
+ $fieldParams = [
'is_required' => 1,
'label' => $params['amount_label'],
'id' => $priceFieldID,
- );
+ ];
CRM_Price_BAO_PriceField::add($fieldParams);
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', $params['amount_label']);
}
@@ -762,14 +757,14 @@ public function postProcess() {
if (!empty($params['is_pledge_active'])) {
$deletePledgeBlk = FALSE;
- $pledgeBlockParams = array(
+ $pledgeBlockParams = [
'entity_id' => $contributionPageID,
'entity_table' => ts('civicrm_contribution_page'),
- );
+ ];
if ($this->_pledgeBlockID) {
$pledgeBlockParams['id'] = $this->_pledgeBlockID;
}
- $pledgeBlock = array(
+ $pledgeBlock = [
'pledge_frequency_unit',
'max_reminders',
'initial_reminder_day',
@@ -777,7 +772,7 @@ public function postProcess() {
'pledge_start_date',
'is_pledge_start_date_visible',
'is_pledge_start_date_editable',
- );
+ ];
foreach ($pledgeBlock as $key) {
$pledgeBlockParams[$key] = CRM_Utils_Array::value($key, $params);
}
diff --git a/CRM/Contribute/Form/ContributionPage/Custom.php b/CRM/Contribute/Form/ContributionPage/Custom.php
index 930a29512930..94f02e99c194 100644
--- a/CRM/Contribute/Form/ContributionPage/Custom.php
+++ b/CRM/Contribute/Form/ContributionPage/Custom.php
@@ -1,9 +1,9 @@
'contact_1', 'entity_type' => 'IndividualModel');
- $allowCoreTypes = array_merge(array('Contact', 'Individual'), CRM_Contact_BAO_ContactType::subTypes('Individual'));
- $allowSubTypes = array();
+ $entities = [];
+ $entities[] = ['entity_name' => 'contact_1', 'entity_type' => 'IndividualModel'];
+ $allowCoreTypes = array_merge(['Contact', 'Individual'], CRM_Contact_BAO_ContactType::subTypes('Individual'));
+ $allowSubTypes = [];
// Register 'contribution_1'
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'financial_type_id');
$allowCoreTypes[] = 'Contribution';
//CRM-15427
- $allowSubTypes['ContributionType'] = array($financialTypeId);
- $entities[] = array(
+ $allowSubTypes['ContributionType'] = [$financialTypeId];
+ $entities[] = [
'entity_name' => 'contribution_1',
'entity_type' => 'ContributionModel',
'entity_sub_type' => '*',
- );
+ ];
// If applicable, register 'membership_1'
$member = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
if ($member && $member['is_active']) {
//CRM-15427
- $entities[] = array(
+ $entities[] = [
'entity_name' => 'membership_1',
'entity_type' => 'MembershipModel',
'entity_sub_type' => '*',
- );
+ ];
$allowCoreTypes[] = 'Membership';
$allowSubTypes['MembershipType'] = explode(',', $member['membership_types']);
}
@@ -73,7 +73,7 @@ public function buildQuickForm() {
$this->addProfileSelector('custom_pre_id', ts('Include Profile') . ' ' . ts('(top of page)'), $allowCoreTypes, $allowSubTypes, $entities, TRUE);
$this->addProfileSelector('custom_post_id', ts('Include Profile') . ' ' . ts('(bottom of page)'), $allowCoreTypes, $allowSubTypes, $entities, TRUE);
- $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Custom', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contribute_Form_ContributionPage_Custom', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -106,12 +106,12 @@ public function postProcess() {
$transaction = new CRM_Core_Transaction();
// also update uf join table
- $ufJoinParams = array(
+ $ufJoinParams = [
'is_active' => 1,
'module' => 'CiviContribute',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $this->_id,
- );
+ ];
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
@@ -156,7 +156,7 @@ public function getTitle() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
$preProfileType = $postProfileType = NULL;
// for membership profile make sure Membership section is enabled
// get membership section for this contribution page
diff --git a/CRM/Contribute/Form/ContributionPage/Delete.php b/CRM/Contribute/Form/ContributionPage/Delete.php
index 22d186344fb2..a715b136d8b2 100644
--- a/CRM/Contribute/Form/ContributionPage/Delete.php
+++ b/CRM/Contribute/Form/ContributionPage/Delete.php
@@ -1,9 +1,9 @@
_relatedContributions) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'next',
'name' => ts('Delete Contribution Page'),
'isDefault' => TRUE,
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
}
@@ -105,10 +106,10 @@ public function postProcess() {
// first delete the join entries associated with this contribution page
$dao = new CRM_Core_DAO_UFJoin();
- $params = array(
+ $params = [
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $this->_id,
- );
+ ];
$dao->copyValues($params);
$dao->delete();
@@ -137,7 +138,7 @@ public function postProcess() {
$transaction->commit();
- CRM_Core_Session::setStatus(ts("The contribution page '%1' has been deleted.", array(1 => $this->_title)), ts('Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The contribution page '%1' has been deleted.", [1 => $this->_title]), ts('Deleted'), 'success');
}
}
diff --git a/CRM/Contribute/Form/ContributionPage/Premium.php b/CRM/Contribute/Form/ContributionPage/Premium.php
index f5c3bbe9b9c0..109dbc39edda 100644
--- a/CRM/Contribute/Form/ContributionPage/Premium.php
+++ b/CRM/Contribute/Form/ContributionPage/Premium.php
@@ -1,9 +1,9 @@
_id)) {
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
@@ -74,7 +74,7 @@ public function buildQuickForm() {
// CRM-10999 Control label and position for No Thank-you radio button
$this->add('text', 'premiums_nothankyou_label', ts('No Thank-you Label'), $attributes['premiums_nothankyou_label']);
- $positions = array(1 => ts('Before Premiums'), 2 => ts('After Premiums'));
+ $positions = [1 => ts('Before Premiums'), 2 => ts('After Premiums')];
$this->add('select', 'premiums_nothankyou_position', ts('No Thank-you Option'), $positions);
$showForm = TRUE;
@@ -92,7 +92,7 @@ public function buildQuickForm() {
$this->assign('showForm', $showForm);
parent::buildQuickForm();
- $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Premium', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contribute_Form_ContributionPage_Premium', 'formRule'], $this);
$premiumPage = new CRM_Contribute_Page_Premium();
$premiumPage->browse();
@@ -108,7 +108,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params) {
- $errors = array();
+ $errors = [];
if (!empty($params['premiums_active'])) {
if (empty($params['premiums_nothankyou_label'])) {
$errors['premiums_nothankyou_label'] = ts('No Thank-you Label is a required field.');
diff --git a/CRM/Contribute/Form/ContributionPage/Settings.php b/CRM/Contribute/Form/ContributionPage/Settings.php
index af346e884bec..0e7ae3ae58f8 100644
--- a/CRM/Contribute/Form/ContributionPage/Settings.php
+++ b/CRM/Contribute/Form/ContributionPage/Settings.php
@@ -1,9 +1,9 @@
_id) {
+ $defaults['start_date'] = date('Y-m-d H:i:s');
+ unset($defaults['start_time']);
+ }
$soft_credit_types = CRM_Core_OptionGroup::values('soft_credit_type', TRUE, FALSE, FALSE, NULL, 'name');
if ($this->_id) {
@@ -53,7 +58,7 @@ public function setDefaultValues() {
);
CRM_Utils_System::setTitle(ts('Title and Settings') . " ($title)");
- foreach (array('on_behalf', 'soft_credit') as $module) {
+ foreach (['on_behalf', 'soft_credit'] as $module) {
$ufJoinDAO = new CRM_Core_DAO_UFJoin();
$ufJoinDAO->module = $module;
$ufJoinDAO->entity_id = $this->_id;
@@ -78,10 +83,10 @@ public function setDefaultValues() {
if ($ufGroupDAO->find(TRUE)) {
$defaults['honoree_profile'] = $ufGroupDAO->id;
}
- $defaults['soft_credit_types'] = array(
+ $defaults['soft_credit_types'] = [
CRM_Utils_Array::value('in_honor_of', $soft_credit_types),
CRM_Utils_Array::value('in_memory_of', $soft_credit_types),
- );
+ ];
}
else {
$ufGroupDAO = new CRM_Core_DAO_UFGroup();
@@ -101,10 +106,10 @@ public function setDefaultValues() {
if ($ufGroupDAO->find(TRUE)) {
$defaults['honoree_profile'] = $ufGroupDAO->id;
}
- $defaults['soft_credit_types'] = array(
+ $defaults['soft_credit_types'] = [
CRM_Utils_Array::value('in_honor_of', $soft_credit_types),
CRM_Utils_Array::value('in_memory_of', $soft_credit_types),
- );
+ ];
}
return $defaults;
@@ -120,9 +125,9 @@ public function buildQuickForm() {
// financial Type
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
- $financialOptions = array(
+ $financialOptions = [
'options' => $financialTypes,
- );
+ ];
if (!CRM_Core_Permission::check('administer CiviCRM Financial Types')) {
$financialOptions['context'] = 'search';
}
@@ -139,42 +144,42 @@ public function buildQuickForm() {
$this->add('wysiwyg', 'footer_text', ts('Footer Message'), $attributes['footer_text']);
//Register schema which will be used for OnBehalOf and HonorOf profile Selector
- CRM_UF_Page_ProfileEditor::registerSchemas(array('OrganizationModel', 'HouseholdModel'));
+ CRM_UF_Page_ProfileEditor::registerSchemas(['OrganizationModel', 'HouseholdModel']);
// is on behalf of an organization ?
- $this->addElement('checkbox', 'is_organization', ts('Allow individuals to contribute and / or signup for membership on behalf of an organization?'), NULL, array('onclick' => "showHideByValue('is_organization',true,'for_org_text','table-row','radio',false);showHideByValue('is_organization',true,'for_org_option','table-row','radio',false);"));
+ $this->addElement('checkbox', 'is_organization', ts('Allow individuals to contribute and / or signup for membership on behalf of an organization?'), NULL, ['onclick' => "showHideByValue('is_organization',true,'for_org_text','table-row','radio',false);showHideByValue('is_organization',true,'for_org_option','table-row','radio',false);"]);
//CRM-15787 - If applicable, register 'membership_1'
$member = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
- $coreTypes = array('Contact', 'Organization');
+ $coreTypes = ['Contact', 'Organization'];
- $entities[] = array(
- 'entity_name' => array('contact_1'),
+ $entities[] = [
+ 'entity_name' => ['contact_1'],
'entity_type' => 'OrganizationModel',
- );
+ ];
if ($member && $member['is_active']) {
$coreTypes[] = 'Membership';
- $entities[] = array(
- 'entity_name' => array('membership_1'),
+ $entities[] = [
+ 'entity_name' => ['membership_1'],
'entity_type' => 'MembershipModel',
- );
+ ];
}
$allowCoreTypes = array_merge($coreTypes, CRM_Contact_BAO_ContactType::subTypes('Organization'));
- $allowSubTypes = array();
+ $allowSubTypes = [];
$this->addProfileSelector('onbehalf_profile_id', ts('Organization Profile'), $allowCoreTypes, $allowSubTypes, $entities);
- $options = array();
+ $options = [];
$options[] = $this->createElement('radio', NULL, NULL, ts('Optional'), 1);
$options[] = $this->createElement('radio', NULL, NULL, ts('Required'), 2);
$this->addGroup($options, 'is_for_organization', '');
- $this->add('textarea', 'for_organization', ts('On behalf of Label'), array('rows' => 2, 'cols' => 50));
+ $this->add('textarea', 'for_organization', ts('On behalf of Label'), ['rows' => 2, 'cols' => 50]);
// collect goal amount
- $this->add('text', 'goal_amount', ts('Goal Amount'), array('size' => 8, 'maxlength' => 12));
- $this->addRule('goal_amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $this->add('text', 'goal_amount', ts('Goal Amount'), ['size' => 8, 'maxlength' => 12]);
+ $this->addRule('goal_amount', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
// is confirmation page enabled?
$this->addElement('checkbox', 'is_confirm_enabled', ts('Use a confirmation page?'));
@@ -186,34 +191,34 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_active', ts('Is this Online Contribution Page Active?'));
// should the honor be enabled
- $this->addElement('checkbox', 'honor_block_is_active', ts('Honoree Section Enabled'), NULL, array('onclick' => "showHonor()"));
+ $this->addElement('checkbox', 'honor_block_is_active', ts('Honoree Section Enabled'), NULL, ['onclick' => "showHonor()"]);
- $this->add('text', 'honor_block_title', ts('Honoree Section Title'), array('maxlength' => 255, 'size' => 45));
+ $this->add('text', 'honor_block_title', ts('Honoree Section Title'), ['maxlength' => 255, 'size' => 45]);
- $this->add('textarea', 'honor_block_text', ts('Honoree Introductory Message'), array('rows' => 2, 'cols' => 50));
+ $this->add('textarea', 'honor_block_text', ts('Honoree Introductory Message'), ['rows' => 2, 'cols' => 50]);
- $this->addSelect('soft_credit_types', array(
+ $this->addSelect('soft_credit_types', [
'label' => ts('Honor Types'),
'entity' => 'ContributionSoft',
'field' => 'soft_credit_type_id',
'multiple' => TRUE,
'class' => 'huge',
- ));
+ ]);
- $entities = array(
- array(
+ $entities = [
+ [
'entity_name' => 'contact_1',
'entity_type' => 'IndividualModel',
- ),
- );
+ ],
+ ];
- $allowCoreTypes = array_merge(array(
- 'Contact',
- 'Individual',
- 'Organization',
- 'Household',
- ), CRM_Contact_BAO_ContactType::subTypes('Individual'));
- $allowSubTypes = array();
+ $allowCoreTypes = array_merge([
+ 'Contact',
+ 'Individual',
+ 'Organization',
+ 'Household',
+ ], CRM_Contact_BAO_ContactType::subTypes('Individual'));
+ $allowSubTypes = [];
$this->addProfileSelector('honoree_profile', ts('Honoree Profile'), $allowCoreTypes, $allowSubTypes, $entities);
@@ -223,10 +228,10 @@ public function buildQuickForm() {
}
// add optional start and end dates
- $this->addDateTime('start_date', ts('Start Date'));
- $this->addDateTime('end_date', ts('End Date'));
+ $this->add('datepicker', 'start_date', ts('Start Date'));
+ $this->add('datepicker', 'end_date', ts('End Date'));
- $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Settings', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contribute_Form_ContributionPage_Settings', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -244,7 +249,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errors = array();
+ $errors = [];
$contributionPageId = $self->_id;
//CRM-4286
if (strstr($values['title'], '/')) {
@@ -257,7 +262,7 @@ public static function formRule($values, $files, $self) {
$errors['onbehalf_profile_id'] = ts('Please select a profile to collect organization information on this contribution page.');
}
else {
- $requiredProfileFields = array('organization_name', 'email');
+ $requiredProfileFields = ['organization_name', 'email'];
if (!CRM_Core_BAO_UFGroup::checkValidProfile($values['onbehalf_profile_id'], $requiredProfileFields)) {
$errors['onbehalf_profile_id'] = ts('Profile does not contain the minimum required fields for an On Behalf Of Organization');
}
@@ -278,11 +283,11 @@ public static function formRule($values, $files, $self) {
//dont allow on behalf of save when
//pre or post profile consists of membership fields
if ($contributionPageId && !empty($values['is_organization'])) {
- $ufJoinParams = array(
+ $ufJoinParams = [
'module' => 'CiviContribute',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $contributionPageId,
- );
+ ];
list($contributionProfiles['custom_pre_id'],
$contributionProfiles['custom_post_id']
@@ -303,7 +308,7 @@ public static function formRule($values, $files, $self) {
}
}
if (!empty($conProfileType)) {
- $errors['is_organization'] = ts("You should move the membership related fields configured in %1 to the 'On Behalf' profile for this Contribution Page", array(1 => $conProfileType));
+ $errors['is_organization'] = ts("You should move the membership related fields configured in %1 to the 'On Behalf' profile for this Contribution Page", [1 => $conProfileType]);
}
}
return $errors;
@@ -334,10 +339,6 @@ public function postProcess() {
$params['is_credit_card_only'] = CRM_Utils_Array::value('is_credit_card_only', $params, FALSE);
$params['honor_block_is_active'] = CRM_Utils_Array::value('honor_block_is_active', $params, FALSE);
$params['is_for_organization'] = !empty($params['is_organization']) ? CRM_Utils_Array::value('is_for_organization', $params, FALSE) : 0;
-
- $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time'], TRUE);
- $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], $params['end_date_time'], TRUE);
-
$params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
if (!$params['honor_block_is_active']) {
@@ -347,18 +348,18 @@ public function postProcess() {
$dao = CRM_Contribute_BAO_ContributionPage::create($params);
- $ufJoinParams = array(
- 'is_organization' => array(
+ $ufJoinParams = [
+ 'is_organization' => [
'module' => 'on_behalf',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $dao->id,
- ),
- 'honor_block_is_active' => array(
+ ],
+ 'honor_block_is_active' => [
'module' => 'soft_credit',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $dao->id,
- ),
- );
+ ],
+ ];
foreach ($ufJoinParams as $index => $ufJoinParam) {
if (!empty($params[$index])) {
@@ -406,7 +407,7 @@ public function postProcess() {
$url = 'civicrm/admin/contribute';
$urlParams = 'reset=1';
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
- array(1 => $this->getTitle())
+ [1 => $this->getTitle()]
), ts('Saved'), 'success');
}
diff --git a/CRM/Contribute/Form/ContributionPage/TabHeader.php b/CRM/Contribute/Form/ContributionPage/TabHeader.php
index 8f9cad5e476c..c24edb0726e8 100644
--- a/CRM/Contribute/Form/ContributionPage/TabHeader.php
+++ b/CRM/Contribute/Form/ContributionPage/TabHeader.php
@@ -1,9 +1,9 @@
assign_by_ref('tabHeader', $tabs);
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header')
- ->addSetting(array(
- 'tabSettings' => array(
+ ->addSetting([
+ 'tabSettings' => [
'active' => self::getCurrentTab($tabs),
- ),
- ));
+ ],
+ ]);
return $tabs;
}
@@ -67,74 +68,74 @@ public static function process(&$form) {
return NULL;
}
- $tabs = array(
- 'settings' => array(
+ $tabs = [
+ 'settings' => [
'title' => ts('Title'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'amount' => array(
+ ],
+ 'amount' => [
'title' => ts('Amounts'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'membership' => array(
+ ],
+ 'membership' => [
'title' => ts('Memberships'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'thankyou' => array(
+ ],
+ 'thankyou' => [
'title' => ts('Receipt'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'friend' => array(
+ ],
+ 'friend' => [
'title' => ts('Tell a Friend'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'custom' => array(
+ ],
+ 'custom' => [
'title' => ts('Profiles'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'premium' => array(
+ ],
+ 'premium' => [
'title' => ts('Premiums'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'widget' => array(
+ ],
+ 'widget' => [
'title' => ts('Widgets'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- 'pcp' => array(
+ ],
+ 'pcp' => [
'title' => ts('Personal Campaigns'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
- ),
- );
+ ],
+ ];
$contribPageId = $form->getVar('_id');
- CRM_Utils_Hook::tabset('civicrm/admin/contribute', $tabs, array('contribution_page_id' => $contribPageId));
+ CRM_Utils_Hook::tabset('civicrm/admin/contribute', $tabs, ['contribution_page_id' => $contribPageId]);
$fullName = $form->getVar('_name');
$className = CRM_Utils_String::getClassName($fullName);
@@ -142,7 +143,7 @@ public static function process(&$form) {
switch ($className) {
case 'Contribute':
$attributes = $form->getVar('_attributes');
- $class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
+ $class = CRM_Utils_Request::retrieveComponent($attributes);
break;
case 'MembershipBlock':
@@ -177,7 +178,7 @@ public static function process(&$form) {
$tabs[$key]['active'] = $tabs[$key]['valid'] = TRUE;
}
//get all section info.
- $contriPageInfo = CRM_Contribute_BAO_ContributionPage::getSectionInfo(array($contribPageId));
+ $contriPageInfo = CRM_Contribute_BAO_ContributionPage::getSectionInfo([$contribPageId]);
foreach ($contriPageInfo[$contribPageId] as $section => $info) {
if (!$info) {
diff --git a/CRM/Contribute/Form/ContributionPage/ThankYou.php b/CRM/Contribute/Form/ContributionPage/ThankYou.php
index 9b90a9d7d385..d8a53f151a12 100644
--- a/CRM/Contribute/Form/ContributionPage/ThankYou.php
+++ b/CRM/Contribute/Form/ContributionPage/ThankYou.php
@@ -1,9 +1,9 @@
add('text', 'thankyou_title', ts('Thank-you Page Title'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'thankyou_title'), TRUE);
- $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'thankyou_text') + array('class' => 'collapsed');
+ $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'thankyou_text') + ['class' => 'collapsed'];
$this->add('wysiwyg', 'thankyou_text', ts('Thank-you Message'), $attributes);
$this->add('wysiwyg', 'thankyou_footer', ts('Thank-you Footer'), $attributes);
- $this->addElement('checkbox', 'is_email_receipt', ts('Email Receipt to Contributor?'), NULL, array('onclick' => "showReceipt()"));
+ $this->addElement('checkbox', 'is_email_receipt', ts('Email Receipt to Contributor?'), NULL, ['onclick' => "showReceipt()"]);
$this->add('text', 'receipt_from_name', ts('Receipt From Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'receipt_from_name'));
$this->add('text', 'receipt_from_email', ts('Receipt From Email'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'receipt_from_email'));
$this->add('textarea', 'receipt_text', ts('Receipt Message'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'receipt_text'));
@@ -70,7 +70,7 @@ public function buildQuickForm() {
$this->addRule('bcc_receipt', ts('Please enter a valid list of comma delimited email addresses'), 'emailList');
parent::buildQuickForm();
- $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_ThankYou', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contribute_Form_ContributionPage_ThankYou', 'formRule'], $this);
}
/**
@@ -87,7 +87,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $options) {
- $errors = array();
+ $errors = [];
// if is_email_receipt is set, the receipt message must be non-empty
if (!empty($fields['is_email_receipt'])) {
diff --git a/CRM/Contribute/Form/ContributionPage/Widget.php b/CRM/Contribute/Form/ContributionPage/Widget.php
index 7824a8c5b38d..2a88bc06b5df 100644
--- a/CRM/Contribute/Form/ContributionPage/Widget.php
+++ b/CRM/Contribute/Form/ContributionPage/Widget.php
@@ -1,9 +1,9 @@
_fields = array(
- 'title' => array(
+ $this->_fields = [
+ 'title' => [
ts('Title'),
'text',
FALSE,
$title,
- ),
- 'url_logo' => array(
+ ],
+ 'url_logo' => [
ts('URL to Logo Image'),
'text',
FALSE,
NULL,
- ),
- 'button_title' => array(
+ ],
+ 'button_title' => [
ts('Button Title'),
'text',
FALSE,
ts('Contribute!'),
- ),
- );
+ ],
+ ];
- $this->_colorFields = array(
- 'color_title' => array(
+ $this->_colorFields = [
+ 'color_title' => [
ts('Title Text Color'),
- 'text',
+ 'color',
FALSE,
'#2786C2',
- ),
- 'color_bar' => array(
+ ],
+ 'color_bar' => [
ts('Progress Bar Color'),
- 'text',
+ 'color',
FALSE,
'#2786C2',
- ),
- 'color_main_text' => array(
+ ],
+ 'color_main_text' => [
ts('Additional Text Color'),
- 'text',
+ 'color',
FALSE,
'#FFFFFF',
- ),
- 'color_main' => array(
+ ],
+ 'color_main' => [
ts('Background Color'),
- 'text',
+ 'color',
FALSE,
'#96C0E7',
- ),
- 'color_main_bg' => array(
+ ],
+ 'color_main_bg' => [
ts('Background Color Top Area'),
- 'text',
+ 'color',
FALSE,
'#B7E2FF',
- ),
- 'color_bg' => array(
+ ],
+ 'color_bg' => [
ts('Border Color'),
- 'text',
+ 'color',
FALSE,
'#96C0E7',
- ),
- 'color_about_link' => array(
+ ],
+ 'color_about_link' => [
ts('Button Text Color'),
- 'text',
+ 'color',
FALSE,
'#556C82',
- ),
- 'color_button' => array(
+ ],
+ 'color_button' => [
ts('Button Background Color'),
- 'text',
+ 'color',
FALSE,
'#FFFFFF',
- ),
- 'color_homepage_link' => array(
+ ],
+ 'color_homepage_link' => [
ts('Homepage Link Color'),
- 'text',
+ 'color',
FALSE,
'#FFFFFF',
- ),
- );
+ ],
+ ];
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
// check if there is a widget already created
if ($this->_widget) {
CRM_Core_DAO::storeValues($this->_widget, $defaults);
@@ -175,7 +175,7 @@ public function buildQuickForm() {
'is_active',
ts('Enable Widget?'),
NULL,
- array('onclick' => "widgetBlock(this)")
+ ['onclick' => "widgetBlock(this)"]
);
$this->add('wysiwyg', 'about', ts('About'), $attributes['about']);
@@ -206,7 +206,7 @@ public function buildQuickForm() {
ts('Save and Preview')
);
parent::buildQuickForm();
- $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Widget', 'formRule'), $this);
+ $this->addFormRule(['CRM_Contribute_Form_ContributionPage_Widget', 'formRule'], $this);
}
/**
@@ -222,7 +222,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($params['is_active'])) {
if (empty($params['title'])) {
$errors['title'] = ts('Title is a required field.');
@@ -233,7 +233,7 @@ public static function formRule($params, $files, $self) {
foreach ($params as $key => $val) {
if (substr($key, 0, 6) == 'color_' && empty($params[$key])) {
- $errors[$key] = ts('%1 is a required field.', array(1 => $self->_colorFields[$key][0]));
+ $errors[$key] = ts('%1 is a required field.', [1 => $self->_colorFields[$key][0]]);
}
}
}
diff --git a/CRM/Contribute/Form/ContributionRecur.php b/CRM/Contribute/Form/ContributionRecur.php
new file mode 100644
index 000000000000..24ad75822273
--- /dev/null
+++ b/CRM/Contribute/Form/ContributionRecur.php
@@ -0,0 +1,138 @@
+ 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'ContributionRecur';
+ }
+
+ /**
+ * Explicitly declare the form context.
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
+ /**
+ * Set variables up before form is built.
+ */
+ public function preProcess() {
+ $this->setAction(CRM_Core_Action::UPDATE);
+ $this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE);
+ $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
+ $this->contributionRecurID = $this->_crid;
+ $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
+ $this->setPaymentProcessor();
+ }
+
+ /**
+ * Set the payment processor object up.
+ *
+ * This is a function that needs to be better consolidated between the inheriting forms
+ * but this is good choice of function to call.
+ */
+ protected function setPaymentProcessor() {
+ if ($this->_crid) {
+ $this->_paymentProcessor = CRM_Contribute_BAO_ContributionRecur::getPaymentProcessor($this->contributionRecurID);
+ if (!$this->_paymentProcessor) {
+ CRM_Core_Error::statusBounce(ts('There is no valid processor for this subscription so it cannot be updated'));
+ }
+ $this->_paymentProcessorObj = $this->_paymentProcessor['object'];
+ }
+ }
+
+}
diff --git a/CRM/Contribute/Form/ContributionView.php b/CRM/Contribute/Form/ContributionView.php
index 21a6fa560f0c..a9eb615488e0 100644
--- a/CRM/Contribute/Form/ContributionView.php
+++ b/CRM/Contribute/Form/ContributionView.php
@@ -1,9 +1,9 @@
get('id');
- $params = array('id' => $id);
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $params = ['id' => $id];
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $context);
$values = CRM_Contribute_BAO_Contribution::getValuesWithMappings($params);
@@ -94,7 +94,7 @@ public function preProcess() {
if (!empty($values['contribution_recur_id'])) {
$sql = "SELECT installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1";
- $params = array(1 => array($values['contribution_recur_id'], 'Integer'));
+ $params = [1 => [$values['contribution_recur_id'], 'Integer']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$values['recur_installments'] = $dao->installments;
@@ -132,7 +132,7 @@ public function preProcess() {
// show billing address location details, if exists
if (!empty($values['address_id'])) {
- $addressParams = array('id' => CRM_Utils_Array::value('address_id', $values));
+ $addressParams = ['id' => CRM_Utils_Array::value('address_id', $values)];
$addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
$addressDetails = array_values($addressDetails);
$values['billing_address'] = $addressDetails[0]['display'];
@@ -150,10 +150,10 @@ public function preProcess() {
$this->assign($name, $value);
}
- $lineItems = array();
+ $lineItems = [];
$displayLineItems = FALSE;
if ($id) {
- $lineItems = array(CRM_Price_BAO_LineItem::getLineItemsByContributionID(($id)));
+ $lineItems = [CRM_Price_BAO_LineItem::getLineItemsByContributionID(($id))];
$firstLineItem = reset($lineItems[0]);
if (empty($firstLineItem['price_set_id'])) {
// CRM-20297 All we care is that it's not QuickConfig, so no price set
@@ -162,10 +162,10 @@ public function preProcess() {
}
else {
try {
- $priceSet = civicrm_api3('PriceSet', 'getsingle', array(
+ $priceSet = civicrm_api3('PriceSet', 'getsingle', [
'id' => $firstLineItem['price_set_id'],
'return' => 'is_quick_config, id',
- ));
+ ]);
$displayLineItems = !$priceSet['is_quick_config'];
}
catch (CiviCRM_API3_Exception $e) {
@@ -190,7 +190,7 @@ public function preProcess() {
// assign values to the template
$this->assign($values);
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
+ $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
$this->assign('invoicing', $invoicing);
$this->assign('isDeferred', CRM_Utils_Array::value('deferred_revenue_enabled', $invoiceSettings));
if ($invoicing && isset($values['tax_amount'])) {
@@ -215,7 +215,7 @@ public function preProcess() {
$title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount'], $values['currency']) . ' ' . ' - ' . $values['financial_type'] . ')';
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -235,7 +235,7 @@ public function preProcess() {
$recentOther
);
$contributionStatus = $status[$values['contribution_status_id']];
- if (in_array($contributionStatus, array('Partially paid', 'Pending refund'))
+ if (in_array($contributionStatus, ['Partially paid', 'Pending refund'])
|| ($contributionStatus == 'Pending' && $values['is_pay_later'])
) {
if ($contributionStatus == 'Pending refund') {
@@ -249,21 +249,44 @@ public function preProcess() {
$this->assign('componentId', $id);
$this->assign('component', 'contribution');
}
+ $this->assignPaymentInfoBlock($id);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
-
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
+ }
+
+ /**
+ * Assign the values to build the payment info block.
+ *
+ * @todo - this is a bit too much copy & paste from AbstractEditPayment
+ * (justifying on the basis it's 'pretty short' and in a different inheritance
+ * tree. I feel like traits are probably the longer term answer).
+ *
+ * @param int $id
+ *
+ * @return string
+ * Block title.
+ */
+ protected function assignPaymentInfoBlock($id) {
+ // component is used in getPaymentInfo primarily to retrieve the contribution id, we
+ // already have that.
+ $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($id, 'contribution', TRUE);
+ $title = ts('View Payment');
+ $this->assign('transaction', TRUE);
+ $this->assign('payments', $paymentInfo['transaction']);
+ $this->assign('paymentLinks', $paymentInfo['payment_links']);
+ return $title;
}
}
diff --git a/CRM/Contribute/Form/ManagePremiums.php b/CRM/Contribute/Form/ManagePremiums.php
index 5820ff296247..bbb5543e20f0 100644
--- a/CRM/Contribute/Form/ManagePremiums.php
+++ b/CRM/Contribute/Form/ManagePremiums.php
@@ -1,9 +1,9 @@
_id) {
- $params = array('id' => $this->_id);
- CRM_Contribute_BAO_ManagePremiums::retrieve($params, $tempDefaults);
- $imageUrl = (isset($tempDefaults['image'])) ? $tempDefaults['image'] : "";
+ $params = ['id' => $this->_id];
+ CRM_Contribute_BAO_Product::retrieve($params, $tempDefaults);
if (isset($tempDefaults['image']) && isset($tempDefaults['thumbnail'])) {
$defaults['imageUrl'] = $tempDefaults['image'];
$defaults['thumbnailUrl'] = $tempDefaults['thumbnail'];
@@ -92,10 +91,10 @@ public function buildQuickForm() {
$this->applyFilter('__ALL__', 'trim');
$this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'name'), TRUE);
- $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', array(
- 'CRM_Contribute_DAO_Product',
- $this->_id,
- ));
+ $this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', [
+ 'CRM_Contribute_DAO_Product',
+ $this->_id,
+ ]);
$this->add('text', 'sku', ts('SKU'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'sku'));
$this->add('textarea', 'description', ts('Description'), 'rows=3, cols=60');
@@ -124,25 +123,25 @@ public function buildQuickForm() {
$this->add('textarea', 'options', ts('Options'), 'rows=3, cols=60');
- $this->add('select', 'period_type', ts('Period Type'), array(
- '' => '- select -',
- 'rolling' => 'Rolling',
- 'fixed' => 'Fixed',
- ));
+ $this->add('select', 'period_type', ts('Period Type'), [
+ '' => '- select -',
+ 'rolling' => 'Rolling',
+ 'fixed' => 'Fixed',
+ ]);
$this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
- $this->add('Select', 'duration_unit', ts('Duration Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
+ $this->add('Select', 'duration_unit', ts('Duration Unit'), ['' => '- select period -'] + CRM_Core_SelectValues::getPremiumUnits());
$this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
- $this->add('Select', 'frequency_unit', ts('Frequency Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
+ $this->add('Select', 'frequency_unit', ts('Frequency Unit'), ['' => '- select period -'] + CRM_Core_SelectValues::getPremiumUnits());
$this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
//Financial Type CRM-11106
$financialType = CRM_Contribute_PseudoConstant::financialType();
- $premiumFinancialType = array();
+ $premiumFinancialType = [];
CRM_Core_PseudoConstant::populate(
$premiumFinancialType,
'CRM_Financial_DAO_EntityFinancialAccount',
@@ -152,7 +151,7 @@ public function buildQuickForm() {
'account_relationship = 8'
);
- $costFinancialType = array();
+ $costFinancialType = [];
CRM_Core_PseudoConstant::populate(
$costFinancialType,
'CRM_Financial_DAO_EntityFinancialAccount',
@@ -174,25 +173,24 @@ public function buildQuickForm() {
'select',
'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialType
+ ['' => ts('- select -')] + $financialType
);
$this->add('checkbox', 'is_active', ts('Enabled?'));
- $this->addFormRule(array('CRM_Contribute_Form_ManagePremiums', 'formRule'));
-
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addFormRule(['CRM_Contribute_Form_ManagePremiums', 'formRule']);
+
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
$this->assign('productId', $this->_id);
}
@@ -272,7 +270,15 @@ public function postProcess() {
// If deleting, then only delete and skip the rest of the post-processing
if ($this->_action & CRM_Core_Action::DELETE) {
- CRM_Contribute_BAO_ManagePremiums::del($this->_id);
+ try {
+ CRM_Contribute_BAO_Product::del($this->_id);
+ }
+ catch (CRM_Core_Exception $e) {
+ $message = ts("This Premium is linked to an Online Contribution page. Please remove it before deleting this Premium.", [1 => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1')]);
+ CRM_Core_Session::setStatus($message, ts('Cannot delete Premium'), 'error');
+ CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
+ return;
+ }
CRM_Core_Session::setStatus(
ts('Selected Premium Product type has been deleted.'),
ts('Deleted'), 'info');
@@ -282,23 +288,23 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
// Clean the the money fields
- $moneyFields = array('cost', 'price', 'min_contribution');
+ $moneyFields = ['cost', 'price', 'min_contribution'];
foreach ($moneyFields as $field) {
$params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
}
- $ids = array();
+ // If we're updating, we need to pass in the premium product Id
if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['premium'] = $this->_id;
+ $params['id'] = $this->_id;
}
$this->_processImages($params);
- // Save to database
- $premium = CRM_Contribute_BAO_ManagePremiums::add($params, $ids);
+ // Save the premium product to database
+ $premium = CRM_Contribute_BAO_Product::create($params);
CRM_Core_Session::setStatus(
- ts("The Premium '%1' has been saved.", array(1 => $premium->name)),
+ ts("The Premium '%1' has been saved.", [1 => $premium->name]),
ts('Saved'), 'success');
}
@@ -309,14 +315,14 @@ public function postProcess() {
* @param array $params
*/
protected function _processImages(&$params) {
- $defaults = array(
+ $defaults = [
'imageOption' => 'noImage',
- 'uploadFile' => array('name' => ''),
+ 'uploadFile' => ['name' => ''],
'image' => '',
'thumbnail' => '',
'imageUrl' => '',
'thumbnailUrl' => '',
- );
+ ];
$params = array_merge($defaults, $params);
// User is uploading an image
diff --git a/CRM/Contribute/Form/Search.php b/CRM/Contribute/Form/Search.php
index b0174523f6bb..8351b6d9ad8b 100644
--- a/CRM/Contribute/Form/Search.php
+++ b/CRM/Contribute/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- // @todo - is this an error - $this->_defaults is used.
- $this->defaults = array();
-
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
+ $this->loadStandardSearchOptionsFromUrl();
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
@@ -165,29 +161,13 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
- parent::buildQuickForm();
- $this->addSortNameField();
-
- $this->_group = CRM_Core_PseudoConstant::nestedGroup();
-
- // multiselect for groups
- if ($this->_group) {
- $this->add('select', 'group', ts('Groups'), $this->_group, FALSE,
- array('id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2')
- );
- }
-
- // multiselect for tags
- $contactTags = CRM_Core_BAO_Tag::getTags();
+ if ($this->isFormInViewOrEditMode()) {
+ parent::buildQuickForm();
+ $this->addContactSearchFields();
- if ($contactTags) {
- $this->add('select', 'contact_tags', ts('Tags'), $contactTags, FALSE,
- array('id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2')
- );
+ CRM_Contribute_BAO_Query::buildSearchForm($this);
}
- CRM_Contribute_BAO_Query::buildSearchForm($this);
-
$rows = $this->get('rows');
if (is_array($rows)) {
if (!$this->_single) {
@@ -197,11 +177,11 @@ public function buildQuickForm() {
$permission = CRM_Core_Permission::getPermission();
$queryParams = $this->get('queryParams');
- $softCreditFiltering = FALSE;
+ $taskParams['softCreditFiltering'] = FALSE;
if (!empty($queryParams)) {
- $softCreditFiltering = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($queryParams);
+ $taskParams['softCreditFiltering'] = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($queryParams);
}
- $tasks = CRM_Contribute_Task::permissionedTaskTitles($permission, $softCreditFiltering);
+ $tasks = CRM_Contribute_Task::permissionedTaskTitles($permission, $taskParams);
$this->addTaskMenu($tasks);
}
@@ -229,6 +209,36 @@ protected function getSortNameLabelWithOutEmail() {
return ts('Contributor Name');
}
+ /**
+ * Get the label for the tag field.
+ *
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
+ *
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Contributor Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getGroupLabel() {
+ return ts('Contributor Group(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Contributor Contact Type');
+ }
+
/**
* The post processing of the form gets done here.
*
@@ -248,7 +258,7 @@ public function postProcess() {
$this->_done = TRUE;
- if (!empty($_POST)) {
+ if (!empty($_POST) && !$this->_force) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
@@ -259,10 +269,10 @@ public function postProcess() {
$this->_formValues["contribution_test"] = 0;
}
- foreach (array(
- 'contribution_amount_low',
- 'contribution_amount_high',
- ) as $f) {
+ foreach ([
+ 'contribution_amount_low',
+ 'contribution_amount_high',
+ ] as $f) {
if (isset($this->_formValues[$f])) {
$this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
}
@@ -270,7 +280,7 @@ public function postProcess() {
$config = CRM_Core_Config::singleton();
if (!empty($_POST)) {
- $specialParams = array(
+ $specialParams = [
'financial_type_id',
'contribution_soft_credit_type_id',
'contribution_status_id',
@@ -281,7 +291,7 @@ public function postProcess() {
'invoice_id',
'payment_instrument_id',
'contribution_batch_id',
- );
+ ];
CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, $specialParams);
$tags = CRM_Utils_Array::value('contact_tags', $this->_formValues);
@@ -365,9 +375,7 @@ public function postProcess() {
if ($this->_context == 'user') {
$query->setSkipPermission(TRUE);
}
- $summary = &$query->summaryContribution($this->_context);
- $this->set('summary', $summary);
- $this->assign('contributionSummary', $summary);
+
$controller->run();
}
@@ -383,8 +391,8 @@ public function fixFormValues() {
$status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
- $this->_formValues['contribution_status_id'] = array($status => 1);
- $this->_defaults['contribution_status_id'] = array($status => 1);
+ $this->_formValues['contribution_status_id'] = [$status => 1];
+ $this->_defaults['contribution_status_id'] = [$status => 1];
}
$pcpid = (array) CRM_Utils_Request::retrieve('pcpid', 'String', $this);
diff --git a/CRM/Contribute/Form/SearchContribution.php b/CRM/Contribute/Form/SearchContribution.php
index 781ac5fa798d..1b3130469550 100644
--- a/CRM/Contribute/Form/SearchContribution.php
+++ b/CRM/Contribute/Form/SearchContribution.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
public function postProcess() {
@@ -62,7 +62,7 @@ public function postProcess() {
$parent = $this->controller->getParent();
$parent->set('searchResult', 1);
if (!empty($params)) {
- $fields = array('title', 'financial_type_id', 'campaign_id');
+ $fields = ['title', 'financial_type_id', 'campaign_id'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
diff --git a/CRM/Contribute/Form/SoftCredit.php b/CRM/Contribute/Form/SoftCredit.php
index 5ffc5e59f00b..431cb24dce16 100644
--- a/CRM/Contribute/Form/SoftCredit.php
+++ b/CRM/Contribute/Form/SoftCredit.php
@@ -1,9 +1,9 @@
find(TRUE)) {
$jsonData = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoinDAO->module_data, TRUE, 'soft_credit');
if ($jsonData) {
- foreach (array('honor_block_title', 'honor_block_text') as $name) {
+ foreach (['honor_block_title', 'honor_block_text'] as $name) {
$form->assign($name, $jsonData[$name]);
}
@@ -68,7 +68,7 @@ public static function buildQuickForm(&$form) {
}
// by default generate 10 blocks
- $item_count = 11;
+ $item_count = $form->_softCreditItemCount;
$showSoftCreditRow = 2;
if ($form->getAction() & CRM_Core_Action::UPDATE) {
@@ -96,15 +96,15 @@ public static function buildQuickForm(&$form) {
}
for ($rowNumber = 1; $rowNumber <= $item_count; $rowNumber++) {
- $form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Contact'), array('create' => TRUE));
+ $form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Contact'), ['create' => TRUE]);
$form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE);
- $form->addSelect("soft_credit_type[{$rowNumber}]", array(
- 'entity' => 'contribution_soft',
- 'field' => 'soft_credit_type_id',
- 'label' => ts('Type'),
- ));
+ $form->addSelect("soft_credit_type[{$rowNumber}]", [
+ 'entity' => 'contribution_soft',
+ 'field' => 'soft_credit_type_id',
+ 'label' => ts('Type'),
+ ]);
if (!empty($form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id'])) {
$form->add('hidden', "soft_credit_id[{$rowNumber}]",
$form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id']);
@@ -117,7 +117,7 @@ public static function buildQuickForm(&$form) {
$form->assign('rowCount', $item_count);
$form->addElement('hidden', 'sct_default_id',
CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
- array('id' => 'sct_default_id')
+ ['id' => 'sct_default_id']
);
}
@@ -135,7 +135,7 @@ public static function addPCPFields(&$form, $suffix = '') {
if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) {
$form->assign('siteHasPCPs', 1);
// Fixme: Not a true entityRef field. Relies on PCP.js.tpl
- $form->add('text', "pcp_made_through_id$suffix", ts('Credit to a Personal Campaign Page'), array('class' => 'twenty', 'placeholder' => ts('- select -')));
+ $form->add('text', "pcp_made_through_id$suffix", ts('Credit to a Personal Campaign Page'), ['class' => 'twenty', 'placeholder' => ts('- select -')]);
// stores the label
$form->add('hidden', "pcp_made_through$suffix");
$form->addElement('checkbox', "pcp_display_in_roll$suffix", ts('Display in Honor Roll?'), NULL);
@@ -191,7 +191,7 @@ public static function setDefaultValues(&$defaults, &$form) {
* Array of errors
*/
public static function formRule($fields, $errors, $self) {
- $errors = array();
+ $errors = [];
// if honor roll fields are populated but no PCP is selected
if (empty($fields['pcp_made_through_id'])) {
diff --git a/CRM/Contribute/Form/Task.php b/CRM/Contribute/Form/Task.php
index 3f1a4e50f8a2..fac10e2ac666 100644
--- a/CRM/Contribute/Form/Task.php
+++ b/CRM/Contribute/Form/Task.php
@@ -1,9 +1,9 @@
_contributionIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_contributionIds = [];
$values = $form->controller->exportValues($form->get('searchFormName'));
@@ -105,7 +77,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$contributeTasks = CRM_Contribute_Task::tasks();
$form->assign('taskName', CRM_Utils_Array::value($form->_task, $contributeTasks));
- $ids = array();
+ $ids = [];
if (isset($values['radio_ts']) && $values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -116,27 +88,29 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
else {
$queryParams = $form->get('queryParams');
$isTest = FALSE;
- foreach ($queryParams as $fields) {
- if ($fields[0] == 'contribution_test') {
- $isTest = TRUE;
- break;
+ if (is_array($queryParams)) {
+ foreach ($queryParams as $fields) {
+ if ($fields[0] == 'contribution_test') {
+ $isTest = TRUE;
+ break;
+ }
}
}
if (!$isTest) {
- $queryParams[] = array(
+ $queryParams[] = [
'contribution_test',
'=',
0,
0,
0,
- );
+ ];
}
- $returnProperties = array('contribution_id' => 1);
+ $returnProperties = ['contribution_id' => 1];
$sortOrder = $sortCol = NULL;
if ($form->get(CRM_Utils_Sort::SORT_ORDER)) {
$sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER);
//Include sort column in select clause.
- $sortCol = trim(str_replace(array('`', 'asc', 'desc'), '', $sortOrder));
+ $sortCol = trim(str_replace(['`', 'asc', 'desc'], '', $sortOrder));
$returnProperties[$sortCol] = 1;
}
@@ -147,7 +121,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
// @todo the function CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled should handle this
// can we remove? if not why not?
if ($form->_includesSoftCredits) {
- $contactIds = $contributionContactIds = array();
+ $contactIds = $contributionContactIds = [];
$query->_rowCountClause = " count(civicrm_contribution.id)";
$query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
}
@@ -163,7 +137,6 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$contributionContactIds["{$result->contact_id}-{$result->contribution_id}"] = $result->contribution_id;
}
}
- $result->free();
$form->assign('totalSelectedContributions', $form->get('rowCount'));
}
@@ -215,7 +188,7 @@ public function setContributionIds($contributionIds) {
*/
public function setContactIDs() {
if (!$this->_includesSoftCredits) {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent(
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent(
$this->_contributionIds,
'civicrm_contribution'
);
@@ -234,18 +207,17 @@ public function setContactIDs() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Contribute/Form/Task/Batch.php b/CRM/Contribute/Form/Task/Batch.php
index 3964d6cbdcb1..b2f32ee2549c 100644
--- a/CRM/Contribute/Form/Task/Batch.php
+++ b/CRM/Contribute/Form/Task/Batch.php
@@ -1,9 +1,9 @@
ts('Name')),
+ $readOnlyFields = array_merge(['sort_name' => ts('Name')],
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
@@ -89,12 +91,12 @@ public function buildQuickForm() {
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
- $this->_fields = array();
+ $this->_fields = [];
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
// remove file type field and then limit fields
$suppressFields = FALSE;
- $removehtmlTypes = array('File', 'Autocomplete-Select');
+ $removehtmlTypes = ['File'];
foreach ($this->_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -112,25 +114,24 @@ public function buildQuickForm() {
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Update Contribution(s)'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Update Contribution(s)'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_contributionIds);
//load all campaigns.
if (array_key_exists('contribution_campaign_id', $this->_fields)) {
- $this->_componentCampaigns = array();
+ $this->_componentCampaigns = [];
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Contribute_DAO_Contribution',
TRUE, 'campaign_id', 'id',
@@ -141,14 +142,14 @@ public function buildQuickForm() {
// It is possible to have fields that are required in CiviCRM not be required in the
// profile. Overriding that here. Perhaps a better approach would be to
// make them required in the schema & read that up through getFields functionality.
- $requiredFields = array('receive_date');
+ $requiredFields = ['receive_date'];
//fix for CRM-2752
$customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
foreach ($this->_contributionIds as $contributionId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $contributionId, 'financial_type_id');
foreach ($this->_fields as $name => $field) {
- $entityColumnValue = array();
+ $entityColumnValue = [];
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $customFields);
if (!empty($customValue['extends_entity_column_value'])) {
@@ -179,7 +180,7 @@ public function buildQuickForm() {
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_Batch_next') {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple contributions."), ts('Unsupported Field Type'), 'error');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple contributions."), ts('Unsupported Field Type'), 'error');
}
$this->addDefaultButtons(ts('Update Contributions'));
@@ -193,7 +194,7 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_contributionIds as $contributionId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $contributionId, 'Contribute');
}
@@ -206,6 +207,9 @@ public function setDefaultValues() {
*/
public function postProcess() {
$params = $this->exportValues();
+ // @todo extract submit functions &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test
+ // handling of custom data, specifically checkbox fields.
if (isset($params['field'])) {
foreach ($params['field'] as $contributionID => $value) {
@@ -214,9 +218,9 @@ public function postProcess() {
$value['financial_type_id'] = $value['financial_type'];
}
- $value['options'] = array(
+ $value['options'] = [
'reload' => 1,
- );
+ ];
$contribution = civicrm_api3('Contribution', 'create', $value);
$contribution = $contribution['values'][$contributionID];
diff --git a/CRM/Contribute/Form/Task/Delete.php b/CRM/Contribute/Form/Task/Delete.php
index 76b81892225c..8601ee564c11 100644
--- a/CRM/Contribute/Form/Task/Delete.php
+++ b/CRM/Contribute/Form/Task/Delete.php
@@ -1,9 +1,9 @@
_contributionIds)) {
- CRM_Core_Session::setStatus(ts('1 contribution could not be deleted.', array('plural' => '%count contributions could not be deleted.', 'count' => $count)), ts('Error'), 'error');
- $this->addButtons(array(
- array(
+ CRM_Core_Session::setStatus(ts('1 contribution could not be deleted.', ['plural' => '%count contributions could not be deleted.', 'count' => $count]), ts('Error'), 'error');
+ $this->addButtons([
+ [
'type' => 'back',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
elseif ($count && !empty($this->_contributionIds)) {
- CRM_Core_Session::setStatus(ts('1 contribution will not be deleted.', array('plural' => '%count contributions will not be deleted.', 'count' => $count)), ts('Warning'), 'warning');
+ CRM_Core_Session::setStatus(ts('1 contribution will not be deleted.', ['plural' => '%count contributions will not be deleted.', 'count' => $count]), ts('Warning'), 'warning');
$this->addDefaultButtons(ts('Delete Contributions'), 'done');
}
else {
@@ -115,12 +114,12 @@ public function postProcess() {
}
if ($deleted) {
- $msg = ts('%count contribution deleted.', array('plural' => '%count contributions deleted.', 'count' => $deleted));
+ $msg = ts('%count contribution deleted.', ['plural' => '%count contributions deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Contribute/Form/Task/Email.php b/CRM/Contribute/Form/Task/Email.php
index 0156f14a410b..1300c85d5e7e 100644
--- a/CRM/Contribute/Form/Task/Email.php
+++ b/CRM/Contribute/Form/Task/Email.php
@@ -1,9 +1,9 @@
_contributionIds = array($id);
+ $this->_contributionIds = [$id];
$this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
$this->_single = TRUE;
$this->assign('totalSelectedContributions', 1);
@@ -92,8 +96,8 @@ public function preProcess() {
// check that all the contribution ids have status Completed, Pending, Refunded.
$this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
- $status = array('Completed', 'Pending', 'Refunded');
- $statusId = array();
+ $status = ['Completed', 'Pending', 'Refunded'];
+ $statusId = [];
foreach ($this->_contributionStatusId as $key => $value) {
if (in_array($value, $status)) {
$statusId[] = $key;
@@ -117,18 +121,19 @@ public function preProcess() {
}
$url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'url' => $url,
'title' => ts('Search Results'),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
$this->_selectedOutput = CRM_Utils_Request::retrieve('select', 'String', $this);
$this->assign('selectedOutput', $this->_selectedOutput);
+ CRM_Contact_Form_Task_EmailCommon::preProcessFromAddress($this);
if ($this->_selectedOutput == 'email') {
CRM_Utils_System::setTitle(ts('Email Invoice'));
}
@@ -141,63 +146,38 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $session = CRM_Core_Session::singleton();
$this->preventAjaxSubmit();
if (CRM_Core_Permission::check('administer CiviCRM')) {
$this->assign('isAdmin', 1);
}
- $contactID = $session->get('userID');
- $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
- $emails = array();
- $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
- $contactID, 'display_name'
- );
- foreach ($contactEmails as $emailId => $item) {
- $email = $item['email'];
- if ($email) {
- $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
- }
- if (isset($emails[$emailId])) {
- $emails[$emailId] .= $item['locationType'];
- if ($item['is_primary']) {
- $emails[$emailId] .= ' ' . ts('(preferred)');
- }
- $emails[$emailId] = htmlspecialchars($emails[$emailId]);
- }
- }
- $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
- foreach ($fromEmailAddress as $key => $email) {
- $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
- }
- $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
- $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
+
+ $this->add('select', 'from_email_address', ts('From'), $this->_fromEmails, TRUE);
if ($this->_selectedOutput != 'email') {
$this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
$this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
$this->addRule('output', ts('Selection required'), 'required');
- $this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
+ $this->addFormRule(['CRM_Contribute_Form_Task_Invoice', 'formRule']);
}
else {
$this->addRule('from_email_address', ts('From Email Address is required'), 'required');
}
- $this->add('wysiwyg', 'email_comment', ts('If you would like to add personal message to email please add it here. (If sending to more then one receipient the same message will be sent to each contact.)'), array(
+ $this->add('wysiwyg', 'email_comment', ts('If you would like to add personal message to email please add it here. (If sending to more then one receipient the same message will be sent to each contact.)'), [
'rows' => 2,
'cols' => 40,
- ));
-
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ ]);
+
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -209,7 +189,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values) {
- $errors = array();
+ $errors = [];
if ($values['output'] == 'email_invoice' && empty($values['from_email_address'])) {
$errors['from_email_address'] = ts("From Email Address is required");
@@ -238,7 +218,7 @@ public function postProcess() {
*/
public static function printPDF($contribIDs, &$params, $contactIds) {
// get all the details needed to generate a invoice
- $messageInvoice = array();
+ $messageInvoice = [];
$invoiceTemplate = CRM_Core_Smarty::singleton();
$invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
@@ -252,7 +232,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
foreach ($invoiceElements['details'] as $contribID => $detail) {
- $input = $ids = $objects = array();
+ $input = $ids = $objects = [];
if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
continue;
}
@@ -281,11 +261,11 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
$objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
- $addressParams = array('contact_id' => $contribution->contact_id);
+ $addressParams = ['contact_id' => $contribution->contact_id];
$addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
// to get billing address if present
- $billingAddress = array();
+ $billingAddress = [];
foreach ($addressDetails as $address) {
if (($address['is_billing'] == 1) && ($address['is_primary'] == 1) && ($address['contact_id'] == $contribution->contact_id)) {
$billingAddress[$address['contact_id']] = $address;
@@ -312,7 +292,9 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
$creditNoteId = $contribution->creditnote_id;
}
}
- $invoiceNumber = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
+ if (!$contribution->invoice_number) {
+ $contribution->invoice_number = CRM_Contribute_BAO_Contribution::getInvoiceNumber($contribution->id);
+ }
//to obtain due date for PDF invoice
$contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
@@ -327,10 +309,10 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
$lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, 'participant', NULL, TRUE, FALSE, TRUE);
}
- $resultPayments = civicrm_api3('Payment', 'get', array(
- 'sequential' => 1,
- 'contribution_id' => $contribID,
- ));
+ $resultPayments = civicrm_api3('Payment', 'get', [
+ 'sequential' => 1,
+ 'contribution_id' => $contribID,
+ ]);
$amountPaid = 0;
foreach ($resultPayments['values'] as $singlePayment) {
// Only count payments that have been (status =) completed.
@@ -341,7 +323,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
$amountDue = ($input['amount'] - $amountPaid);
// retrieving the subtotal and sum of same tax_rate
- $dataArray = array();
+ $dataArray = [];
$subTotal = 0;
foreach ($lineItem as $taxRate) {
if (isset($dataArray[(string) $taxRate['tax_rate']])) {
@@ -354,18 +336,18 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
}
// to email the invoice
- $mailDetails = array();
- $values = array();
+ $mailDetails = [];
+ $values = [];
if ($contribution->_component == 'event') {
$daoName = 'CRM_Event_DAO_Event';
$pageId = $contribution->_relatedObjects['event']->id;
- $mailElements = array(
+ $mailElements = [
'title',
'confirm_from_name',
'confirm_from_email',
'cc_confirm',
'bcc_confirm',
- );
+ ];
CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
$values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
$values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
@@ -378,13 +360,13 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
elseif ($contribution->_component == 'contribute') {
$daoName = 'CRM_Contribute_DAO_ContributionPage';
$pageId = $contribution->contribution_page_id;
- $mailElements = array(
+ $mailElements = [
'title',
'receipt_from_name',
'receipt_from_email',
'cc_receipt',
'bcc_receipt',
- );
+ ];
CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
$values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
@@ -404,7 +386,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
// get organization address
$domain = CRM_Core_BAO_Domain::getDomain();
- $locParams = array('contact_id' => $domain->contact_id);
+ $locParams = ['contact_id' => $domain->contact_id];
$locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
if (isset($locationDefaults['address'][1]['state_province_id'])) {
$stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
@@ -420,12 +402,12 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
}
// parameters to be assign for template
- $tplParams = array(
+ $tplParams = [
'title' => $title,
'component' => $input['component'],
'id' => $contribution->id,
'source' => $source,
- 'invoice_number' => $invoiceNumber,
+ 'invoice_number' => $contribution->invoice_number,
'invoice_id' => $contribution->invoice_id,
'resourceBase' => $config->userFrameworkResourceURL,
'defaultCurrency' => $config->defaultCurrency,
@@ -442,6 +424,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
'pendingStatusId' => $pendingStatusId,
'cancelledStatusId' => $cancelledStatusId,
'contribution_status_id' => $contribution->contribution_status_id,
+ 'contributionStatusName' => CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id),
'subTotal' => $subTotal,
'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
@@ -463,49 +446,24 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
'domain_country' => $countryDomain,
'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
- );
+ ];
if (isset($creditNoteId)) {
$tplParams['creditnote_id'] = $creditNoteId;
}
- $pdfFileName = "{$invoiceNumber}.pdf";
- $sendTemplateParams = array(
+ $pdfFileName = $contribution->invoice_number . ".pdf";
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'contribution_invoice_receipt',
'contactId' => $contribution->contact_id,
'tplParams' => $tplParams,
'PDFFilename' => $pdfFileName,
- );
- $session = CRM_Core_Session::singleton();
- $contactID = $session->get('userID');
- //CRM-16319 - we dont store in userID in case the user is doing multiple
- //transactions etc
- if (empty($contactID)) {
- $contactID = $session->get('transaction.userID');
- }
- // Fix Invoice email doesnot send out when completed payment using Paypal
- if (empty($contactID)) {
- $contactID = current($contactIds);
- }
- $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
- $emails = array();
- $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
- $contactID, 'display_name'
- );
-
- foreach ($contactEmails as $emailId => $item) {
- $email = $item['email'];
- if ($email) {
- $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
- }
- }
- $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
+ ];
// from email address
- if (isset($params['from_email_address'])) {
- $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
- }
+ $fromEmailAddress = CRM_Utils_Array::value('from_email_address', $params);
+
// condition to check for download PDF Invoice or email Invoice
if ($invoiceElements['createPdf']) {
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
@@ -513,11 +471,11 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
return $html;
}
else {
- $mail = array(
+ $mail = [
'subject' => $subject,
'body' => $message,
'html' => $html,
- );
+ ];
if ($mail['html']) {
$messageInvoice[] = $mail['html'];
}
@@ -529,7 +487,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
elseif ($contribution->_component == 'contribute') {
$email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
- $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
+ $sendTemplateParams['tplParams'] = array_merge($tplParams, ['email_comment' => $invoiceElements['params']['email_comment']]);
$sendTemplateParams['from'] = $fromEmailAddress;
$sendTemplateParams['toEmail'] = $email;
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
@@ -537,14 +495,13 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
// functions call for adding activity with attachment
- $pdfFileName = "{$invoiceNumber}.pdf";
$fileName = self::putFile($html, $pdfFileName);
self::addActivities($subject, $contribution->contact_id, $fileName, $params);
}
elseif ($contribution->_component == 'event') {
$email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
- $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
+ $sendTemplateParams['tplParams'] = array_merge($tplParams, ['email_comment' => $invoiceElements['params']['email_comment']]);
$sendTemplateParams['from'] = $fromEmailAddress;
$sendTemplateParams['toEmail'] = $email;
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
@@ -552,12 +509,9 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
// functions call for adding activity with attachment
- $pdfFileName = "{$invoiceNumber}.pdf";
$fileName = self::putFile($html, $pdfFileName);
self::addActivities($subject, $contribution->contact_id, $fileName, $params);
}
-
- CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_number', $invoiceNumber);
$invoiceTemplate->clearTemplateVars();
}
@@ -566,12 +520,11 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
return $html;
}
else {
- $pdfFileName = "{$invoiceNumber}.pdf";
- CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
+ CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, [
'margin_top' => 10,
'margin_left' => 65,
'metric' => 'px',
- ));
+ ]);
// functions call for adding activity with attachment
$fileName = self::putFile($html, $pdfFileName);
self::addActivities($subject, $contactIds, $fileName, $params);
@@ -581,7 +534,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
}
else {
if ($invoiceElements['suppressedEmails']) {
- $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
+ $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', [1 => $invoiceElements['suppressedEmails']]);
$msgTitle = ts('Email Error');
$msgType = 'error';
}
@@ -607,7 +560,7 @@ public static function printPDF($contribIDs, &$params, $contactIds) {
* For invoices.
*
*/
- static public function addActivities($subject, $contactIds, $fileName, $params) {
+ public static function addActivities($subject, $contactIds, $fileName, $params) {
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
$config = CRM_Core_Config::singleton();
@@ -628,19 +581,19 @@ static public function addActivities($subject, $contactIds, $fileName, $params)
);
}
- $activityParams = array(
+ $activityParams = [
'subject' => $subject,
'source_contact_id' => $userID,
'target_contact_id' => $contactIds,
'activity_type_id' => $activityTypeID,
'activity_date_time' => date('YmdHis'),
- 'attachFile_1' => array(
+ 'attachFile_1' => [
'uri' => $fileName,
'type' => 'application/pdf',
'location' => $fileName,
'upload_date' => date('YmdHis'),
- ),
- );
+ ],
+ ];
CRM_Activity_BAO_Activity::create($activityParams);
}
@@ -655,7 +608,7 @@ static public function addActivities($subject, $contactIds, $fileName, $params)
* @return string
* Name of file which is in pdf format
*/
- static public function putFile($html, $name = 'Invoice.pdf') {
+ public static function putFile($html, $name = 'Invoice.pdf') {
$options = new Options();
$options->set('isRemoteEnabled', TRUE);
@@ -674,9 +627,9 @@ static public function putFile($html, $name = 'Invoice.pdf') {
*/
public static function getPrintPDF() {
$contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
- $contributionIDs = array($contributionId);
+ $contributionIDs = [$contributionId];
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
- $params = array('output' => 'pdf_invoice');
+ $params = ['output' => 'pdf_invoice'];
CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId);
}
diff --git a/CRM/Contribute/Form/Task/PDF.php b/CRM/Contribute/Form/Task/PDF.php
index 2455d38fdecd..c27b4fd176ac 100644
--- a/CRM/Contribute/Form/Task/PDF.php
+++ b/CRM/Contribute/Form/Task/PDF.php
@@ -1,9 +1,9 @@
_contributionIds = array($id);
+ $this->_contributionIds = [$id];
$this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
$this->_single = TRUE;
$this->assign('totalSelectedContributions', 1);
@@ -85,12 +85,12 @@ public function preProcess() {
}
$url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'url' => $url,
'title' => ts('Search Results'),
- ),
- );
+ ],
+ ];
CRM_Contact_Form_Task_EmailCommon ::preProcessFromAddress($this, FALSE);
// we have all the contribution ids, so now we get the contact ids
parent::setContactIDs();
@@ -104,35 +104,38 @@ public function preProcess() {
public function buildQuickForm() {
$this->addElement('radio', 'output', NULL, ts('Email Receipts'), 'email_receipt',
- array(
+ [
'onClick' => "document.getElementById('selectPdfFormat').style.display = 'none';
- document.getElementById('selectEmailFrom').style.display = 'block';")
+ document.getElementById('selectEmailFrom').style.display = 'block';",
+ ]
);
$this->addElement('radio', 'output', NULL, ts('PDF Receipts'), 'pdf_receipt',
- array('onClick' => "document.getElementById('selectPdfFormat').style.display = 'block';")
+ [
+ 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'block';
+ document.getElementById('selectEmailFrom').style.display = 'none';",
+ ]
);
$this->addRule('output', ts('Selection required'), 'required');
$this->add('select', 'pdf_format_id', ts('Page Format'),
- array(0 => ts('- default -')) + CRM_Core_BAO_PdfFormat::getList(TRUE)
+ [0 => ts('- default -')] + CRM_Core_BAO_PdfFormat::getList(TRUE)
);
$this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
$this->add('checkbox', 'override_privacy', ts('Override privacy setting? (Do not email / Do not mail)'), FALSE);
- $this->add('select', 'fromEmailAddress', ts('From Email'), $this->_fromEmails, FALSE, array('class' => 'crm-select2 huge'));
-
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Process Receipt(s)'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->add('select', 'from_email_address', ts('From Email'), $this->_fromEmails, FALSE);
+
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Process Receipt(s)'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -140,7 +143,7 @@ public function buildQuickForm() {
*/
public function setDefaultValues() {
$defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
- return array('pdf_format_id' => $defaultFormat['id'], 'receipt_update' => 1, 'override_privacy' => 0);
+ return ['pdf_format_id' => $defaultFormat['id'], 'receipt_update' => 1, 'override_privacy' => 0];
}
/**
@@ -148,14 +151,14 @@ public function setDefaultValues() {
*/
public function postProcess() {
// get all the details needed to generate a receipt
- $message = array();
+ $message = [];
$template = CRM_Core_Smarty::singleton();
$params = $this->controller->exportValues($this->_name);
$elements = self::getElements($this->_contributionIds, $params, $this->_contactIds);
foreach ($elements['details'] as $contribID => $detail) {
- $input = $ids = $objects = array();
+ $input = $ids = $objects = [];
if (in_array($detail['contact'], $elements['excludeContactIds'])) {
continue;
@@ -190,17 +193,20 @@ public function postProcess() {
CRM_Core_DAO::singleValueQuery("SELECT payment_processor_id
FROM civicrm_financial_trxn
WHERE trxn_id = %1
- LIMIT 1", array(
- 1 => array($contribution->trxn_id, 'String')));
+ LIMIT 1", [
+ 1 => [$contribution->trxn_id, 'String'],
+ ]);
// CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
$objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
- $values = array();
- if (isset($params['fromEmailAddress']) && !$elements['createPdf']) {
+ $values = [];
+ if (isset($params['from_email_address']) && !$elements['createPdf']) {
+ // If a logged in user from email is used rather than a domain wide from email address
+ // the from_email_address params key will be numerical and we need to convert it to be
+ // in normal from email format
+ $from = CRM_Utils_Mail::formatFromAddress($params['from_email_address']);
// CRM-19129 Allow useres the choice of From Email to send the receipt from.
- $fromEmail = $params['fromEmailAddress'];
- $from = CRM_Utils_Array::value($fromEmail, $this->_emails);
$fromDetails = explode(' <', $from);
$input['receipt_from_email'] = substr(trim($fromDetails[1]), 0, -1);
$input['receipt_from_name'] = str_replace('"', '', $fromDetails[0]);
@@ -230,7 +236,7 @@ public function postProcess() {
}
else {
if ($elements['suppressedEmails']) {
- $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $elements['suppressedEmails']));
+ $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', [1 => $elements['suppressedEmails']]);
$msgTitle = ts('Email Error');
$msgType = 'error';
}
@@ -258,8 +264,8 @@ public function postProcess() {
* array of common elements
*
*/
- static public function getElements($contribIds, $params, $contactIds) {
- $pdfElements = array();
+ public static function getElements($contribIds, $params, $contactIds) {
+ $pdfElements = [];
$pdfElements['contribIDs'] = implode(',', $contribIds);
@@ -276,14 +282,14 @@ static public function getElements($contribIds, $params, $contactIds) {
$pdfElements['createPdf'] = TRUE;
}
- $excludeContactIds = array();
+ $excludeContactIds = [];
if (!$pdfElements['createPdf']) {
- $returnProperties = array(
+ $returnProperties = [
'email' => 1,
'do_not_email' => 1,
'is_deceased' => 1,
'on_hold' => 1,
- );
+ ];
list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, FALSE, FALSE);
$pdfElements['suppressedEmails'] = 0;
diff --git a/CRM/Contribute/Form/Task/PDFLetter.php b/CRM/Contribute/Form/Task/PDFLetter.php
index de0afcc2cbfd..03620ec4dd2c 100644
--- a/CRM/Contribute/Form/Task/PDFLetter.php
+++ b/CRM/Contribute/Form/Task/PDFLetter.php
@@ -1,9 +1,9 @@
skipOnHold = $this->skipDeceased = FALSE;
CRM_Contact_Form_Task_PDFLetterCommon::preProcess($this);
// store case id if present
- $this->_caseId = CRM_Utils_Request::retrieve('caseid', 'Positive', $this, FALSE);
+ $this->_caseId = CRM_Utils_Request::retrieve('caseid', 'CommaSeparatedIntegers', $this, FALSE);
+ if (!empty($this->_caseId) && strpos($this->_caseId, ',')) {
+ $this->_caseIds = explode(',', $this->_caseId);
+ unset($this->_caseId);
+ }
// retrieve contact ID if this is 'single' mode
- $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
+ $cid = CRM_Utils_Request::retrieve('cid', 'CommaSeparatedIntegers', $this, FALSE);
$this->_activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
if ($cid) {
CRM_Contact_Form_Task_PDFLetterCommon::preProcessSingle($this, $cid);
$this->_single = TRUE;
- $this->_cid = $cid;
}
else {
parent::preProcess();
@@ -81,13 +84,14 @@ public function preProcess() {
* @return array
* reference to the array of default values
*/
+
/**
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_activityId)) {
- $params = array('id' => $this->_activityId);
+ $params = ['id' => $this->_activityId];
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
$defaults['html_message'] = CRM_Utils_Array::value('details', $defaults);
}
@@ -105,8 +109,8 @@ public function buildQuickForm() {
//enable form element
$this->assign('suppressForm', FALSE);
- // use contact form as a base
- CRM_Contact_Form_Task_PDFLetterCommon::buildQuickForm($this);
+ // Build common form elements
+ CRM_Contribute_Form_Task_PDFLetterCommon::buildQuickForm($this);
// specific need for contributions
$this->add('static', 'more_options_header', NULL, ts('Thank-you Letter Options'));
@@ -114,42 +118,41 @@ public function buildQuickForm() {
$this->add('checkbox', 'thankyou_update', ts('Update thank-you dates for these contributions'), FALSE);
// Group options for tokens are not yet implemented. dgg
- $options = array(
+ $options = [
'' => ts('- no grouping -'),
'contact_id' => ts('Contact'),
'contribution_recur_id' => ts('Contact and Recurring'),
'financial_type_id' => ts('Contact and Financial Type'),
'campaign_id' => ts('Contact and Campaign'),
'payment_instrument_id' => ts('Contact and Payment Method'),
- );
- $this->addElement('select', 'group_by', ts('Group contributions by'), $options, array(), " ", FALSE);
+ ];
+ $this->addElement('select', 'group_by', ts('Group contributions by'), $options, [], " ", FALSE);
// this was going to be free-text but I opted for radio options in case there was a script injection risk
- $separatorOptions = array('comma' => 'Comma', 'td' => 'Horizontal Table Cell', 'tr' => 'Vertical Table Cell', 'br' => 'Line Break');
+ $separatorOptions = ['comma' => 'Comma', 'td' => 'Horizontal Table Cell', 'tr' => 'Vertical Table Cell', 'br' => 'Line Break'];
$this->addElement('select', 'group_by_separator', ts('Separator (grouped contributions)'), $separatorOptions);
- $emailOptions = array(
+ $emailOptions = [
'' => ts('Generate PDFs for printing (only)'),
'email' => ts('Send emails where possible. Generate printable PDFs for contacts who cannot receive email.'),
'both' => ts('Send emails where possible. Generate printable PDFs for all contacts.'),
- );
+ ];
if (CRM_Core_Config::singleton()->doNotAttachPDFReceipt) {
$emailOptions['pdfemail'] = ts('Send emails with an attached PDF where possible. Generate printable PDFs for contacts who cannot receive email.');
$emailOptions['pdfemail_both'] = ts('Send emails with an attached PDF where possible. Generate printable PDFs for all contacts.');
}
- $this->addElement('select', 'email_options', ts('Print and email options'), $emailOptions, array(), " ", FALSE);
-
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ts('Make Thank-you Letters'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addElement('select', 'email_options', ts('Print and email options'), $emailOptions, [], " ", FALSE);
+
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => ts('Make Thank-you Letters'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
diff --git a/CRM/Contribute/Form/Task/PDFLetterCommon.php b/CRM/Contribute/Form/Task/PDFLetterCommon.php
index 87bb38225b22..88a870f7169d 100644
--- a/CRM/Contribute/Form/Task/PDFLetterCommon.php
+++ b/CRM/Contribute/Form/Task/PDFLetterCommon.php
@@ -6,6 +6,20 @@
*/
class CRM_Contribute_Form_Task_PDFLetterCommon extends CRM_Contact_Form_Task_PDFLetterCommon {
+ /**
+ * Build the form object.
+ *
+ * @var CRM_Core_Form $form
+ */
+ public static function buildQuickForm(&$form) {
+ // use contact form as a base
+ CRM_Contact_Form_Task_PDFLetterCommon::buildQuickForm($form);
+
+ // Contribute PDF tasks allow you to email as well, so we need to add email address to those forms
+ $form->add('select', 'from_email_address', ts('From Email Address'), $form->_fromEmails, TRUE);
+ parent::buildQuickForm($form);
+ }
+
/**
* Process the form after the input has been submitted and validated.
*
@@ -18,12 +32,16 @@ public static function postProcess(&$form, $formValues = NULL) {
}
list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($formValues);
$isPDF = FALSE;
- $emailParams = array();
+ $emailParams = [];
if (!empty($formValues['email_options'])) {
$returnProperties['email'] = $returnProperties['on_hold'] = $returnProperties['is_deceased'] = $returnProperties['do_not_email'] = 1;
- $emailParams = array(
- 'subject' => $formValues['subject'],
- );
+ $emailParams = [
+ 'subject' => CRM_Utils_Array::value('subject', $formValues),
+ 'from' => CRM_Utils_Array::value('from_email_address', $formValues),
+ ];
+
+ $emailParams['from'] = CRM_Utils_Mail::formatFromAddress($emailParams['from']);
+
// We need display_name for emailLetter() so add to returnProperties here
$returnProperties['display_name'] = 1;
if (stristr($formValues['email_options'], 'pdfemail')) {
@@ -38,21 +56,22 @@ public static function postProcess(&$form, $formValues = NULL) {
$updateStatus = '';
$task = 'CRM_Contribution_Form_Task_PDFLetterCommon';
$realSeparator = ', ';
- $tableSeparators = array(
+ $tableSeparators = [
'td' => '
',
'tr' => '
',
- );
+ ];
//the original thinking was mutliple options - but we are going with only 2 (comma & td) for now in case
// there are security (& UI) issues we need to think through
if (isset($formValues['group_by_separator'])) {
- if (in_array($formValues['group_by_separator'], array('td', 'tr'))) {
+ if (in_array($formValues['group_by_separator'], ['td', 'tr'])) {
$realSeparator = $tableSeparators[$formValues['group_by_separator']];
}
elseif ($formValues['group_by_separator'] == 'br') {
$realSeparator = " ";
}
}
- $separator = '****~~~~';// a placeholder in case the separator is common in the string - e.g ', '
+ // a placeholder in case the separator is common in the string - e.g ', '
+ $separator = '****~~~~';
$groupBy = $formValues['group_by'];
// skip some contacts ?
@@ -64,8 +83,8 @@ public static function postProcess(&$form, $formValues = NULL) {
$contributionIDs = $form->getVar('_contributionContactIds');
}
list($contributions, $contacts) = self::buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $form->_includesSoftCredits);
- $html = array();
- $contactHtml = $emailedHtml = array();
+ $html = [];
+ $contactHtml = $emailedHtml = [];
foreach ($contributions as $contributionId => $contribution) {
$contact = &$contacts[$contribution['contact_id']];
$grouped = FALSE;
@@ -89,26 +108,22 @@ public static function postProcess(&$form, $formValues = NULL) {
}
$contact['is_sent'][$groupBy][$groupByID] = TRUE;
}
- // update dates (do it for each contribution including grouped recurring contribution)
- //@todo - the 2 calls below bypass all hooks. Using the api would possibly be slower than one call but not than 2
+ // Update receipt/thankyou dates
+ $contributionParams = ['id' => $contributionId];
if ($receipt_update) {
- $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'receipt_date', $nowDate);
- if ($result) {
- $receipts++;
- }
+ $contributionParams['receipt_date'] = $nowDate;
}
if ($thankyou_update) {
- $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'thankyou_date', $nowDate);
- if ($result) {
- $thanks++;
- }
+ $contributionParams['thankyou_date'] = $nowDate;
+ }
+ if ($receipt_update || $thankyou_update) {
+ civicrm_api3('Contribution', 'create', $contributionParams);
+ $receipts = ($receipt_update ? $receipts + 1 : $receipts);
+ $thanks = ($thankyou_update ? $thanks + 1 : $thanks);
}
}
- // This seems silly, but the old behavior was to first check `_cid`
- // and then use the provided `$contactIds`. Probably not even necessary,
- // but difficult to audit.
- $contactIds = $form->_cid ? array($form->_cid) : array_keys($contacts);
+ $contactIds = array_keys($contacts);
self::createActivities($form, $html_message, $contactIds, CRM_Utils_Array::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array::value('campaign_id', $formValues), $contactHtml);
$html = array_diff_key($html, $emailedHtml);
@@ -131,13 +146,13 @@ public static function postProcess(&$form, $formValues = NULL) {
$form->postProcessHook();
if ($emailed) {
- $updateStatus = ts('Receipts have been emailed to %1 contributions.', array(1 => $emailed));
+ $updateStatus = ts('Receipts have been emailed to %1 contributions.', [1 => $emailed]);
}
if ($receipts) {
- $updateStatus = ts('Receipt date has been updated for %1 contributions.', array(1 => $receipts));
+ $updateStatus = ts('Receipt date has been updated for %1 contributions.', [1 => $receipts]);
}
if ($thanks) {
- $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', array(1 => $thanks));
+ $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', [1 => $thanks]);
}
if ($updateStatus) {
@@ -145,7 +160,7 @@ public static function postProcess(&$form, $formValues = NULL) {
}
if (!empty($html)) {
// ie. we have only sent emails - lets no show a white screen
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
}
@@ -160,7 +175,7 @@ public static function postProcess(&$form, $formValues = NULL) {
* @return bool
*/
public static function isValidHTMLWithTableSeparator($tokens, $html) {
- $relevantEntities = array('contribution');
+ $relevantEntities = ['contribution'];
foreach ($relevantEntities as $entity) {
if (isset($tokens[$entity]) && is_array($tokens[$entity])) {
foreach ($tokens[$entity] as $token) {
@@ -177,17 +192,17 @@ public static function isValidHTMLWithTableSeparator($tokens, $html) {
* Check that the token only appears in a table cell. The '
' separator cannot otherwise work
* Calculate the number of times it appears IN the cell & the number of times it appears - should be the same!
*
- * @param $token
- * @param $entity
- * @param $textToSearch
+ * @param string $token
+ * @param string $entity
+ * @param string $textToSearch
*
* @return bool
*/
public static function isHtmlTokenInTableCell($token, $entity, $textToSearch) {
- $tokenToMatch = $entity . '.' . $token;
- $dontCare = array();
- $within = preg_match_all("|
).)*\{' . $tokenToMatch . '\}.*?|si';
+ $within = preg_match_all($pattern, $textToSearch);
+ $total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch);
return ($within == $total);
}
@@ -240,18 +255,18 @@ private static function resolveTokens($html_message, $contact, $contribution, $m
* @return array
*/
public static function buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $isIncludeSoftCredits) {
- $contributions = $contacts = array();
+ $contributions = $contacts = [];
foreach ($contributionIDs as $item => $contributionId) {
// Basic return attributes available to the template.
- $returnValues = array('contact_id', 'total_amount', 'financial_type', 'receive_date', 'contribution_campaign_title');
+ $returnValues = ['contact_id', 'total_amount', 'financial_type', 'receive_date', 'contribution_campaign_title'];
if (!empty($messageToken['contribution'])) {
$returnValues = array_merge($messageToken['contribution'], $returnValues);
}
// retrieve contribution tokens listed in $returnProperties using Contribution.Get API
- $contribution = civicrm_api3('Contribution', 'getsingle', array(
+ $contribution = civicrm_api3('Contribution', 'getsingle', [
'id' => $contributionId,
'return' => $returnValues,
- ));
+ ]);
$contribution['campaign'] = CRM_Utils_Array::value('contribution_campaign_title', $contribution);
$contributions[$contributionId] = $contribution;
@@ -264,9 +279,9 @@ public static function buildContributionArray($groupBy, $contributionIDs, $retur
$contactID = $contribution['contact_id'];
}
if (!isset($contacts[$contactID])) {
- $contacts[$contactID] = array();
+ $contacts[$contactID] = [];
$contacts[$contactID]['contact_aggregate'] = 0;
- $contacts[$contactID]['combined'] = $contacts[$contactID]['contribution_ids'] = array();
+ $contacts[$contactID]['combined'] = $contacts[$contactID]['contribution_ids'] = [];
}
$contacts[$contactID]['contact_aggregate'] += $contribution['total_amount'];
@@ -288,7 +303,7 @@ public static function buildContributionArray($groupBy, $contributionIDs, $retur
// Hooks allow more nuanced smarty usage here.
CRM_Core_Smarty::singleton()->assign('contributions', $contributions);
foreach ($contacts as $contactID => $contact) {
- $tokenResolvedContacts = CRM_Utils_Token::getTokenDetails(array('contact_id' => $contactID),
+ $tokenResolvedContacts = CRM_Utils_Token::getTokenDetails(['contact_id' => $contactID],
$returnProperties,
$skipOnHold,
$skipDeceased,
@@ -298,7 +313,7 @@ public static function buildContributionArray($groupBy, $contributionIDs, $retur
);
$contacts[$contactID] = array_merge($tokenResolvedContacts[0][$contactID], $contact);
}
- return array($contributions, $contacts);
+ return [$contributions, $contacts];
}
/**
@@ -349,29 +364,32 @@ public static function assignCombinedContributionValues($contact, $contributions
*
* @return bool
*/
- public static function emailLetter($contact, $html, $is_pdf, $format = array(), $params = array()) {
+ public static function emailLetter($contact, $html, $is_pdf, $format = [], $params = []) {
try {
if (empty($contact['email'])) {
return FALSE;
}
- $mustBeEmpty = array('do_not_email', 'is_deceased', 'on_hold');
+ $mustBeEmpty = ['do_not_email', 'is_deceased', 'on_hold'];
foreach ($mustBeEmpty as $emptyField) {
if (!empty($contact[$emptyField])) {
return FALSE;
}
}
- $defaults = array(
+ $defaults = [
'toName' => $contact['display_name'],
'toEmail' => $contact['email'],
'text' => '',
'html' => $html,
- );
+ ];
if (empty($params['from'])) {
$emails = CRM_Core_BAO_Email::getFromEmail();
$emails = array_keys($emails);
$defaults['from'] = array_pop($emails);
}
+ else {
+ $defaults['from'] = $params['from'];
+ }
if (!empty($params['subject'])) {
$defaults['subject'] = $params['subject'];
}
@@ -380,7 +398,7 @@ public static function emailLetter($contact, $html, $is_pdf, $format = array(),
}
if ($is_pdf) {
$defaults['html'] = ts('Please see attached');
- $defaults['attachments'] = array(CRM_Utils_Mail::appendPDF('ThankYou.pdf', $html, $format));
+ $defaults['attachments'] = [CRM_Utils_Mail::appendPDF('ThankYou.pdf', $html, $format)];
}
$params = array_merge($defaults);
return CRM_Utils_Mail::send($params);
diff --git a/CRM/Contribute/Form/Task/PickProfile.php b/CRM/Contribute/Form/Task/PickProfile.php
index 3d445df4fc9c..9d45ddafcd21 100644
--- a/CRM/Contribute/Form/Task/PickProfile.php
+++ b/CRM/Contribute/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
_contributionIds) > $this->_maxContributions) {
- CRM_Core_Session::setStatus(ts("The maximum number of contributions you can select for Update multiple contributions is %1. You have selected %2. Please select fewer contributions from your search results and try again.", array(
- 1 => $this->_maxContributions,
- 2 => count($this->_contributionIds),
- )), ts('Update multiple records error'), 'error');
+ CRM_Core_Session::setStatus(ts("The maximum number of contributions you can select for Update multiple contributions is %1. You have selected %2. Please select fewer contributions from your search results and try again.", [
+ 1 => $this->_maxContributions,
+ 2 => count($this->_contributionIds),
+ ]), ts('Update multiple records error'), 'error');
$validate = TRUE;
}
@@ -85,18 +87,18 @@ public function preProcess() {
*/
public function buildQuickForm() {
- $types = array('Contribution');
+ $types = ['Contribution'];
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
if (empty($profiles)) {
- CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple contributions. Navigate to Administer CiviCRM > Customize Data and Screens > CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts('Profile Required'), 'error');
+ CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple contributions. Navigate to Administer CiviCRM > Customize Data and Screens > CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", [1 => $types[0]]), ts('Profile Required'), 'error');
CRM_Utils_System::redirect($this->_userContext);
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
- array(
+ [
'' => ts('- select profile -'),
- ) + $profiles, TRUE
+ ] + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
@@ -105,7 +107,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Contribute_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Contribute_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Contribute/Form/Task/Print.php b/CRM/Contribute/Form/Task/Print.php
index dfb89f892559..58055ce580e5 100644
--- a/CRM/Contribute/Form/Task/Print.php
+++ b/CRM/Contribute/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Contributions'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Contributions'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Contribute/Form/Task/Result.php b/CRM/Contribute/Form/Task/Result.php
index 62259940b8cc..11ff679294d5 100644
--- a/CRM/Contribute/Form/Task/Result.php
+++ b/CRM/Contribute/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Contribute/Form/Task/SearchTaskHookSample.php b/CRM/Contribute/Form/Task/SearchTaskHookSample.php
index 9e01ea3d4832..6c84b5315d19 100644
--- a/CRM/Contribute/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Contribute/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_contributionIds);
@@ -60,12 +60,12 @@ public function preProcess() {
);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'source' => $dao->source,
'receive_date' => $dao->receive_date,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -74,14 +74,13 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Contribute/Form/Task/Status.php b/CRM/Contribute/Form/Task/Status.php
index a3535e5cbefe..348ed223870d 100644
--- a/CRM/Contribute/Form/Task/Status.php
+++ b/CRM/Contribute/Form/Task/Status.php
@@ -1,9 +1,9 @@
_contributionIds = array($id);
+ $this->_contributionIds = [$id];
$this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
$this->_single = TRUE;
$this->assign('totalSelectedContributions', 1);
@@ -115,11 +115,11 @@ public function buildQuickForm() {
);
// build a row for each contribution id
- $this->_rows = array();
+ $this->_rows = [];
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
- $defaults = array();
- $now = date("m/d/Y");
- $paidByOptions = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument();
+ $defaults = [];
+ $now = date("Y-m-d");
+ $paidByOptions = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument();
while ($dao->fetch()) {
$row['contact_id'] = $dao->contact_id;
@@ -131,7 +131,7 @@ public function buildQuickForm() {
$this->addRule("trxn_id_{$row['contribution_id']}",
ts('This Transaction ID already exists in the database. Include the account number for checks.'),
'objectExists',
- array('CRM_Contribute_DAO_Contribution', $dao->contribution_id, 'trxn_id')
+ ['CRM_Contribute_DAO_Contribution', $dao->contribution_id, 'trxn_id']
);
$row['fee_amount'] = &$this->add('text', "fee_amount_{$row['contribution_id']}", ts('Fee Amount'),
@@ -140,9 +140,7 @@ public function buildQuickForm() {
$this->addRule("fee_amount_{$row['contribution_id']}", ts('Please enter a valid amount.'), 'money');
$defaults["fee_amount_{$row['contribution_id']}"] = 0.0;
- $row['trxn_date'] = $this->addDate("trxn_date_{$row['contribution_id']}", FALSE,
- ts('Receipt Date'), array('formatType' => 'activityDate')
- );
+ $row['trxn_date'] = $this->add('datepicker', "trxn_date_{$row['contribution_id']}", ts('Transaction Date'), [], FALSE, ['time' => FALSE]);
$defaults["trxn_date_{$row['contribution_id']}"] = $now;
$this->add("text", "check_number_{$row['contribution_id']}", ts('Check Number'));
@@ -156,20 +154,19 @@ public function buildQuickForm() {
$this->assign_by_ref('rows', $this->_rows);
$this->setDefaults($defaults);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Update Pending Status'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $this->addFormRule(array('CRM_Contribute_Form_Task_Status', 'formRule'));
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Update Pending Status'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFormRule(['CRM_Contribute_Form_Task_Status', 'formRule']);
}
/**
@@ -182,7 +179,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
- $seen = $errors = array();
+ $seen = $errors = [];
foreach ($fields as $name => $value) {
if (strpos($name, 'trxn_id_') !== FALSE) {
if ($fields[$name]) {
@@ -196,7 +193,7 @@ public static function formRule($fields) {
if ((strpos($name, 'check_number_') !== FALSE) && $value) {
$contribID = substr($name, 13);
- if ($fields["payment_instrument_id_{$contribID}"] != CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name')) {
+ if ($fields["payment_instrument_id_{$contribID}"] != CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Check')) {
$errors["payment_instrument_id_{$contribID}"] = ts("Payment Method should be Check when a check number is entered for a contribution.");
}
}
@@ -239,7 +236,7 @@ public static function processForm($form, $params) {
// for each contribution id, we just call the baseIPN stuff
foreach ($form->_rows as $row) {
- $input = $ids = $objects = array();
+ $input = $ids = $objects = [];
$input['component'] = $details[$row['contribution_id']]['component'];
$ids['contact'] = $row['contact_id'];
@@ -294,7 +291,7 @@ public static function processForm($form, $params) {
else {
$input['trxn_id'] = $contribution->invoice_id;
}
- $input['trxn_date'] = CRM_Utils_Date::processDate($params["trxn_date_{$row['contribution_id']}"], date('H:i:s'));
+ $input['trxn_date'] = $params["trxn_date_{$row['contribution_id']}"] . ' ' . date('H:i:s');
// @todo calling baseIPN like this is a pattern in it's last gasps. Call contribute.completetransaction api.
$baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
@@ -305,11 +302,14 @@ public static function processForm($form, $params) {
}
/**
- * @param $contributionIDs
+ * @param string $contributionIDs
*
* @return array
*/
public static function &getDetails($contributionIDs) {
+ if (empty($contributionIDs)) {
+ return [];
+ }
$query = "
SELECT c.id as contribution_id,
c.contact_id as contact_id ,
@@ -322,18 +322,17 @@ public static function &getDetails($contributionIDs) {
LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
WHERE c.id IN ( $contributionIDs )";
- $rows = array();
+ $rows = [];
$dao = CRM_Core_DAO::executeQuery($query,
CRM_Core_DAO::$_nullArray
);
- $rows = array();
while ($dao->fetch()) {
$rows[$dao->contribution_id]['component'] = $dao->participant_id ? 'event' : 'contribute';
$rows[$dao->contribution_id]['contact'] = $dao->contact_id;
if ($dao->membership_id) {
if (!array_key_exists('membership', $rows[$dao->contribution_id])) {
- $rows[$dao->contribution_id]['membership'] = array();
+ $rows[$dao->contribution_id]['membership'] = [];
}
$rows[$dao->contribution_id]['membership'][] = $dao->membership_id;
}
diff --git a/CRM/Contribute/Form/UpdateBilling.php b/CRM/Contribute/Form/UpdateBilling.php
index 97d358859b4d..5a20bd0ef33f 100644
--- a/CRM/Contribute/Form/UpdateBilling.php
+++ b/CRM/Contribute/Form/UpdateBilling.php
@@ -1,9 +1,9 @@
_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE);
- $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
+ parent::preProcess();
if ($this->_crid) {
- $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
- $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
// Are we cancelling a recurring contribution that is linked to an auto-renew membership?
@@ -67,7 +57,6 @@ public function preProcess() {
}
}
- $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
if ($this->_coid) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
$this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
@@ -88,14 +77,13 @@ public function preProcess() {
CRM_Core_Error::fatal('Required information missing.');
}
if (!CRM_Core_Permission::check('edit contributions')) {
- $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
- if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
- CRM_Core_Error::fatal(ts('You do not have permission to cancel subscription.'));
+ if ($this->_subscriptionDetails->contact_id != $this->getContactID()) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to cancel subscription.'));
}
$this->_selfService = TRUE;
}
- if (!$this->_paymentProcessor['object']->isSupported('updateSubscriptionBillingInfo')) {
+ if (!$this->_paymentProcessor['object']->supports('updateSubscriptionBillingInfo')) {
CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.",
array(1 => $this->_paymentProcessor['object']->_processorName)
));
@@ -178,17 +166,16 @@ public function buildQuickForm() {
}
$this->addButtons(array(
- array(
- 'type' => $type,
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ array(
+ 'type' => $type,
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ),
+ array(
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ),
+ ));
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, TRUE, TRUE);
$this->addFormRule(array('CRM_Contribute_Form_UpdateBilling', 'formRule'), $this);
@@ -335,17 +322,15 @@ public function postProcess() {
$activityParams = array(
'source_contact_id' => $this->_subscriptionDetails->contact_id,
- 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
- 'Update Recurring Contribution Billing Details',
- 'name'
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey(
+ 'CRM_Activity_BAO_Activity',
+ 'activity_type_id',
+ 'Update Recurring Contribution Billing Details'
),
'subject' => ts('Recurring Contribution Billing Details Updated'),
'details' => $message,
'activity_date_time' => date('YmdHis'),
- 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
- 'Completed',
- 'name'
- ),
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
);
$session = CRM_Core_Session::singleton();
$cid = $session->get('userID');
diff --git a/CRM/Contribute/Form/UpdateSubscription.php b/CRM/Contribute/Form/UpdateSubscription.php
index 1baf49654bd5..162748d9cf8b 100644
--- a/CRM/Contribute/Form/UpdateSubscription.php
+++ b/CRM/Contribute/Form/UpdateSubscription.php
@@ -1,9 +1,9 @@
setAction(CRM_Core_Action::UPDATE);
- $this->contributionRecurID = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
if ($this->contributionRecurID) {
- $this->_paymentProcessor = CRM_Contribute_BAO_ContributionRecur::getPaymentProcessor($this->contributionRecurID);
- if (!$this->_paymentProcessor) {
- CRM_Core_Error::statusBounce(ts('There is no valid processor for this subscription so it cannot be edited.'));
- }
- $this->_paymentProcessorObj = $this->_paymentProcessor['object'];
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->contributionRecurID);
}
- $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
if ($this->_coid) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
+ // @todo test & replace with $this->_paymentProcessorObj = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
$this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
$this->contributionRecurID = $this->_subscriptionDetails->recur_id;
@@ -105,12 +91,21 @@ public function preProcess() {
}
if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
- CRM_Core_Error::statusBounce(ts('You cannot update the subscription.'));
+ // Add Membership details to form
+ $membership = civicrm_api3('Membership', 'get', [
+ 'contribution_recur_id' => $this->contributionRecurID,
+ ]);
+ if (!empty($membership['count'])) {
+ $membershipDetails = reset($membership['values']);
+ $values['membership_id'] = $membershipDetails['id'];
+ $values['membership_name'] = $membershipDetails['membership_name'];
+ }
+ $this->assign('recurMembership', $values);
+ $this->assign('contactId', $this->_subscriptionDetails->contact_id);
}
if (!CRM_Core_Permission::check('edit contributions')) {
- $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
- if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
+ if ($this->_subscriptionDetails->contact_id != $this->getContactID()) {
CRM_Core_Error::statusBounce(ts('You do not have permission to update subscription.'));
}
$this->_selfService = TRUE;
@@ -127,17 +122,21 @@ public function preProcess() {
else {
$this->assign('changeHelpText', $changeHelpText);
}
- $alreadyHardCodedFields = array('amount', 'installments');
+ $alreadyHardCodedFields = ['amount', 'installments'];
foreach ($this->editableScheduleFields as $editableScheduleField) {
if (!in_array($editableScheduleField, $alreadyHardCodedFields)) {
- $this->addField($editableScheduleField, array('entity' => 'ContributionRecur'));
+ $this->addField($editableScheduleField, ['entity' => 'ContributionRecur'], FALSE, FALSE);
}
}
+ // when custom data is included in this page
+ if (!empty($_POST['hidden_custom'])) {
+ CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'ContributionRecur', $this->contributionRecurID);
+ CRM_Custom_Form_CustomData::buildQuickForm($this);
+ CRM_Custom_Form_CustomData::setDefaultValues($this);
+ }
+
$this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
- $this->assign('paymentProcessor', $this->_paymentProcessor);
- $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
- $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
if ($this->_subscriptionDetails->contact_id) {
list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
@@ -155,14 +154,14 @@ public function preProcess() {
* Note that in edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
$this->_defaults['amount'] = $this->_subscriptionDetails->amount;
$this->_defaults['installments'] = $this->_subscriptionDetails->installments;
$this->_defaults['campaign_id'] = $this->_subscriptionDetails->campaign_id;
$this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
$this->_defaults['is_notify'] = 1;
foreach ($this->editableScheduleFields as $field) {
- $this->_defaults[$field] = $this->_subscriptionDetails->$field;
+ $this->_defaults[$field] = isset($this->_subscriptionDetails->$field) ? $this->_subscriptionDetails->$field : NULL;
}
return $this->_defaults;
@@ -173,16 +172,16 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
// CRM-16398: If current recurring contribution got > 1 lineitems then make amount field readonly
- $amtAttr = array('size' => 20);
+ $amtAttr = ['size' => 20];
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_coid);
if (count($lineItems) > 1) {
- $amtAttr += array('readonly' => TRUE);
+ $amtAttr += ['readonly' => TRUE];
}
$this->addMoney('amount', ts('Recurring Contribution Amount'), TRUE, $amtAttr,
TRUE, 'currency', $this->_subscriptionDetails->currency, TRUE
);
- $this->add('text', 'installments', ts('Number of Installments'), array('size' => 20), FALSE);
+ $this->add('text', 'installments', ts('Number of Installments'), ['size' => 20], FALSE);
if ($this->_donorEmail) {
$this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
@@ -193,27 +192,30 @@ public function buildQuickForm() {
}
if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($this->contributionRecurID)) {
- $this->addEntityRef('financial_type_id', ts('Financial Type'), array('entity' => 'FinancialType'), !$this->_selfService);
+ $this->addEntityRef('financial_type_id', ts('Financial Type'), ['entity' => 'FinancialType'], !$this->_selfService);
}
+ // Add custom data
+ $this->assign('customDataType', 'ContributionRecur');
+ $this->assign('entityID', $this->contributionRecurID);
+
$type = 'next';
if ($this->_selfService) {
$type = 'submit';
}
// define the buttons
- $this->addButtons(array(
- array(
- 'type' => $type,
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $type,
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -234,7 +236,7 @@ public function postProcess() {
$params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
$updateSubscription = TRUE;
- if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
+ if ($this->_paymentProcessorObj->supports('changeSubscriptionAmount')) {
$updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
}
if (is_a($updateSubscription, 'CRM_Core_Error')) {
@@ -244,15 +246,17 @@ public function postProcess() {
$msgType = 'error';
}
elseif ($updateSubscription) {
+ // Handle custom data
+ $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->contributionRecurID, 'ContributionRecur');
// save the changes
- $result = CRM_Contribute_BAO_ContributionRecur::add($params);
+ CRM_Contribute_BAO_ContributionRecur::add($params);
$status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
- array(
+ [
1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
2 => $this->_subscriptionDetails->frequency_interval,
3 => $this->_subscriptionDetails->frequency_unit,
4 => $params['installments'],
- )
+ ]
);
$msgTitle = ts('Update Success');
@@ -262,10 +266,10 @@ public function postProcess() {
if ($this->_subscriptionDetails->amount != $params['amount']) {
$message .= " " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.",
- array(
+ [
1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency),
2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
- )) . ' ';
+ ]) . ' ';
if ($this->_subscriptionDetails->amount < $params['amount']) {
$msg = ts('Recurring Contribution Updated - increased installment amount');
}
@@ -275,26 +279,21 @@ public function postProcess() {
}
if ($this->_subscriptionDetails->installments != $params['installments']) {
- $message .= " " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(
- 1 => $this->_subscriptionDetails->installments,
- 2 => $params['installments'],
- )) . ' ';
+ $message .= " " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", [
+ 1 => $this->_subscriptionDetails->installments,
+ 2 => $params['installments'],
+ ]) . ' ';
}
- $activityParams = array(
+ $activityParams = [
'source_contact_id' => $contactID,
- 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
- 'Update Recurring Contribution',
- 'name'
- ),
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Update Recurring Contribution'),
'subject' => $msg,
'details' => $message,
'activity_date_time' => date('YmdHis'),
- 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
- 'Completed',
- 'name'
- ),
- );
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
+ ];
+
$session = CRM_Core_Session::singleton();
$cid = $session->get('userID');
@@ -308,11 +307,11 @@ public function postProcess() {
// send notification
if ($this->_subscriptionDetails->contribution_page_id) {
CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
- $this->_subscriptionDetails->contribution_page_id, $value, array(
+ $this->_subscriptionDetails->contribution_page_id, $value, [
'title',
'receipt_from_name',
'receipt_from_email',
- )
+ ]
);
$receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
}
@@ -323,17 +322,17 @@ public function postProcess() {
list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
- $tplParams = array(
+ $tplParams = [
'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
'amount' => CRM_Utils_Money::format($params['amount']),
'installments' => $params['installments'],
- );
+ ];
- $tplParams['contact'] = array('display_name' => $donorDisplayName);
+ $tplParams['contact'] = ['display_name' => $donorDisplayName];
$tplParams['receipt_from_email'] = $receiptFrom;
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'contribution_recurring_edit',
'contactId' => $contactID,
@@ -343,7 +342,7 @@ public function postProcess() {
'from' => $receiptFrom,
'toName' => $donorDisplayName,
'toEmail' => $donorEmail,
- );
+ ];
list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
@@ -363,11 +362,4 @@ public function postProcess() {
}
}
- /**
- * Explicitly declare the form context.
- */
- public function getDefaultContext() {
- return 'create';
- }
-
}
diff --git a/CRM/Contribute/Import/Controller.php b/CRM/Contribute/Import/Controller.php
index 32eef8a8b3be..7860644926cb 100644
--- a/CRM/Contribute/Import/Controller.php
+++ b/CRM/Contribute/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Contribute/Import/Field.php b/CRM/Contribute/Import/Field.php
index 686440fc1538..969441ef83e9 100644
--- a/CRM/Contribute/Import/Field.php
+++ b/CRM/Contribute/Import/Field.php
@@ -1,9 +1,9 @@
_value);
case 'trxn_id':
- static $seenTrxnIds = array();
+ static $seenTrxnIds = [];
if (in_array($this->_value, $seenTrxnIds)) {
return FALSE;
}
diff --git a/CRM/Contribute/Import/Form/DataSource.php b/CRM/Contribute/Import/Form/DataSource.php
index 6338597b5c1a..ff0ee51e5479 100644
--- a/CRM/Contribute/Import/Form/DataSource.php
+++ b/CRM/Contribute/Import/Form/DataSource.php
@@ -1,9 +1,9 @@
createElement('radio',
NULL, NULL, ts('Insert new contributions'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -57,9 +57,9 @@ public function buildQuickForm() {
ts('Import mode')
);
- $this->setDefaults(array('onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP));
+ $this->setDefaults(['onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP]);
- $this->addElement('submit', 'loadMapping', ts('Load Mapping'), NULL, array('onclick' => 'checkSelect()'));
+ $this->addElement('submit', 'loadMapping', ts('Load Mapping'), NULL, ['onclick' => 'checkSelect()']);
$this->addContactTypeSelector();
}
@@ -68,12 +68,12 @@ public function buildQuickForm() {
* Process the uploaded file.
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
- ));
+ ]);
$this->submitFileForMapping('CRM_Contribute_Import_Parser_Contribution');
}
diff --git a/CRM/Contribute/Import/Form/MapField.php b/CRM/Contribute/Import/Form/MapField.php
index 8421712d4d21..e0f58c436e77 100644
--- a/CRM/Contribute/Import/Form/MapField.php
+++ b/CRM/Contribute/Import/Form/MapField.php
@@ -1,9 +1,9 @@
assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
- /* if we had a column header to skip, stash it for later */
+ // If we had a column header to skip, stash it for later
$this->_columnHeaders = $this->_dataValues[0];
}
else {
$this->assign('rowDisplayCount', 2);
}
- $highlightedFields = array('financial_type', 'total_amount');
+ $highlightedFields = ['financial_type', 'total_amount'];
//CRM-2219 removing other required fields since for updation only
//invoice id or trxn id or contribution id is required.
if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
- $remove = array('contribution_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
+ $remove = [
+ 'contribution_contact_id',
+ 'email',
+ 'first_name',
+ 'last_name',
+ 'external_identifier',
+ ];
foreach ($remove as $value) {
unset($this->_mapperFields[$value]);
}
//modify field title only for update mode. CRM-3245
- foreach (array(
- 'contribution_id',
- 'invoice_id',
- 'trxn_id',
- ) as $key) {
+ foreach ([
+ 'contribution_id',
+ 'invoice_id',
+ 'trxn_id',
+ ] as $key) {
$this->_mapperFields[$key] .= ' (match to contribution record)';
$highlightedFields[] = $key;
}
}
elseif ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
unset($this->_mapperFields['contribution_id']);
- $highlightedFieldsArray = array(
+ $highlightedFieldsArray = [
'contribution_contact_id',
'email',
'first_name',
'last_name',
'external_identifier',
- );
+ ];
foreach ($highlightedFieldsArray as $name) {
$highlightedFields[] = $name;
}
@@ -125,8 +130,8 @@ public function buildQuickForm() {
//mapping is to be loaded from database
- $params = array('id' => $savedMapping);
- $temp = array();
+ $params = ['id' => $savedMapping];
+ $temp = [];
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$this->assign('loadedMapping', $mappingDetails->name);
@@ -150,13 +155,16 @@ public function buildQuickForm() {
$this->add('text', 'saveMappingDesc', ts('Description'));
}
- $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
+ $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
- $this->addFormRule(array('CRM_Contribute_Import_Form_MapField', 'formRule'), $this);
+ $this->addFormRule([
+ 'CRM_Contribute_Import_Form_MapField',
+ 'formRule',
+ ], $this);
//-------- end of saved mapping stuff ---------
- $defaults = array();
+ $defaults = [];
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
$headerPatterns = $this->get('headerPatterns');
@@ -191,7 +199,7 @@ public function buildQuickForm() {
$warning = 0;
for ($i = 0; $i < $this->_columnCount; $i++) {
- $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
+ $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
$jsSet = FALSE;
if ($this->get('savedMapping')) {
if (isset($mappingName[$i])) {
@@ -207,16 +215,16 @@ public function buildQuickForm() {
$js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
- $defaults["mapper[$i]"] = array(
+ $defaults["mapper[$i]"] = [
CRM_Utils_Array::value(0, $mappingHeader),
($softField) ? $softField : "",
(isset($locationId)) ? $locationId : "",
(isset($phoneType)) ? $phoneType : "",
- );
+ ];
$jsSet = TRUE;
}
else {
- $defaults["mapper[$i]"] = array();
+ $defaults["mapper[$i]"] = [];
}
if (!$jsSet) {
for ($k = 1; $k < 4; $k++) {
@@ -229,10 +237,10 @@ public function buildQuickForm() {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
if ($hasHeaders) {
- $defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
+ $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns)];
}
else {
- $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
+ $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
}
}
//end of load mapping
@@ -248,28 +256,25 @@ public function buildQuickForm() {
}
else {
// Infer the default from the column names if we have them
- $defaults["mapper[$i]"] = array(
- $this->defaultFromHeader($this->_columnHeaders[$i],
- $headerPatterns
- ),
+ $defaults["mapper[$i]"] = [
+ $this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns),
0,
- );
+ ];
}
}
else {
// Otherwise guess the default from the form of the data
- $defaults["mapper[$i]"] = array(
+ $defaults["mapper[$i]"] = [
$this->defaultFromData($dataPatterns, $i),
- // $defaultLocationType->id
0,
- );
+ ];
}
if (!empty($mapperKeysValues) && $mapperKeysValues[$i][0] == 'soft_credit') {
$js .= "cj('#mapper_" . $i . "_1').val($mapperKeysValues[$i][1]);\n";
$js .= "cj('#mapper_" . $i . "_2').val($mapperKeysValues[$i][2]);\n";
}
}
- $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
+ $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
}
$js .= "\n";
$this->assign('initHideBoxes', $js);
@@ -291,23 +296,22 @@ public function buildQuickForm() {
$this->setDefaults($defaults);
- $this->addButtons(array(
- array(
- 'type' => 'back',
- 'name' => ts('Previous'),
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'back',
+ 'name' => ts('Previous'),
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -323,25 +327,25 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
$fieldMessage = NULL;
$contactORContributionId = $self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE ? 'contribution_id' : 'contribution_contact_id';
if (!array_key_exists('savedMapping', $fields)) {
- $importKeys = array();
+ $importKeys = [];
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
$contactTypeId = $self->get('contactType');
- $contactTypes = array(
+ $contactTypes = [
CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual',
CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household',
CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization',
- );
- $params = array(
+ ];
+ $params = [
'used' => 'Unsupervised',
'contact_type' => isset($contactTypes[$contactTypeId]) ? $contactTypes[$contactTypeId] : '',
- );
+ ];
list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
$weightSum = 0;
foreach ($importKeys as $key => $val) {
@@ -363,11 +367,11 @@ public static function formRule($fields, $files, $self) {
}
// FIXME: should use the schema titles, not redeclare them
- $requiredFields = array(
+ $requiredFields = [
$contactORContributionId == 'contribution_id' ? 'contribution_id' : 'contribution_contact_id' => $contactORContributionId == 'contribution_id' ? ts('Contribution ID') : ts('Contact ID'),
'total_amount' => ts('Total Amount'),
'financial_type' => ts('Financial Type'),
- );
+ ];
foreach ($requiredFields as $field => $title) {
if (!in_array($field, $importKeys)) {
@@ -378,9 +382,9 @@ public static function formRule($fields, $files, $self) {
if (!($weightSum >= $threshold || in_array('external_identifier', $importKeys)) &&
$self->_onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE
) {
- $errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
- 1 => $threshold,
- )) . ' ';
+ $errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [
+ 1 => $threshold,
+ ]) . ' ';
}
elseif ($self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE &&
!(in_array('invoice_id', $importKeys) || in_array('trxn_id', $importKeys) ||
@@ -391,9 +395,9 @@ public static function formRule($fields, $files, $self) {
}
}
else {
- $errors['_qf_default'] .= ts('Missing required field: %1', array(
- 1 => $title,
- )) . ' ';
+ $errors['_qf_default'] .= ts('Missing required field: %1', [
+ 1 => $title,
+ ]) . ' ';
}
}
}
@@ -403,7 +407,12 @@ public static function formRule($fields, $files, $self) {
$atleastOne = FALSE;
foreach ($self->_mapperFields as $key => $field) {
if (in_array($key, $importKeys) &&
- !in_array($key, array('doNotImport', 'contribution_id', 'invoice_id', 'trxn_id'))
+ !in_array($key, [
+ 'doNotImport',
+ 'contribution_id',
+ 'invoice_id',
+ 'trxn_id',
+ ])
) {
$atleastOne = TRUE;
break;
@@ -421,8 +430,7 @@ public static function formRule($fields, $files, $self) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Contribution', 'name');
- if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
+ if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contribution'))) {
$errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
}
}
@@ -460,7 +468,7 @@ public function postProcess() {
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
- $mapper = $mapperKeys = $mapperKeysMain = $mapperSoftCredit = $softCreditFields = $mapperPhoneType = $mapperSoftCreditType = array();
+ $mapper = $mapperKeys = $mapperKeysMain = $mapperSoftCredit = $softCreditFields = $mapperPhoneType = $mapperSoftCreditType = [];
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
@@ -478,10 +486,10 @@ public function postProcess() {
else {
$softCreditFields[$i] = $mapperSoftCredit[$i];
}
- $mapperSoftCreditType[$i] = array(
+ $mapperSoftCreditType[$i] = [
'value' => isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : '',
'label' => isset($softCreditTypes[$mapperKeys[$i][2]]) ? $softCreditTypes[$mapperKeys[$i][2]] : '',
- );
+ ];
}
else {
$mapperSoftCredit[$i] = $softCreditFields[$i] = $mapperSoftCreditType[$i] = NULL;
@@ -501,7 +509,7 @@ public function postProcess() {
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
- $mappingFieldsId = array();
+ $mappingFieldsId = [];
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
@@ -523,14 +531,11 @@ public function postProcess() {
//Saving Mapping Details and Records
if (!empty($params['saveMapping'])) {
- $mappingParams = array(
+ $mappingParams = [
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import Contribution',
- 'name'
- ),
- );
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contribution'),
+ ];
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
diff --git a/CRM/Contribute/Import/Form/Preview.php b/CRM/Contribute/Import/Form/Preview.php
index c5bdf920c93a..074c06b6d5f6 100644
--- a/CRM/Contribute/Import/Form/Preview.php
+++ b/CRM/Contribute/Import/Form/Preview.php
@@ -1,9 +1,9 @@
set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'softCreditFields',
'mapperSoftCreditType',
@@ -97,7 +97,8 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
+ $this->setStatusUrl();
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -117,9 +118,9 @@ public function postProcess() {
$mapperSoftCreditType = $this->get('mapperSoftCreditType');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
- $mapperSoftCredit = array();
- $mapperPhoneType = array();
+ $mapperKeys = [];
+ $mapperSoftCredit = [];
+ $mapperPhoneType = [];
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
@@ -137,7 +138,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -148,7 +149,9 @@ public function postProcess() {
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$this->get('contactType'),
- $onDuplicate
+ $onDuplicate,
+ $this->get('statusID'),
+ $this->get('totalRowCount')
);
// Add all the necessary variables to the form.
@@ -158,7 +161,7 @@ public function postProcess() {
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Contribute/Import/Form/Summary.php b/CRM/Contribute/Import/Form/Summary.php
index d0b20cd5af37..ddd0222305d4 100644
--- a/CRM/Contribute/Import/Form/Summary.php
+++ b/CRM/Contribute/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -119,7 +119,7 @@ public function preProcess() {
'invalidPledgePaymentRowCount',
'downloadPledgePaymentErrorRecordsUrl',
'downloadSoftCreditErrorRecordsUrl',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Contribute/Import/Parser.php b/CRM/Contribute/Import/Parser.php
index 46b841f259bf..939eef3d8018 100644
--- a/CRM/Contribute/Import/Parser.php
+++ b/CRM/Contribute/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = $this->_invalidSoftCreditRowCount = $this->_invalidPledgePaymentRowCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
- $this->_pledgePaymentErrors = array();
- $this->_softCreditErrors = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
+ $this->_pledgePaymentErrors = [];
+ $this->_softCreditErrors = [];
+ if ($statusID) {
+ $this->progressImport($statusID);
+ $startTimestamp = $currTimestamp = $prevTimestamp = time();
+ }
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
@@ -215,6 +235,9 @@ public function run(
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
+ if ($statusID && (($this->_lineCount % 50) == 0)) {
+ $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
+ }
}
else {
$returnCode = self::ERROR;
@@ -256,38 +279,32 @@ public function run(
if ($returnCode == self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode == self::PLEDGE_PAYMENT_ERROR) {
$this->_invalidPledgePaymentRowCount++;
- if ($this->_invalidPledgePaymentRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_pledgePaymentErrors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_pledgePaymentErrors[] = $values;
}
if ($returnCode == self::SOFT_CREDIT_ERROR) {
$this->_invalidSoftCreditRowCount++;
- if ($this->_invalidSoftCreditRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_softCreditErrors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_softCreditErrors[] = $values;
}
if ($returnCode == self::CONFLICT) {
@@ -342,57 +359,47 @@ public function run(
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_invalidPledgePaymentRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_pledgePaymentErrorsFileName = self::errorFileName(self::PLEDGE_PAYMENT_ERROR);
self::exportCSV($this->_pledgePaymentErrorsFileName, $headers, $this->_pledgePaymentErrors);
}
if ($this->_invalidSoftCreditRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_softCreditErrorsFileName = self::errorFileName(self::SOFT_CREDIT_ERROR);
self::exportCSV($this->_softCreditErrorsFileName, $headers, $this->_softCreditErrors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('View Contribution URL'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('View Contribution URL'),
+ ], $customHeaders);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
@@ -444,12 +451,12 @@ public function setActiveFieldSoftCreditType($elements) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)) {
if (isset($this->_activeFields[$i]->_softCreditField)) {
if (!isset($params[$this->_activeFields[$i]->_name])) {
- $params[$this->_activeFields[$i]->_name] = array();
+ $params[$this->_activeFields[$i]->_name] = [];
}
$params[$this->_activeFields[$i]->_name][$i][$this->_activeFields[$i]->_softCreditField] = $this->_activeFields[$i]->_value;
if (isset($this->_activeFields[$i]->_softCreditType)) {
@@ -565,7 +572,7 @@ public function set($store, $mode = self::MODE_SUMMARY) {
* @param array $data
*/
public static function exportCSV($fileName, $header, $data) {
- $output = array();
+ $output = [];
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
diff --git a/CRM/Contribute/Import/Parser/Contribution.php b/CRM/Contribute/Import/Parser/Contribution.php
index 05736a628028..6ee91c40ef6d 100644
--- a/CRM/Contribute/Import/Parser/Contribution.php
+++ b/CRM/Contribute/Import/Parser/Contribution.php
@@ -1,9 +1,9 @@
_contactType, FALSE);
$fields = array_merge($fields,
- array(
- 'soft_credit' => array(
+ [
+ 'soft_credit' => [
'title' => ts('Soft Credit'),
'softCredit' => TRUE,
'headerPattern' => '/Soft Credit/i',
- ),
- )
+ ],
+ ]
);
// add pledge fields only if its is enabled
if (CRM_Core_Permission::access('CiviPledge')) {
- $pledgeFields = array(
- 'pledge_payment' => array(
+ $pledgeFields = [
+ 'pledge_payment' => [
'title' => ts('Pledge Payment'),
'headerPattern' => '/Pledge Payment/i',
- ),
- 'pledge_id' => array(
+ ],
+ 'pledge_id' => [
'title' => ts('Pledge ID'),
'headerPattern' => '/Pledge ID/i',
- ),
- );
+ ],
+ ];
$fields = array_merge($fields, $pledgeFields);
}
@@ -105,7 +105,7 @@ public function init() {
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newContributions = array();
+ $this->_newContributions = [];
$this->setActiveFields($this->_mapperKeys);
$this->setActiveFieldSoftCredit($this->_mapperSoftCredit);
@@ -177,49 +177,7 @@ public function summary(&$values) {
$errorMessage = NULL;
//for date-Formats
- $session = CRM_Core_Session::singleton();
- $dateType = $session->get('dateTypes');
- foreach ($params as $key => $val) {
- if ($val) {
- switch ($key) {
- case 'receive_date':
- if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
- $params[$key] = $dateValue;
- }
- else {
- CRM_Contact_Import_Parser_Contact::addToErrorMsg('Receive Date', $errorMessage);
- }
- break;
-
- case 'cancel_date':
- if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
- $params[$key] = $dateValue;
- }
- else {
- CRM_Contact_Import_Parser_Contact::addToErrorMsg('Cancel Date', $errorMessage);
- }
- break;
-
- case 'receipt_date':
- if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
- $params[$key] = $dateValue;
- }
- else {
- CRM_Contact_Import_Parser_Contact::addToErrorMsg('Receipt date', $errorMessage);
- }
- break;
-
- case 'thankyou_date':
- if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
- $params[$key] = $dateValue;
- }
- else {
- CRM_Contact_Import_Parser_Contact::addToErrorMsg('Thankyou Date', $errorMessage);
- }
- break;
- }
- }
- }
+ $errorMessage = implode('; ', $this->formatDateFields($params));
//date-Format part ends
$params['contact_type'] = 'Contribution';
@@ -256,49 +214,13 @@ public function import($onDuplicate, &$values) {
}
$params = &$this->getActiveFieldParams();
- $formatted = array('version' => 3);
-
- // don't add to recent items, CRM-4399
- $formatted['skipRecentView'] = TRUE;
-
- //for date-Formats
- $session = CRM_Core_Session::singleton();
- $dateType = $session->get('dateTypes');
-
- $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
- $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
+ $formatted = ['version' => 3, 'skipRecentView' => TRUE, 'skipCleanMoney' => FALSE];
//CRM-10994
if (isset($params['total_amount']) && $params['total_amount'] == 0) {
$params['total_amount'] = '0.00';
}
- foreach ($params as $key => $val) {
- if ($val) {
- switch ($key) {
- case 'receive_date':
- case 'cancel_date':
- case 'receipt_date':
- case 'thankyou_date':
- $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType);
- break;
-
- case 'pledge_payment':
- $params[$key] = CRM_Utils_String::strtobool($val);
- break;
-
- }
- if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
- if ($customFields[$customFieldID]['data_type'] == 'Date') {
- CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
- unset($params[$key]);
- }
- elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
- $params[$key] = CRM_Utils_String::strtoboolstr($val);
- }
- }
- }
- }
- //date-Format part ends
+ $this->formatInput($params);
static $indieFields = NULL;
if ($indieFields == NULL) {
@@ -306,7 +228,7 @@ public function import($onDuplicate, &$values) {
$indieFields = $tempIndieFields;
}
- $paramValues = array();
+ $paramValues = [];
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
@@ -360,11 +282,11 @@ public function import($onDuplicate, &$values) {
//fix for CRM-2219 - Update Contribution
// onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) {
- $dupeIds = array(
+ $dupeIds = [
'id' => CRM_Utils_Array::value('contribution_id', $paramValues),
'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues),
'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues),
- );
+ ];
$ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
@@ -376,7 +298,7 @@ public function import($onDuplicate, &$values) {
);
//process note
if (!empty($paramValues['note'])) {
- $noteID = array();
+ $noteID = [];
$contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
$daoNote = new CRM_Core_BAO_Note();
$daoNote->entity_table = 'civicrm_contribution';
@@ -385,32 +307,32 @@ public function import($onDuplicate, &$values) {
$noteID['id'] = $daoNote->id;
}
- $noteParams = array(
+ $noteParams = [
'entity_table' => 'civicrm_contribution',
'note' => $paramValues['note'],
'entity_id' => $ids['contribution'],
'contact_id' => $contactID,
- );
+ ];
CRM_Core_BAO_Note::add($noteParams, $noteID);
unset($formatted['note']);
}
//need to check existing soft credit contribution, CRM-3968
if (!empty($formatted['soft_credit'])) {
- $dupeSoftCredit = array(
+ $dupeSoftCredit = [
'contact_id' => $formatted['soft_credit'],
'contribution_id' => $ids['contribution'],
- );
+ ];
//Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
$existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']);
if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) {
foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) {
if (!empty($existingSoftCreditValues['soft_credit_id'])) {
- civicrm_api3('ContributionSoft', 'delete', array(
+ civicrm_api3('ContributionSoft', 'delete', [
'id' => $existingSoftCreditValues['soft_credit_id'],
'pcp_id' => NULL,
- ));
+ ]);
}
}
}
@@ -430,11 +352,11 @@ public function import($onDuplicate, &$values) {
return CRM_Import_Parser::VALID;
}
else {
- $labels = array(
+ $labels = [
'id' => 'Contribution ID',
'trxn_id' => 'Transaction ID',
'invoice_id' => 'Invoice ID',
- );
+ ];
foreach ($dupeIds as $k => $v) {
if ($v) {
$errorMsg[] = "$labels[$k] $v";
@@ -495,10 +417,10 @@ public function import($onDuplicate, &$values) {
}
else {
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = NULL;
foreach ($fieldsArray as $value) {
@@ -575,7 +497,7 @@ public function import($onDuplicate, &$values) {
public function processPledgePayments(&$formatted) {
if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) {
//get completed status
- $completeStatusID = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
+ $completeStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
//need to update payment record to map contribution_id
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'],
@@ -583,7 +505,7 @@ public function processPledgePayments(&$formatted) {
);
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($formatted['pledge_id'],
- array($formatted['pledge_payment_id']),
+ [$formatted['pledge_payment_id']],
$completeStatusID,
NULL,
$formatted['total_amount']
@@ -608,4 +530,105 @@ public function &getImportedContributions() {
public function fini() {
}
+ /**
+ * Format date fields from input to mysql.
+ *
+ * @param array $params
+ *
+ * @return array
+ * Error messages, if any.
+ */
+ public function formatDateFields(&$params) {
+ $errorMessage = [];
+ $dateType = CRM_Core_Session::singleton()->get('dateTypes');
+ foreach ($params as $key => $val) {
+ if ($val) {
+ switch ($key) {
+ case 'receive_date':
+ if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
+ $params[$key] = $dateValue;
+ }
+ else {
+ $errorMessage[] = ts('Receive Date');
+ }
+ break;
+
+ case 'cancel_date':
+ if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
+ $params[$key] = $dateValue;
+ }
+ else {
+ $errorMessage[] = ts('Cancel Date');
+ }
+ break;
+
+ case 'receipt_date':
+ if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
+ $params[$key] = $dateValue;
+ }
+ else {
+ $errorMessage[] = ts('Receipt date');
+ }
+ break;
+
+ case 'thankyou_date':
+ if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
+ $params[$key] = $dateValue;
+ }
+ else {
+ $errorMessage[] = ts('Thankyou Date');
+ }
+ break;
+ }
+ }
+ }
+ return $errorMessage;
+ }
+
+ /**
+ * Format input params to suit api handling.
+ *
+ * Over time all the parts of _civicrm_api3_deprecated_formatted_param
+ * and all the parts of the import function on this class that relate to
+ * reformatting input should be moved here and tests should be added in
+ * CRM_Contribute_Import_Parser_ContributionTest.
+ *
+ * @param array $params
+ */
+ public function formatInput(&$params) {
+ $dateType = CRM_Core_Session::singleton()->get('dateTypes');
+ $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
+ $customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
+ // @todo call formatDateFields & move custom data handling there.
+ // Also note error handling for dates is currently in _civicrm_api3_deprecated_formatted_param
+ // we should use the error handling in formatDateFields.
+ foreach ($params as $key => $val) {
+ // @todo - call formatDateFields instead.
+ if ($val) {
+ switch ($key) {
+ case 'receive_date':
+ case 'cancel_date':
+ case 'receipt_date':
+ case 'thankyou_date':
+ $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType);
+ break;
+
+ case 'pledge_payment':
+ $params[$key] = CRM_Utils_String::strtobool($val);
+ break;
+
+ }
+ if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
+ if ($customFields[$customFieldID]['data_type'] == 'Date') {
+ CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
+ unset($params[$key]);
+ }
+ elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
+ $params[$key] = CRM_Utils_String::strtoboolstr($val);
+ }
+ }
+ }
+ }
+ }
+
}
diff --git a/CRM/Contribute/Info.php b/CRM/Contribute/Info.php
index 7fccbdda920b..6fd1c9c51c39 100644
--- a/CRM/Contribute/Info.php
+++ b/CRM/Contribute/Info.php
@@ -1,9 +1,9 @@
'CiviContribute',
'translatedName' => ts('CiviContribute'),
'title' => ts('CiviCRM Contribution Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
/**
@@ -80,23 +82,23 @@ public function getInfo() {
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviContribute' => array(
+ $permissions = [
+ 'access CiviContribute' => [
ts('access CiviContribute'),
ts('Record backend contributions (with edit contributions) and view all contributions (for visible contacts)'),
- ),
- 'edit contributions' => array(
+ ],
+ 'edit contributions' => [
ts('edit contributions'),
ts('Record and update contributions'),
- ),
- 'make online contributions' => array(
+ ],
+ 'make online contributions' => [
ts('make online contributions'),
- ),
- 'delete in CiviContribute' => array(
+ ],
+ 'delete in CiviContribute' => [
ts('delete in CiviContribute'),
ts('Delete contributions'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -114,13 +116,14 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* list of permissions
* @see CRM_Component_Info::getPermissions
*/
+
/**
* @return array
*/
public function getAnonymousPermissionWarnings() {
- return array(
+ return [
'access CiviContribute',
- );
+ ];
}
/**
@@ -132,16 +135,17 @@ public function getAnonymousPermissionWarnings() {
* collection of required dashboard settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Contributions'),
'title' => ts('Your Contribution(s)'),
- 'perm' => array('make online contributions'),
+ 'perm' => ['make online contributions'],
'weight' => 10,
- );
+ ];
}
/**
@@ -153,15 +157,24 @@ public function getUserDashboardElement() {
* collection of required dashboard settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Contributions'),
'url' => 'contribution',
'weight' => 20,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-credit-card';
}
/**
@@ -173,14 +186,15 @@ public function registerTab() {
* collection of required pane settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Contributions'),
'weight' => 20,
- );
+ ];
}
/**
@@ -193,6 +207,7 @@ public function registerAdvancedSearchPane() {
* @return array|null
* collection of activity types
*/
+
/**
* @return array|null
*/
@@ -209,20 +224,20 @@ public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviContribute') &&
CRM_Core_Permission::check('edit contributions')
) {
- $shortCut[] = array(
+ $shortCut[] = [
'path' => 'civicrm/contribute/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-contribution',
'title' => ts('Contribution'),
- );
+ ];
if ($newCredit) {
$title = ts('Contribution') . ' (' . ts('credit card') . ')';
- $shortCut[0]['shortCuts'][] = array(
+ $shortCut[0]['shortCuts'][] = [
'path' => 'civicrm/contribute/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-contribution-cc',
'title' => $title,
- );
+ ];
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
diff --git a/CRM/Contribute/Page/AJAX.php b/CRM/Contribute/Page/AJAX.php
index e51e17a243eb..9cbfacdd6af3 100644
--- a/CRM/Contribute/Page/AJAX.php
+++ b/CRM/Contribute/Page/AJAX.php
@@ -1,9 +1,9 @@
'Integer',
'context' => 'String',
- );
- $optionalParameters = array(
+ ];
+ $optionalParameters = [
'entityID' => 'Integer',
'isTest' => 'Integer',
- );
+ ];
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
diff --git a/CRM/Contribute/Page/ContributionPage.php b/CRM/Contribute/Page/ContributionPage.php
index ba4786bef437..0f9f8df41a68 100644
--- a/CRM/Contribute/Page/ContributionPage.php
+++ b/CRM/Contribute/Page/ContributionPage.php
@@ -1,9 +1,9 @@
ts('Test-drive'),
'url' => $urlString,
'qs' => $urlParams . '&action=preview',
+ // Addresses https://lab.civicrm.org/dev/core/issues/658
+ 'fe' => TRUE,
'uniqueName' => 'test_drive',
),
);
@@ -419,8 +421,10 @@ public function browse($action = NULL) {
$params = array();
$whereClause = $this->whereClause($params, FALSE);
- $this->pagerAToZ($whereClause, $params);
-
+ $config = CRM_Core_Config::singleton();
+ if ($config->includeAlphabeticalPager) {
+ $this->pagerAToZ($whereClause, $params);
+ }
$params = array();
$whereClause = $this->whereClause($params, TRUE);
$this->pager($whereClause, $params);
diff --git a/CRM/Contribute/Page/ContributionRecur.php b/CRM/Contribute/Page/ContributionRecur.php
index 977ec388a29a..7aa68b264e3d 100644
--- a/CRM/Contribute/Page/ContributionRecur.php
+++ b/CRM/Contribute/Page/ContributionRecur.php
@@ -1,9 +1,9 @@
id = $this->_id;
- if ($recur->find(TRUE)) {
- $values = array();
- CRM_Core_DAO::storeValues($recur, $values);
- // if there is a payment processor ID, get the name of the payment processor
- if (!empty($values['payment_processor_id'])) {
- $values['payment_processor'] = CRM_Core_DAO::getFieldValue(
- 'CRM_Financial_DAO_PaymentProcessor',
- $values['payment_processor_id'],
- 'name'
- );
- }
- $idFields = array('contribution_status_id', 'campaign_id');
- if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($values['id'])) {
- $idFields[] = 'financial_type_id';
- }
- foreach ($idFields as $idField) {
- if (!empty($values[$idField])) {
- $values[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $values[$idField]);
- }
+ if (empty($this->_id)) {
+ CRM_Core_Error::statusBounce('Recurring contribution not found');
+ }
+
+ try {
+ $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
+ 'id' => $this->_id,
+ ]);
+ }
+ catch (Exception $e) {
+ CRM_Core_Error::statusBounce('Recurring contribution not found (ID: ' . $this->_id);
+ }
+
+ $contributionRecur['payment_processor'] = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessorName(
+ CRM_Utils_Array::value('payment_processor_id', $contributionRecur)
+ );
+ $idFields = ['contribution_status_id', 'campaign_id', 'financial_type_id'];
+ foreach ($idFields as $idField) {
+ if (!empty($contributionRecur[$idField])) {
+ $contributionRecur[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $contributionRecur[$idField]);
}
+ }
- $this->assign('recur', $values);
+ // Add linked membership
+ $membership = civicrm_api3('Membership', 'get', [
+ 'contribution_recur_id' => $contributionRecur['id'],
+ ]);
+ if (!empty($membership['count'])) {
+ $membershipDetails = reset($membership['values']);
+ $contributionRecur['membership_id'] = $membershipDetails['id'];
+ $contributionRecur['membership_name'] = $membershipDetails['membership_name'];
}
+
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('ContributionRecur', NULL, $contributionRecur['id']);
+ CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $contributionRecur['id']);
+
+ $this->assign('recur', $contributionRecur);
+
+ $displayName = CRM_Contact_BAO_Contact::displayName($contributionRecur['contact_id']);
+ $this->assign('displayName', $displayName);
+
+ // Check if this is default domain contact CRM-10482
+ if (CRM_Contact_BAO_Contact::checkDomainContact($contributionRecur['contact_id'])) {
+ $displayName .= ' (' . ts('default organization') . ')';
+ }
+
+ // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
+ CRM_Utils_System::setTitle(ts('View Recurring Contribution from') . ' ' . $displayName);
}
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'view');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
diff --git a/CRM/Contribute/Page/ContributionRecurPayments.php b/CRM/Contribute/Page/ContributionRecurPayments.php
new file mode 100644
index 000000000000..91419ff36428
--- /dev/null
+++ b/CRM/Contribute/Page/ContributionRecurPayments.php
@@ -0,0 +1,225 @@
+id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
+ $this->contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
+
+ $this->loadRelatedContributions();
+
+ return parent::run();
+ }
+
+ /**
+ * Loads contributions associated to the current recurring contribution being
+ * viewed.
+ */
+ private function loadRelatedContributions() {
+ $relatedContributions = [];
+
+ $relatedContributionsResult = civicrm_api3('Contribution', 'get', [
+ 'sequential' => 1,
+ 'contribution_recur_id' => $this->id,
+ 'contact_id' => $this->contactId,
+ 'options' => ['limit' => 0],
+ 'contribution_test' => '',
+ ]);
+
+ foreach ($relatedContributionsResult['values'] as $contribution) {
+ $this->insertAmountExpandingPaymentsControl($contribution);
+ $this->fixDateFormats($contribution);
+ $this->insertStatusLabels($contribution);
+ $this->insertContributionActions($contribution);
+
+ if ($contribution['is_test']) {
+ $contribution['financial_type'] = CRM_Core_TestEntity::appendTestText($contribution['financial_type']);
+ }
+ $relatedContributions[] = $contribution;
+ }
+
+ if (count($relatedContributions) > 0) {
+ $this->assign('contributionsCount', count($relatedContributions));
+ $this->assign('relatedContributions', json_encode($relatedContributions));
+ }
+ }
+
+ /**
+ * Inserts a string into the array with the html used to show the expanding
+ * payments control, which loads when user clicks on the amount.
+ *
+ * @param array $contribution
+ * Reference to the array holding the contribution's data and where the
+ * control will be inserted into
+ */
+ private function insertAmountExpandingPaymentsControl(&$contribution) {
+ $amount = CRM_Utils_Money::format($contribution['total_amount'], $contribution['currency']);
+
+ $expandPaymentsUrl = CRM_Utils_System::url('civicrm/payment',
+ [
+ 'view' => 'transaction',
+ 'component' => 'contribution',
+ 'action' => 'browse',
+ 'cid' => $this->contactId,
+ 'id' => $contribution['contribution_id'],
+ 'selector' => 1,
+ ],
+ FALSE, NULL, TRUE
+ );
+
+ $contribution['amount_control'] = '
+
+ ' . $amount . '
+
+ ';
+ }
+
+ /**
+ * Fixes date fields present in the given contribution.
+ *
+ * @param array $contribution
+ * Reference to the array holding the contribution's data
+ */
+ private function fixDateFormats(&$contribution) {
+ $config = CRM_Core_Config::singleton();
+
+ $contribution['formatted_receive_date'] = CRM_Utils_Date::customFormat($contribution['receive_date'], $config->dateformatDatetime);
+ $contribution['formatted_thankyou_date'] = CRM_Utils_Date::customFormat($contribution['thankyou_date'], $config->dateformatDatetime);
+ }
+
+ /**
+ * Inserts a contribution_status_label key into the array, with the value
+ * showing the current status plus observations on the current status.
+ *
+ * @param array $contribution
+ * Reference to the array holding the contribution's data and where the new
+ * position will be inserted
+ */
+ private function insertStatusLabels(&$contribution) {
+ $contribution['contribution_status_label'] = $contribution['contribution_status'];
+
+ if ($contribution['is_pay_later'] && CRM_Utils_Array::value('contribution_status', $contribution) == 'Pending') {
+ $contribution['contribution_status_label'] .= ' (' . ts('Pay Later') . ')';
+ }
+ elseif (CRM_Utils_Array::value('contribution_status', $contribution) == 'Pending') {
+ $contribution['contribution_status_label'] .= ' (' . ts('Incomplete Transaction') . ')';
+ }
+ }
+
+ /**
+ * Inserts into the given array a string with the 'action' key, holding the
+ * html to be used to show available actions for the contribution.
+ *
+ * @param $contribution
+ * Reference to the array holding the contribution's data. It is also the
+ * array where the new 'action' key will be inserted.
+ */
+ private function insertContributionActions(&$contribution) {
+ $contribution['action'] = CRM_Core_Action::formLink(
+ $this->buildContributionLinks($contribution),
+ $this->getContributionPermissionsMask(),
+ [
+ 'id' => $contribution['contribution_id'],
+ 'cid' => $contribution['contact_id'],
+ 'cxt' => 'contribution',
+ ],
+ ts('more'),
+ FALSE,
+ 'contribution.selector.row',
+ 'Contribution',
+ $contribution['contribution_id']
+ );
+ }
+
+ /**
+ * Builds list of links for authorized actions that can be done on given
+ * contribution.
+ *
+ * @param array $contribution
+ *
+ * @return array
+ */
+ private function buildContributionLinks($contribution) {
+ $links = CRM_Contribute_Selector_Search::links($contribution['contribution_id'],
+ CRM_Utils_Request::retrieve('action', 'String'),
+ NULL,
+ NULL
+ );
+
+ $isPayLater = FALSE;
+ if ($contribution['is_pay_later'] && CRM_Utils_Array::value('contribution_status', $contribution) == 'Pending') {
+ $isPayLater = TRUE;
+
+ $links[CRM_Core_Action::ADD] = [
+ 'name' => ts('Pay with Credit Card'),
+ 'url' => 'civicrm/contact/view/contribution',
+ 'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%&mode=live',
+ 'title' => ts('Pay with Credit Card'),
+ ];
+ }
+
+ if (in_array($contribution['contribution_status'], ['Partially paid', 'Pending refund']) || $isPayLater) {
+ $buttonName = ts('Record Payment');
+
+ if ($contribution['contribution_status'] == 'Pending refund') {
+ $buttonName = ts('Record Refund');
+ }
+ elseif (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
+ $links[CRM_Core_Action::BASIC] = [
+ 'name' => ts('Submit Credit Card payment'),
+ 'url' => 'civicrm/payment/add',
+ 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution&mode=live',
+ 'title' => ts('Submit Credit Card payment'),
+ ];
+ }
+ $links[CRM_Core_Action::ADD] = [
+ 'name' => $buttonName,
+ 'url' => 'civicrm/payment',
+ 'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution',
+ 'title' => $buttonName,
+ ];
+ }
+
+ return $links;
+ }
+
+ /**
+ * Builds a mask with allowed contribution related permissions.
+ *
+ * @return int
+ */
+ private function getContributionPermissionsMask() {
+ $permissions = [CRM_Core_Permission::VIEW];
+ if (CRM_Core_Permission::check('edit contributions')) {
+ $permissions[] = CRM_Core_Permission::EDIT;
+ }
+ if (CRM_Core_Permission::check('delete in CiviContribute')) {
+ $permissions[] = CRM_Core_Permission::DELETE;
+ }
+
+ return CRM_Core_Action::mask($permissions);
+ }
+
+}
diff --git a/CRM/Contribute/Page/DashBoard.php b/CRM/Contribute/Page/DashBoard.php
index 0f46943431c2..59b07ffda409 100644
--- a/CRM/Contribute/Page/DashBoard.php
+++ b/CRM/Contribute/Page/DashBoard.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/contribute/managePremiums',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Premium'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview'),
'url' => 'civicrm/admin/contribute/managePremiums',
'qs' => 'action=preview&id=%%id%%',
'title' => ts('Preview Premium'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Premium'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Premium'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/contribute/managePremiums',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Premium'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -108,7 +108,7 @@ public function run() {
$id = $this->getIdAndAction();
// what action to take ?
- if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::PREVIEW)) {
+ if (!($this->_action & CRM_Core_Action::BROWSE)) {
$this->edit($this->_action, $id, TRUE);
}
// finally browse the custom groups
@@ -123,13 +123,13 @@ public function run() {
*/
public function browse() {
// get all custom groups sorted by weight
- $premiums = array();
+ $premiums = [];
$dao = new CRM_Contribute_DAO_Product();
$dao->orderBy('name');
$dao->find();
while ($dao->fetch()) {
- $premiums[$dao->id] = array();
+ $premiums[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $premiums[$dao->id]);
// form all action links
$action = array_sum(array_keys($this->links()));
@@ -143,17 +143,16 @@ public function browse() {
$premiums[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(),
$action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'premium.manage.row',
'Premium',
$dao->id
);
- //Financial Type
+ // Financial Type
if (!empty($dao->financial_type_id)) {
- require_once 'CRM/Core/DAO.php';
- $premiums[$dao->id]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $dao->financial_type_id, 'name');
+ $premiums[$dao->id]['financial_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Product', 'financial_type_id', $dao->financial_type_id);
}
}
$this->assign('rows', $premiums);
diff --git a/CRM/Contribute/Page/PaymentInfo.php b/CRM/Contribute/Page/PaymentInfo.php
index 8227ff067f73..bfb9e8436180 100644
--- a/CRM/Contribute/Page/PaymentInfo.php
+++ b/CRM/Contribute/Page/PaymentInfo.php
@@ -1,9 +1,9 @@
_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, TRUE);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, TRUE);
$this->_cid = CRM_Utils_Request::retrieve('cid', 'String', $this, TRUE);
$this->assign('cid', $this->_cid);
diff --git a/CRM/Contribute/Page/Premium.php b/CRM/Contribute/Page/Premium.php
index e0686b459e64..25189668ad14 100644
--- a/CRM/Contribute/Page/Premium.php
+++ b/CRM/Contribute/Page/Premium.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/contribute/addProductToPage',
'qs' => 'action=update&id=%%id%%&pid=%%pid%%&reset=1',
'title' => ts('Edit Premium'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview'),
'url' => 'civicrm/admin/contribute/addProductToPage',
'qs' => 'action=preview&id=%%id%%&pid=%%pid%%',
'title' => ts('Preview Premium'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Remove'),
'url' => 'civicrm/admin/contribute/addProductToPage',
'qs' => 'action=delete&id=%%id%%&pid=%%pid%%',
'extra' => 'onclick = "if (confirm(\'' . $deleteExtra . '\') ) this.href+=\'&confirmed=1\'; else return false;"',
'title' => ts('Disable Premium'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -126,49 +126,49 @@ public function run() {
*/
public function browse() {
// get all custom groups sorted by weight
- $premiums = array();
+ $premiums = [];
$pageID = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
- $dao = new CRM_Contribute_DAO_Premium();
- $dao->entity_table = 'civicrm_contribution_page';
- $dao->entity_id = $pageID;
- $dao->find(TRUE);
- $premiumID = $dao->id;
+ $premiumDao = new CRM_Contribute_DAO_Premium();
+ $premiumDao->entity_table = 'civicrm_contribution_page';
+ $premiumDao->entity_id = $pageID;
+ $premiumDao->find(TRUE);
+ $premiumID = $premiumDao->id;
$this->assign('products', FALSE);
$this->assign('id', $pageID);
if (!$premiumID) {
return;
}
- $dao = new CRM_Contribute_DAO_PremiumsProduct();
- $dao->premiums_id = $premiumID;
- $dao->orderBy('weight');
- $dao->find();
+ $premiumsProductDao = new CRM_Contribute_DAO_PremiumsProduct();
+ $premiumsProductDao->premiums_id = $premiumID;
+ $premiumsProductDao->orderBy('weight');
+ $premiumsProductDao->find();
- while ($dao->fetch()) {
+ while ($premiumsProductDao->fetch()) {
$productDAO = new CRM_Contribute_DAO_Product();
- $productDAO->id = $dao->product_id;
+ $productDAO->id = $premiumsProductDao->product_id;
$productDAO->is_active = 1;
if ($productDAO->find(TRUE)) {
- $premiums[$productDAO->id] = array();
- $premiums[$productDAO->id]['weight'] = $dao->weight;
+ $premiums[$productDAO->id] = [];
+ $premiums[$productDAO->id]['weight'] = $premiumsProductDao->weight;
CRM_Core_DAO::storeValues($productDAO, $premiums[$productDAO->id]);
$action = array_sum(array_keys($this->links()));
- $premiums[$dao->product_id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $pageID, 'pid' => $dao->id),
+ $premiums[$premiumsProductDao->product_id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
+ ['id' => $pageID, 'pid' => $premiumsProductDao->id],
ts('more'),
FALSE,
'premium.contributionpage.row',
'Premium',
- $dao->id
+ $premiumsProductDao->id
);
- //Financial Type
- if (!empty($dao->financial_type_id)) {
- $premiums[$productDAO->id]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $dao->financial_type_id, 'name');
+ // Financial Type
+ if (!empty($premiumsProductDao->financial_type_id)) {
+ $premiums[$productDAO->id]['financial_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Product', 'financial_type_id', $premiumsProductDao->financial_type_id);
}
}
}
diff --git a/CRM/Contribute/Page/SubscriptionStatus.php b/CRM/Contribute/Page/SubscriptionStatus.php
index 4e2aa09863af..96e7f0786f92 100644
--- a/CRM/Contribute/Page/SubscriptionStatus.php
+++ b/CRM/Contribute/Page/SubscriptionStatus.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'title' => ts('View Recurring Payment'),
'url' => 'civicrm/contact/view/contributionrecur',
'qs' => "reset=1&id=%%crid%%&cid=%%cid%%&context={$context}",
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'title' => ts('Edit Recurring Payment'),
'url' => 'civicrm/contribute/updaterecur',
'qs' => "reset=1&action=update&crid=%%crid%%&cid=%%cid%%&context={$context}",
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Cancel'),
'title' => ts('Cancel'),
'ref' => 'crm-enable-disable',
- ),
- );
+ ],
+ ];
}
if ($recurID) {
$links = self::$_links;
- $paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recurID, 'recur', 'obj');
- if (is_object($paymentProcessorObj) && $paymentProcessorObj->supports('cancelRecurring')) {
+ $paymentProcessorObj = CRM_Contribute_BAO_ContributionRecur::getPaymentProcessorObject($recurID);
+ if (!$paymentProcessorObj) {
+ unset($links[CRM_Core_Action::DISABLE]);
+ unset($links[CRM_Core_Action::UPDATE]);
+ return $links;
+ }
+ if ($paymentProcessorObj->supports('cancelRecurring')) {
unset($links[CRM_Core_Action::DISABLE]['extra'], $links[CRM_Core_Action::DISABLE]['ref']);
$links[CRM_Core_Action::DISABLE]['url'] = "civicrm/contribute/unsubscribe";
$links[CRM_Core_Action::DISABLE]['qs'] = "reset=1&crid=%%crid%%&cid=%%cid%%&context={$context}";
}
- if (is_object($paymentProcessorObj) && $paymentProcessorObj->isSupported('updateSubscriptionBillingInfo')) {
- $links[CRM_Core_Action::RENEW] = array(
+ if ($paymentProcessorObj->supports('UpdateSubscriptionBillingInfo')) {
+ $links[CRM_Core_Action::RENEW] = [
'name' => ts('Change Billing Details'),
'title' => ts('Change Billing Details'),
'url' => 'civicrm/contribute/updatebilling',
'qs' => "reset=1&crid=%%crid%%&cid=%%cid%%&context={$context}",
- );
+ ];
+ }
+
+ if (!$paymentProcessorObj->supports('ChangeSubscriptionAmount') && !$paymentProcessorObj->supports('EditRecurringContribution')) {
+ unset($links[CRM_Core_Action::UPDATE]);
}
return $links;
}
return self::$_links;
}
- // end function
/**
* called when action is browse.
@@ -108,7 +116,7 @@ public static function &recurLinks($recurID = FALSE, $context = 'contribution')
*/
public function browse() {
// add annual contribution
- $annual = array();
+ $annual = [];
list($annual['count'],
$annual['amount'],
$annual['avg']
@@ -131,44 +139,9 @@ public function browse() {
$controller->run();
// add recurring block
- $action = array_sum(array_keys($this->recurLinks()));
- $params = CRM_Contribute_BAO_ContributionRecur::getRecurContributions($this->_contactId);
-
- if (!empty($params)) {
- foreach ($params as $ids => $recur) {
- $action = array_sum(array_keys($this->recurLinks($ids)));
- // no action allowed if it's not active
- $params[$ids]['is_active'] = ($recur['contribution_status_id'] != 3);
-
- if ($params[$ids]['is_active']) {
- $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($params[$ids]['id'], 'recur');
- $hideUpdate = $details->membership_id & $details->auto_renew;
-
- if ($hideUpdate) {
- $action -= CRM_Core_Action::UPDATE;
- }
-
- $params[$ids]['action'] = CRM_Core_Action::formLink(self::recurLinks($ids), $action,
- array(
- 'cid' => $this->_contactId,
- 'crid' => $ids,
- 'cxt' => 'contribution',
- ),
- ts('more'),
- FALSE,
- 'contribution.selector.recurring',
- 'Contribution',
- $ids
- );
- }
- }
- // assign vars to templates
- $this->assign('action', $this->_action);
- $this->assign('recurRows', $params);
- $this->assign('recur', TRUE);
- }
+ $this->addRecurringContributionsBlock();
- //enable/disable soft credit records for test contribution
+ // enable/disable soft credit records for test contribution
$isTest = 0;
if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) {
$isTest = 1;
@@ -178,12 +151,14 @@ public function browse() {
$softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionList($this->_contactId, NULL, $isTest);
if (!empty($softCreditList)) {
- $softCreditTotals = array();
+ $softCreditTotals = [];
- list($softCreditTotals['amount'],
+ list($softCreditTotals['count'],
+ $softCreditTotals['cancel']['count'],
+ $softCreditTotals['amount'],
$softCreditTotals['avg'],
- $softCreditTotals['currency'],
- $softCreditTotals['cancelAmount'] //to get cancel amount
+ // to get cancel amount
+ $softCreditTotals['cancel']['amount']
) = CRM_Contribute_BAO_ContributionSoft::getSoftContributionTotals($this->_contactId, $isTest);
$this->assign('softCredit', TRUE);
@@ -194,14 +169,124 @@ public function browse() {
if ($this->_contactId) {
$displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
$this->assign('displayName', $displayName);
- $this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
+ $tabCount = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
+ $this->assign('tabCount', $tabCount);
+ $this->ajaxResponse['tabCount'] = $tabCount;
}
}
+ /**
+ * Get all the recurring contribution information and assign to the template
+ */
+ private function addRecurringContributionsBlock() {
+ list($activeContributions, $activeContributionsCount) = $this->getActiveRecurringContributions();
+ list($inactiveRecurringContributions, $inactiveContributionsCount) = $this->getInactiveRecurringContributions();
+
+ if (!empty($activeContributions) || !empty($inactiveRecurringContributions)) {
+ // assign vars to templates
+ $this->assign('action', $this->_action);
+ $this->assign('activeRecurRows', $activeContributions);
+ $this->assign('contributionRecurCount', $activeContributionsCount + $inactiveContributionsCount);
+ $this->assign('inactiveRecurRows', $inactiveRecurringContributions);
+ $this->assign('recur', TRUE);
+ }
+ }
+
+ /**
+ * Loads active recurring contributions for the current contact and formats
+ * them to be used on the form.
+ *
+ * @return array;
+ */
+ private function getActiveRecurringContributions() {
+ try {
+ $contributionRecurResult = civicrm_api3('ContributionRecur', 'get', [
+ 'contact_id' => $this->_contactId,
+ 'contribution_status_id' => ['NOT IN' => CRM_Contribute_BAO_ContributionRecur::getInactiveStatuses()],
+ 'options' => ['limit' => 0, 'sort' => 'is_test, start_date DESC'],
+ ]);
+ $recurContributions = CRM_Utils_Array::value('values', $contributionRecurResult);
+ }
+ catch (Exception $e) {
+ $recurContributions = [];
+ }
+
+ return $this->buildRecurringContributionsArray($recurContributions);
+ }
+
+ /**
+ * Loads inactive recurring contributions for the current contact and formats
+ * them to be used on the form.
+ *
+ * @return array;
+ */
+ private function getInactiveRecurringContributions() {
+ try {
+ $contributionRecurResult = civicrm_api3('ContributionRecur', 'get', [
+ 'contact_id' => $this->_contactId,
+ 'contribution_status_id' => ['IN' => CRM_Contribute_BAO_ContributionRecur::getInactiveStatuses()],
+ 'options' => ['limit' => 0, 'sort' => 'is_test, start_date DESC'],
+ ]);
+ $recurContributions = CRM_Utils_Array::value('values', $contributionRecurResult);
+ }
+ catch (Exception $e) {
+ $recurContributions = NULL;
+ }
+
+ return $this->buildRecurringContributionsArray($recurContributions);
+ }
+
+ /**
+ * @param $recurContributions
+ *
+ * @return mixed
+ */
+ private function buildRecurringContributionsArray($recurContributions) {
+ $liveRecurringContributionCount = 0;
+ foreach ($recurContributions as $recurId => $recurDetail) {
+ // Is recurring contribution active?
+ $recurContributions[$recurId]['is_active'] = !in_array(CRM_Contribute_PseudoConstant::contributionStatus($recurDetail['contribution_status_id'], 'name'), CRM_Contribute_BAO_ContributionRecur::getInactiveStatuses());
+ if ($recurContributions[$recurId]['is_active']) {
+ $actionMask = array_sum(array_keys(self::recurLinks($recurId)));
+ }
+ else {
+ $actionMask = CRM_Core_Action::mask([CRM_Core_Permission::VIEW]);
+ }
+
+ if (empty($recurDetail['is_test'])) {
+ $liveRecurringContributionCount++;
+ }
+
+ // Get the name of the payment processor
+ if (!empty($recurDetail['payment_processor_id'])) {
+ $recurContributions[$recurId]['payment_processor'] = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessorName($recurDetail['payment_processor_id']);
+ }
+ // Get the label for the contribution status
+ if (!empty($recurDetail['contribution_status_id'])) {
+ $recurContributions[$recurId]['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $recurDetail['contribution_status_id']);
+ }
+
+ $recurContributions[$recurId]['action'] = CRM_Core_Action::formLink(self::recurLinks($recurId), $actionMask,
+ [
+ 'cid' => $this->_contactId,
+ 'crid' => $recurId,
+ 'cxt' => 'contribution',
+ ],
+ ts('more'),
+ FALSE,
+ 'contribution.selector.recurring',
+ 'Contribution',
+ $recurId
+ );
+ }
+
+ return [$recurContributions, $liveRecurringContributionCount];
+ }
+
/**
* called when action is view.
*
- * @return null
+ * @return mixed
*/
public function view() {
$controller = new CRM_Core_Controller_Simple(
@@ -219,11 +304,13 @@ public function view() {
/**
* called when action is update or new.
*
- * @return null
+ * @return mixed
+ * @throws \CRM_Core_Exception
+ * @throws \Exception
*/
public function edit() {
// set https for offline cc transaction
- $mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
if ($mode == 'test' || $mode == 'live') {
CRM_Utils_System::redirectToSSL();
}
@@ -241,7 +328,7 @@ public function edit() {
}
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -251,10 +338,10 @@ public function preProcess() {
else {
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, empty($this->_id));
if (empty($this->_contactId)) {
- $this->_contactId = civicrm_api3('contribution', 'getvalue', array(
- 'id' => $this->_id,
- 'return' => 'contact_id',
- ));
+ $this->_contactId = civicrm_api3('contribution', 'getvalue', [
+ 'id' => $this->_id,
+ 'return' => 'contact_id',
+ ]);
}
$this->assign('contactId', $this->_contactId);
@@ -299,7 +386,7 @@ public function run() {
public function setContext() {
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
- $context = CRM_Utils_Request::retrieve('context', 'String',
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric',
$this, FALSE, 'search'
);
$compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
@@ -320,8 +407,6 @@ public function setContext() {
$qfKey = NULL;
}
- $session = CRM_Core_Session::singleton();
-
switch ($context) {
case 'user':
$url = CRM_Utils_System::url('civicrm/user', 'reset=1');
diff --git a/CRM/Contribute/Page/UserDashboard.php b/CRM/Contribute/Page/UserDashboard.php
index a3dfb350423d..32c231782f0c 100644
--- a/CRM/Contribute/Page/UserDashboard.php
+++ b/CRM/Contribute/Page/UserDashboard.php
@@ -1,9 +1,9 @@
setEmbedded(TRUE);
- $controller->reset();
- $controller->set('limit', 12);
- $controller->set('cid', $this->_contactId);
- $controller->set('context', 'user');
- $controller->set('force', 1);
- $controller->process();
- $controller->run();
+ $rows = civicrm_api3('Contribution', 'get', [
+ 'options' => [
+ 'limit' => 12,
+ 'sort' => 'receive_date DESC',
+ ],
+ 'sequential' => 1,
+ 'contact_id' => $this->_contactId,
+ 'return' => [
+ 'total_amount',
+ 'contribution_recur_id',
+ 'financial_type',
+ 'receive_date',
+ 'receipt_date',
+ 'contribution_status',
+ 'currency',
+ 'amount_level',
+ 'contact_id,',
+ 'contribution_source',
+ ],
+ ])['values'];
+
+ // We want oldest first, just among the most recent contributions
+ $rows = array_reverse($rows);
+
+ foreach ($rows as $index => &$row) {
+ // This is required for tpl logic. We should move away from hard-code this to adding an array of actions to the row
+ // which the tpl can iterate through - this should allow us to cope with competing attempts to add new buttons
+ // and allow extensions to assign new ones through the pageRun hook
+ if ('Pending' === CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $row['contribution_status_id'])) {
+ $row['buttons']['pay'] = [
+ 'class' => 'button',
+ 'label' => ts('Pay Now'),
+ 'url' => CRM_Utils_System::url('civicrm/contribute/transact', [
+ 'reset' => 1,
+ 'id' => CRM_Invoicing_Utils::getDefaultPaymentPage(),
+ 'ccid' => $row['contribution_id'],
+ 'cs' => $this->getUserChecksum(),
+ 'cid' => $row['contact_id'],
+ ])
+ ];
+ }
+ }
+
+ $this->assign('contribute_rows', $rows);
+ $this->assign('contributionSummary', ['total_amount' => civicrm_api3('Contribution', 'getcount', ['contact_id' => $this->_contactId])]);
//add honor block
$params = CRM_Contribute_BAO_Contribution::getHonorContacts($this->_contactId);
@@ -65,18 +96,14 @@ public function listContribution() {
$recur->is_test = 0;
$recur->find();
- $config = CRM_Core_Config::singleton();
-
$recurStatus = CRM_Contribute_PseudoConstant::contributionStatus();
- $recurRow = array();
- $recurIDs = array();
+ $recurRow = [];
+ $recurIDs = [];
while ($recur->fetch()) {
- $mode = $recur->is_test ? 'test' : 'live';
- $paymentProcessor = CRM_Contribute_BAO_ContributionRecur::getPaymentProcessor($recur->id,
- $mode
- );
- if (!$paymentProcessor) {
+ if (empty($recur->payment_processor_id)) {
+ // it's not clear why we continue here as any without a processor id would likely
+ // be imported from another system & still seem valid.
continue;
}
@@ -97,11 +124,11 @@ public function listContribution() {
}
$recurRow[$values['id']]['action'] = CRM_Core_Action::formLink(CRM_Contribute_Page_Tab::recurLinks($recur->id, 'dashboard'),
- $action, array(
+ $action, [
'cid' => $this->_contactId,
'crid' => $values['id'],
'cxt' => 'contribution',
- ),
+ ],
ts('more'),
FALSE,
'contribution.dashboard.recurring',
@@ -110,10 +137,6 @@ public function listContribution() {
);
$recurIDs[] = $values['id'];
-
- //reset $paymentObject for checking other paymenet processor
- //recurring url
- $paymentObject = NULL;
}
if (is_array($recurIDs) && !empty($recurIDs)) {
$getCount = CRM_Contribute_BAO_ContributionRecur::getCount($recurIDs);
@@ -134,16 +157,28 @@ public function listContribution() {
}
}
+ /**
+ * Should invoice links be displayed on the template.
+ *
+ * @todo This should be moved to a hook-like structure on the invoicing class
+ * (currently CRM_Utils_Invoicing) with a view to possible removal from core.
+ */
+ public function isIncludeInvoiceLinks() {
+ if (!CRM_Invoicing_Utils::isInvoicingEnabled()) {
+ return FALSE;
+ }
+ $dashboardOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'user_dashboard_options'
+ );
+ return $dashboardOptions['Invoices / Credit Notes'];
+ }
+
/**
* the main function that is called when the page
* loads, it decides the which action has to be taken for the page.
*/
public function run() {
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
- $defaultInvoicePage = CRM_Utils_Array::value('default_invoice_page', $invoiceSettings);
- $this->assign('invoicing', $invoicing);
- $this->assign('defaultInvoicePage', $defaultInvoicePage);
+ $this->assign('isIncludeInvoiceLinks', $this->isIncludeInvoiceLinks());
parent::preProcess();
$this->listContribution();
}
diff --git a/CRM/Contribute/PseudoConstant.php b/CRM/Contribute/PseudoConstant.php
index f0b50573e309..37433be2e309 100644
--- a/CRM/Contribute/PseudoConstant.php
+++ b/CRM/Contribute/PseudoConstant.php
@@ -1,9 +1,9 @@
is_active = 1;
$dao->orderBy('id');
@@ -275,7 +276,7 @@ public static function products($pageID = NULL) {
$dao->find(TRUE);
$premiumID = $dao->id;
- $productID = array();
+ $productID = [];
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->premiums_id = $premiumID;
@@ -284,7 +285,7 @@ public static function products($pageID = NULL) {
$productID[$dao->product_id] = $dao->product_id;
}
- $tempProduct = array();
+ $tempProduct = [];
foreach ($products as $key => $value) {
if (!array_key_exists($key, $productID)) {
$tempProduct[$key] = $value;
@@ -364,10 +365,10 @@ public static function &pcPage($pageType = NULL, $id = NULL) {
*/
public static function &pcpStatus($column = 'label') {
if (NULL === self::$pcpStatus) {
- self::$pcpStatus = array();
+ self::$pcpStatus = [];
}
if (!array_key_exists($column, self::$pcpStatus)) {
- self::$pcpStatus[$column] = array();
+ self::$pcpStatus[$column] = [];
self::$pcpStatus[$column] = CRM_Core_OptionGroup::values('pcp_status', FALSE,
FALSE, FALSE, NULL, $column
@@ -379,6 +380,8 @@ public static function &pcpStatus($column = 'label') {
/**
* Get financial account for a Financial type.
*
+ * @deprecated use the alternative with caching
+ * CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship
*
* @param int $entityId
* @param string $accountRelationType
@@ -387,11 +390,11 @@ public static function &pcpStatus($column = 'label') {
* @return int
*/
public static function getRelationalFinancialAccount($entityId, $accountRelationType, $entityTable = 'civicrm_financial_type', $returnField = 'financial_account_id') {
- $params = array(
- 'return' => array($returnField),
+ $params = [
+ 'return' => [$returnField],
'entity_table' => $entityTable,
'entity_id' => $entityId,
- );
+ ];
if ($accountRelationType) {
$params['account_relationship.name'] = $accountRelationType;
}
diff --git a/CRM/Contribute/Selector/Search.php b/CRM/Contribute/Selector/Search.php
index d05e92ce084a..f2250641c625 100644
--- a/CRM/Contribute/Selector/Search.php
+++ b/CRM/Contribute/Selector/Search.php
@@ -1,9 +1,9 @@
_action = $action;
- $returnProperties = CRM_Contribute_BAO_Query::selectorReturnProperties();
+ $returnProperties = CRM_Contribute_BAO_Query::selectorReturnProperties($this->_queryParams);
$this->_includeSoftCredits = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_queryParams);
+ $this->_queryParams[] = ['contribution_id', '!=', 0, 0, 0];
$this->_query = new CRM_Contact_BAO_Query(
$this->_queryParams,
$returnProperties,
@@ -226,26 +227,26 @@ public static function &links($componentId = NULL, $componentAction = NULL, $key
}
if (!(self::$_links)) {
- self::$_links = array(
- CRM_Core_Action::VIEW => array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => "reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=contribute{$extraParams}",
'title' => ts('View Contribution'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/contribution',
'qs' => "reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}",
'title' => ts('Edit Contribution'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/contribution',
'qs' => "reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}",
'title' => ts('Delete Contribution'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -316,10 +317,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$this->_contributionClause
);
// process the result of the query
- $rows = array();
+ $rows = [];
//CRM-4418 check for view/edit/delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit contributions')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -369,7 +370,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$componentContext
);
$checkLineItem = FALSE;
- $row = array();
+ $row = [];
// Now check for lineItems
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($result->id);
@@ -417,12 +418,12 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
if ($result->is_pay_later && CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
$isPayLater = TRUE;
$row['contribution_status'] .= ' (' . ts('Pay Later') . ')';
- $links[CRM_Core_Action::ADD] = array(
+ $links[CRM_Core_Action::ADD] = [
'name' => ts('Pay with Credit Card'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%&mode=live',
'title' => ts('Pay with Credit Card'),
- );
+ ];
}
elseif (CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
$row['contribution_status'] .= ' (' . ts('Incomplete Transaction') . ')';
@@ -434,31 +435,31 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contribution_id;
- $actions = array(
+ $actions = [
'id' => $result->contribution_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- );
+ ];
- if (in_array($row['contribution_status_name'], array('Partially paid', 'Pending refund')) || $isPayLater) {
+ if (in_array($row['contribution_status_name'], ['Partially paid', 'Pending refund']) || $isPayLater) {
$buttonName = ts('Record Payment');
if ($row['contribution_status_name'] == 'Pending refund') {
$buttonName = ts('Record Refund');
}
elseif (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
- $links[CRM_Core_Action::BASIC] = array(
+ $links[CRM_Core_Action::BASIC] = [
'name' => ts('Submit Credit Card payment'),
'url' => 'civicrm/payment/add',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution&mode=live',
'title' => ts('Submit Credit Card payment'),
- );
+ ];
}
- $links[CRM_Core_Action::ADD] = array(
+ $links[CRM_Core_Action::ADD] = [
'name' => $buttonName,
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution',
'title' => $buttonName,
- );
+ ];
}
$row['action'] = CRM_Core_Action::formLink(
@@ -504,105 +505,107 @@ public function getQILL() {
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
- $pre = array();
- self::$_columnHeaders = array(
- array(
+ $pre = [];
+ self::$_columnHeaders = [
+ [
'name' => $this->_includeSoftCredits ? ts('Contribution Amount') : ts('Amount'),
'sort' => 'total_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
'field_name' => 'total_amount',
- ),
- );
+ ],
+ ];
if ($this->_includeSoftCredits) {
self::$_columnHeaders
= array_merge(
self::$_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Soft Credit Amount'),
'sort' => 'contribution_soft_credit_amount',
'field_name' => 'contribution_soft_credit_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- )
+ ],
+ ]
);
}
self::$_columnHeaders
= array_merge(
self::$_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Type'),
'sort' => 'financial_type',
'field_name' => 'financial_type',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Source'),
'sort' => 'contribution_source',
'field_name' => 'contribution_source',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Received'),
'sort' => 'receive_date',
'field_name' => 'receive_date',
'type' => 'date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Thank-you Sent'),
'sort' => 'thankyou_date',
'field_name' => 'thankyou_date',
'type' => 'date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'contribution_status',
'field_name' => 'contribution_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
- 'name' => ts('Premium'),
- 'sort' => 'product_name',
- 'field_name' => 'product_name',
- 'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- )
+ ],
+ ]
);
+ if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
+ self::$_columnHeaders[] = [
+ 'name' => ts('Premium'),
+ 'sort' => 'product_name',
+ 'field_name' => 'product_name',
+ 'direction' => CRM_Utils_Sort::DONTCARE,
+ ];
+ }
if (!$this->_single) {
- $pre = array(
- array(
+ $pre = [
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
}
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
if ($this->_includeSoftCredits) {
self::$_columnHeaders = array_merge(
self::$_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Soft Credit For'),
'sort' => 'contribution_soft_credit_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Soft Credit Type'),
'sort' => 'contribution_soft_credit_type',
'direction' => CRM_Utils_Sort::ASCENDING,
- ),
- )
+ ],
+ ]
);
}
self::$_columnHeaders
= array_merge(
- self::$_columnHeaders, array(
- array('desc' => ts('Actions'), 'type' => 'actions'),
- )
+ self::$_columnHeaders, [
+ ['desc' => ts('Actions'), 'type' => 'actions'],
+ ]
);
foreach (array_keys(self::$_columnHeaders) as $index) {
// Add weight & space it out a bit to allow headers to be inserted.
@@ -617,7 +620,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Contribute/StateMachine/Contribution.php b/CRM/Contribute/StateMachine/Contribution.php
index 08b5bda75d1a..f7c598805c53 100644
--- a/CRM/Contribute/StateMachine/Contribution.php
+++ b/CRM/Contribute/StateMachine/Contribution.php
@@ -1,9 +1,9 @@
_pages = array(
+ $this->_pages = [
'CRM_Contribute_Form_Contribution_Main' => NULL,
'CRM_Contribute_Form_Contribution_Confirm' => NULL,
'CRM_Contribute_Form_Contribution_ThankYou' => NULL,
- );
+ ];
$this->addSequentialPages($this->_pages, $action);
}
diff --git a/CRM/Contribute/StateMachine/ContributionPage.php b/CRM/Contribute/StateMachine/ContributionPage.php
index bc225cfc86bc..47ccc247b88b 100644
--- a/CRM/Contribute/StateMachine/ContributionPage.php
+++ b/CRM/Contribute/StateMachine/ContributionPage.php
@@ -1,9 +1,9 @@
_pages = array(
+ $this->_pages = [
'CRM_Contribute_Form_ContributionPage_Settings' => NULL,
'CRM_Contribute_Form_ContributionPage_Amount' => NULL,
'CRM_Member_Form_MembershipBlock' => NULL,
@@ -62,7 +62,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
'CRM_Contribute_Form_ContributionPage_Custom' => NULL,
'CRM_Contribute_Form_ContributionPage_Premium' => NULL,
'CRM_Contribute_Form_ContributionPage_Widget' => NULL,
- );
+ ];
if (!in_array("CiviMember", $config->enableComponents)) {
unset($this->_pages['CRM_Member_Form_MembershipBlock']);
diff --git a/CRM/Contribute/StateMachine/Search.php b/CRM/Contribute/StateMachine/Search.php
index 6d437472e328..62c0d6c07885 100644
--- a/CRM/Contribute/StateMachine/Search.php
+++ b/CRM/Contribute/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Contribute_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -78,7 +78,8 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
+ * [ 'class' => task classname, 'result' => TRUE ]
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Contribute/Task.php b/CRM/Contribute/Task.php
index 9c4f20c5ad53..c7679aab1b5b 100644
--- a/CRM/Contribute/Task.php
+++ b/CRM/Contribute/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete contributions'),
'class' => 'CRM_Contribute_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Contribute_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export contributions'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
+ ],
+ self::BATCH_UPDATE => [
'title' => ts('Update multiple contributions'),
- 'class' => array(
+ 'class' => [
'CRM_Contribute_Form_Task_PickProfile',
'CRM_Contribute_Form_Task_Batch',
- ),
+ ],
'result' => TRUE,
- ),
- 5 => array(
- 'title' => ts('Email - send now'),
+ ],
+ self::TASK_EMAIL => [
+ 'title' => ts('Email - send now (to %1 or less)', [
+ 1 => Civi::settings()
+ ->get('simple_mail_limit'),
+ ]),
'class' => 'CRM_Contribute_Form_Task_Email',
'result' => TRUE,
- ),
- 6 => array(
+ ],
+ self::UPDATE_STATUS => [
'title' => ts('Update pending contribution status'),
'class' => 'CRM_Contribute_Form_Task_Status',
'result' => TRUE,
- ),
- 7 => array(
+ ],
+ self::PDF_RECEIPT => [
'title' => ts('Receipts - print or email'),
'class' => 'CRM_Contribute_Form_Task_PDF',
'result' => FALSE,
- ),
- 8 => array(
+ ],
+ self::PDF_THANKYOU => [
'title' => ts('Thank-you letters - print or email'),
'class' => 'CRM_Contribute_Form_Task_PDFLetter',
'result' => FALSE,
- ),
- 9 => array(
+ ],
+ self::PDF_INVOICE => [
'title' => ts('Invoices - print or email'),
'class' => 'CRM_Contribute_Form_Task_Invoice',
'result' => FALSE,
- ),
- );
+ ],
+ ];
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviContribute')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit contributions')) {
- unset(self::$_tasks[4], self::$_tasks[6]);
+ unset(self::$_tasks[self::BATCH_UPDATE], self::$_tasks[self::UPDATE_STATUS]);
}
// remove action "Invoices - print or email"
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
if (!$invoicing) {
- unset(self::$_tasks[9]);
+ unset(self::$_tasks[self::PDF_INVOICE]);
}
- CRM_Utils_Hook::searchTasks('contribution', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles
- * on contributors
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
*
- * @param bool $softCreditFiltering
+ * @param array $params
+ * bool softCreditFiltering: derived from CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission, $softCreditFiltering = FALSE) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
+ if (!isset($params['softCreditFiltering'])) {
+ $params['softCreditFiltering'] = FALSE;
+ }
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit contributions')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- 5 => self::$_tasks[5]['title'],
- 7 => self::$_tasks[7]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ self::TASK_EMAIL => self::$_tasks[self::TASK_EMAIL]['title'],
+ self::PDF_RECEIPT => self::$_tasks[self::PDF_RECEIPT]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviContribute')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
- if ($softCreditFiltering) {
- unset($tasks[4], $tasks[7]);
+ if ($params['softCreditFiltering']) {
+ unset($tasks[self::BATCH_UPDATE], $tasks[self::PDF_RECEIPT]);
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -204,17 +194,9 @@ public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
- $value = 2;
- }
- // this is possible since hooks can inject a task
- // CRM-13697
- if (!isset(self::$_tasks[$value]['result'])) {
- self::$_tasks[$value]['result'] = NULL;
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Contribute/Tokens.php b/CRM/Contribute/Tokens.php
index 441906fa7e77..25d247c51f59 100644
--- a/CRM/Contribute/Tokens.php
+++ b/CRM/Contribute/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -41,7 +41,7 @@ class CRM_Contribute_Tokens extends \Civi\Token\AbstractTokenSubscriber {
* @return array
*/
protected function getPassthruTokens() {
- return array(
+ return [
'contribution_page_id',
'receive_date',
'total_amount',
@@ -54,7 +54,7 @@ protected function getPassthruTokens() {
'receipt_date',
'thankyou_date',
'tax_amount',
- );
+ ];
}
/**
@@ -63,13 +63,13 @@ protected function getPassthruTokens() {
* @return array
*/
protected function getAliasTokens() {
- return array(
+ return [
'id' => 'contribution_id',
'payment_instrument' => 'payment_instrument_id',
'source' => 'contribution_source',
'status' => 'contribution_status_id',
'type' => 'financial_type_id',
- );
+ ];
}
/**
@@ -97,8 +97,7 @@ public function __construct() {
* @return bool
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
- return
- !empty($processor->context['actionMapping'])
+ return !empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_contribution';
}
@@ -129,7 +128,7 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
$fieldValue = isset($actionSearchResult->{"contrib_$field"}) ? $actionSearchResult->{"contrib_$field"} : NULL;
$aliasTokens = $this->getAliasTokens();
- if (in_array($field, array('total_amount', 'fee_amount', 'net_amount'))) {
+ if (in_array($field, ['total_amount', 'fee_amount', 'net_amount'])) {
return $row->format('text/plain')->tokens($entity, $field,
\CRM_Utils_Money::format($fieldValue, $actionSearchResult->contrib_currency));
}
diff --git a/CRM/Contribute/xml/Menu/Contribute.xml b/CRM/Contribute/xml/Menu/Contribute.xml
index 66b318e5f3a5..548902dbc07c 100644
--- a/CRM/Contribute/xml/Menu/Contribute.xml
+++ b/CRM/Contribute/xml/Menu/Contribute.xml
@@ -323,4 +323,16 @@
CRM_Contribute_Page_AJAX::getSoftContributionRowsaccess CiviCRM
+
+ civicrm/contribute/contributionrecur-payments
+ Recurring Contribution's Payments
+ CRM_Contribute_Page_ContributionRecurPayments
+ access CiviContribute
+
+
+ civicrm/membership/recurring-contributions
+ Membership Recurring Contributions
+ CRM_Member_Page_RecurringContributions
+ access CiviContribute
+
diff --git a/CRM/Core/Action.php b/CRM/Core/Action.php
index 8be4c9f4e549..f93583590f0f 100644
--- a/CRM/Core/Action.php
+++ b/CRM/Core/Action.php
@@ -1,9 +1,9 @@
self::ADD,
'update' => self::UPDATE,
'view' => self::VIEW,
@@ -95,14 +95,14 @@ class CRM_Core_Action {
'revert' => self::REVERT,
'close' => self::CLOSE,
'reopen' => self::REOPEN,
- );
+ ];
/**
* The flipped version of the names array, initialized when used
*
* @var array
*/
- static $_description;
+ public static $_description;
/**
* Called by the request object to translate a string into a mask.
@@ -216,7 +216,7 @@ public static function formLink(
// make links indexed sequentially instead of by bitmask
// otherwise it's next to impossible to reliably add new ones
- $seqLinks = array();
+ $seqLinks = [];
foreach ($links as $bit => $link) {
$link['bit'] = $bit;
$seqLinks[] = $link;
@@ -226,7 +226,7 @@ public static function formLink(
CRM_Utils_Hook::links($op, $objectName, $objectId, $seqLinks, $mask, $values);
}
- $url = array();
+ $url = [];
foreach ($seqLinks as $i => $link) {
if (!$mask || !array_key_exists('bit', $link) || ($mask & $link['bit'])) {
@@ -298,6 +298,65 @@ public static function formLink(
return $result;
}
+ /**
+ * Given a set of links and a mask, return a filtered (by mask) array containing the final links with parsed values
+ * and calling hooks as appropriate.
+ * Use this when passing a set of action links to the API or to the form without adding html formatting.
+ *
+ * @param array $links
+ * The set of link items.
+ * @param int $mask
+ * The mask to be used. a null mask means all items.
+ * @param array $values
+ * The array of values for parameter substitution in the link items.
+ * @param null $op
+ * @param null $objectName
+ * @param int $objectId
+ *
+ * @return array|null
+ * The array describing each link
+ */
+ public static function filterLinks(
+ $links,
+ $mask,
+ $values,
+ $op = NULL,
+ $objectName = NULL,
+ $objectId = NULL
+ ) {
+ if (empty($links)) {
+ return NULL;
+ }
+
+ // make links indexed sequentially instead of by bitmask
+ // otherwise it's next to impossible to reliably add new ones
+ $seqLinks = array();
+ foreach ($links as $bit => $link) {
+ $link['bit'] = $bit;
+ $seqLinks[] = $link;
+ }
+
+ if ($op && $objectName && $objectId) {
+ CRM_Utils_Hook::links($op, $objectName, $objectId, $seqLinks, $mask, $values);
+ }
+
+ foreach ($seqLinks as $i => $link) {
+ if (!$mask || !array_key_exists('bit', $link) || ($mask & $link['bit'])) {
+ $seqLinks[$i]['extra'] = isset($link['extra']) ? self::replace($link['extra'], $values) : NULL;
+
+ if (isset($link['qs']) && !CRM_Utils_System::isNull($link['qs'])) {
+ $seqLinks[$i]['url'] = self::replace($link['url'], $values);
+ $seqLinks[$i]['qs'] = self::replace($link['qs'], $values);
+ }
+ }
+ else {
+ unset($seqLinks[$i]);
+ }
+ }
+
+ return $seqLinks;
+ }
+
/**
* Given a string and an array of values, substitute the real values
* in the placeholder in the str in the CiviCRM format
diff --git a/CRM/Core/BAO/ActionLog.php b/CRM/Core/BAO/ActionLog.php
index 91538012dc78..2d8532e1f9e6 100644
--- a/CRM/Core/BAO/ActionLog.php
+++ b/CRM/Core/BAO/ActionLog.php
@@ -1,9 +1,9 @@
$_action_mapping[$filters['id']],
- );
+ ];
}
else {
throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
@@ -84,11 +84,11 @@ public static function getMapping($id) {
* @throws CRM_Core_Exception
*/
public static function getAllEntityValueLabels() {
- $entityValueLabels = array();
+ $entityValueLabels = [];
foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
/** @var \Civi\ActionSchedule\Mapping $mapping */
$entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
- $valueLabel = array('- ' . strtolower($mapping->getValueHeader()) . ' -');
+ $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
$entityValueLabels[$mapping->getId()] = $valueLabel + $entityValueLabels[$mapping->getId()];
}
return $entityValueLabels;
@@ -102,10 +102,10 @@ public static function getAllEntityValueLabels() {
*/
public static function getAllEntityStatusLabels() {
$entityValueLabels = self::getAllEntityValueLabels();
- $entityStatusLabels = array();
+ $entityStatusLabels = [];
foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
/** @var \Civi\ActionSchedule\Mapping $mapping */
- $statusLabel = array('- ' . strtolower($mapping->getStatusHeader()) . ' -');
+ $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
$entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
$vval = $statusLabel + $mapping->getStatusLabels($kkey);
@@ -146,21 +146,21 @@ public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filt
FROM civicrm_action_schedule cas
";
- $queryParams = array();
+ $queryParams = [];
$where = " WHERE 1 ";
if ($filterMapping and $filterValue) {
$where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
- $queryParams[1] = array($filterValue, 'Integer');
- $queryParams[2] = array($filterMapping->getId(), 'String');
+ $queryParams[1] = [$filterValue, 'Integer'];
+ $queryParams[2] = [$filterMapping->getId(), 'String'];
}
$where .= " AND cas.used_for IS NULL";
$query .= $where;
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
while ($dao->fetch()) {
/** @var Civi\ActionSchedule\Mapping $filterMapping */
- $filterMapping = CRM_Utils_Array::first(self::getMappings(array(
+ $filterMapping = CRM_Utils_Array::first(self::getMappings([
'id' => $dao->mapping_id,
- )));
+ ]));
$list[$dao->id]['id'] = $dao->id;
$list[$dao->id]['title'] = $dao->title;
$list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
@@ -194,7 +194,7 @@ public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filt
*
* @return CRM_Core_DAO_ActionSchedule
*/
- public static function add(&$params, $ids = array()) {
+ public static function add(&$params, $ids = []) {
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->copyValues($params);
@@ -259,8 +259,8 @@ public static function del($id) {
* @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) {
return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
@@ -273,9 +273,9 @@ public static function setIsActive($id, $is_active) {
* @throws CRM_Core_Exception
*/
public static function sendMailings($mappingID, $now) {
- $mapping = CRM_Utils_Array::first(self::getMappings(array(
+ $mapping = CRM_Utils_Array::first(self::getMappings([
'id' => $mappingID,
- )));
+ ]));
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->mapping_id = $mappingID;
@@ -285,7 +285,7 @@ public static function sendMailings($mappingID, $now) {
while ($actionSchedule->fetch()) {
$query = CRM_Core_BAO_ActionSchedule::prepareMailingQuery($mapping, $actionSchedule);
$dao = CRM_Core_DAO::executeQuery($query,
- array(1 => array($actionSchedule->id, 'Integer'))
+ [1 => [$actionSchedule->id, 'Integer']]
);
$multilingual = CRM_Core_I18n::isMultilingual();
@@ -296,7 +296,7 @@ public static function sendMailings($mappingID, $now) {
CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
}
- $errors = array();
+ $errors = [];
try {
$tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
$tokenProcessor->addRow()
@@ -322,12 +322,12 @@ public static function sendMailings($mappingID, $now) {
}
// update action log record
- $logParams = array(
+ $logParams = [
'id' => $dao->reminderID,
'is_error' => !empty($errors),
'message' => empty($errors) ? "null" : implode(' ', $errors),
'action_date_time' => $now,
- );
+ ];
CRM_Core_BAO_ActionLog::create($logParams);
}
@@ -342,7 +342,7 @@ public static function sendMailings($mappingID, $now) {
*
* @throws API_Exception
*/
- public static function buildRecipientContacts($mappingID, $now, $params = array()) {
+ public static function buildRecipientContacts($mappingID, $now, $params = []) {
$actionSchedule = new CRM_Core_DAO_ActionSchedule();
$actionSchedule->mapping_id = $mappingID;
$actionSchedule->is_active = 1;
@@ -353,9 +353,9 @@ public static function buildRecipientContacts($mappingID, $now, $params = array(
while ($actionSchedule->fetch()) {
/** @var \Civi\ActionSchedule\Mapping $mapping */
- $mapping = CRM_Utils_Array::first(self::getMappings(array(
+ $mapping = CRM_Utils_Array::first(self::getMappings([
'id' => $mappingID,
- )));
+ ]));
$builder = new \Civi\ActionSchedule\RecipientBuilder($now, $actionSchedule, $mapping);
$builder->build();
}
@@ -367,7 +367,7 @@ public static function buildRecipientContacts($mappingID, $now, $params = array(
*
* @return array
*/
- public static function processQueue($now = NULL, $params = array()) {
+ public static function processQueue($now = NULL, $params = []) {
$now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
$mappings = CRM_Core_BAO_ActionSchedule::getMappings();
@@ -376,10 +376,10 @@ public static function processQueue($now = NULL, $params = array()) {
CRM_Core_BAO_ActionSchedule::sendMailings($mappingID, $now);
}
- $result = array(
+ $result = [
'is_error' => 0,
'messages' => ts('Sent all scheduled reminders successfully'),
- );
+ ];
return $result;
}
@@ -394,10 +394,10 @@ public static function isConfigured($id, $mappingID) {
WHERE mapping_id = %1 AND
entity_value = %2";
- $params = array(
- 1 => array($mappingID, 'String'),
- 2 => array($id, 'Integer'),
- );
+ $params = [
+ 1 => [$mappingID, 'String'],
+ 2 => [$id, 'Integer'],
+ ];
return CRM_Core_DAO::singleValueQuery($queryString, $params);
}
@@ -409,13 +409,13 @@ public static function isConfigured($id, $mappingID) {
*/
public static function getRecipientListing($mappingID, $recipientType) {
if (!$mappingID) {
- return array();
+ return [];
}
/** @var \Civi\ActionSchedule\Mapping $mapping */
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => $mappingID,
- )));
+ ]));
return $mapping->getRecipientListing($recipientType);
}
@@ -475,7 +475,7 @@ protected static function createMailingActivity($tokenRow, $mapping, $contactID,
= CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
}
- $activityParams = array(
+ $activityParams = [
'subject' => $tokenRow->render('subject'),
'details' => $tokenRow->render('body_html'),
'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID,
@@ -486,13 +486,13 @@ protected static function createMailingActivity($tokenRow, $mapping, $contactID,
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
'activity_type_id' => $activityTypeID,
'source_record_id' => $entityID,
- );
+ ];
// @todo use api, remove all the above wrangling
$activity = CRM_Activity_BAO_Activity::create($activityParams);
//file reminder on case if source activity is a case activity
if (!empty($caseID)) {
- $caseActivityParams = array();
+ $caseActivityParams = [];
$caseActivityParams['case_id'] = $caseID;
$caseActivityParams['activity_id'] = $activity->id;
CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
@@ -511,13 +511,13 @@ protected static function prepareMailingQuery($mapping, $actionSchedule) {
->select("e.id as entityID, e.*")
->where("reminder.action_schedule_id = #casActionScheduleId")
->where("reminder.action_date_time IS NULL")
- ->param(array(
+ ->param([
'casActionScheduleId' => $actionSchedule->id,
'casMailingJoinType' => ($actionSchedule->limit_to == 0) ? 'LEFT JOIN' : 'INNER JOIN',
'casMappingId' => $mapping->getId(),
'casMappingEntity' => $mapping->getEntity(),
'casEntityJoinExpr' => 'e.id = reminder.entity_id',
- ));
+ ]);
if ($actionSchedule->limit_to == 0) {
$select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
@@ -543,7 +543,7 @@ protected static function prepareMailingQuery($mapping, $actionSchedule) {
protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
$toPhoneNumber = self::pickSmsPhoneNumber($toContactID);
if (!$toPhoneNumber) {
- return array("sms_phone_missing" => "Couldn't find recipient's phone number.");
+ return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
}
$messageSubject = $tokenRow->render('subject');
@@ -551,23 +551,20 @@ protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID') ? $session->get('userID') : $tokenRow->context['contactId'];
- $smsParams = array(
+ $smsParams = [
'To' => $toPhoneNumber,
'provider_id' => $schedule->sms_provider_id,
'activity_subject' => $messageSubject,
- );
- $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
- 'SMS',
- 'name'
- );
- $activityParams = array(
+ ];
+ $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
+ $activityParams = [
'source_contact_id' => $userID,
'activity_type_id' => $activityTypeID,
'activity_date_time' => date('YmdHis'),
'subject' => $messageSubject,
'details' => $sms_body_text,
- 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
- );
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
+ ];
$activity = CRM_Activity_BAO_Activity::create($activityParams);
@@ -578,7 +575,7 @@ protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
$userID
);
- return array();
+ return [];
}
/**
@@ -606,7 +603,7 @@ protected static function pickFromEmail($actionSchedule) {
protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
$toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID);
if (!$toEmail) {
- return array("email_missing" => "Couldn't find recipient's email address.");
+ return ["email_missing" => "Couldn't find recipient's email address."];
}
$body_text = $tokenRow->render('body_text');
@@ -616,7 +613,7 @@ protected static function sendReminderEmail($tokenRow, $schedule, $toContactID)
}
// set up the parameters for CRM_Utils_Mail::send
- $mailParams = array(
+ $mailParams = [
'groupName' => 'Scheduled Reminder Sender',
'from' => self::pickFromEmail($schedule),
'toName' => $tokenRow->context['contact']['display_name'],
@@ -624,7 +621,7 @@ protected static function sendReminderEmail($tokenRow, $schedule, $toContactID)
'subject' => $tokenRow->render('subject'),
'entity' => 'action_schedule',
'entity_id' => $schedule->id,
- );
+ ];
if (!$body_html || $tokenRow->context['contact']['preferred_mail_format'] == 'Text' ||
$tokenRow->context['contact']['preferred_mail_format'] == 'Both'
@@ -640,10 +637,10 @@ protected static function sendReminderEmail($tokenRow, $schedule, $toContactID)
}
$result = CRM_Utils_Mail::send($mailParams);
if (!$result || is_a($result, 'PEAR_Error')) {
- return array('email_fail' => 'Failed to send message');
+ return ['email_fail' => 'Failed to send message'];
}
- return array();
+ return [];
}
/**
@@ -652,12 +649,12 @@ protected static function sendReminderEmail($tokenRow, $schedule, $toContactID)
* @return \Civi\Token\TokenProcessor
*/
protected static function createTokenProcessor($schedule, $mapping) {
- $tp = new \Civi\Token\TokenProcessor(\Civi\Core\Container::singleton()->get('dispatcher'), array(
+ $tp = new \Civi\Token\TokenProcessor(\Civi\Core\Container::singleton()->get('dispatcher'), [
'controller' => __CLASS__,
'actionSchedule' => $schedule,
'actionMapping' => $mapping,
'smarty' => TRUE,
- ));
+ ]);
$tp->addMessage('body_text', $schedule->body_text, 'text/plain');
$tp->addMessage('body_html', $schedule->body_html, 'text/html');
$tp->addMessage('sms_body_text', $schedule->sms_body_text, 'text/plain');
@@ -673,11 +670,11 @@ protected static function createTokenProcessor($schedule, $mapping) {
* @return NULL|string
*/
protected static function pickSmsPhoneNumber($smsToContactId) {
- $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', array(
+ $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', [
'is_deceased' => 0,
'is_deleted' => 0,
'do_not_sms' => 0,
- ));
+ ]);
//to get primary mobile ph,if not get a first mobile phONE
if (!empty($toPhoneNumbers)) {
$toPhoneNumberDetails = reset($toPhoneNumbers);
@@ -694,10 +691,10 @@ protected static function pickSmsPhoneNumber($smsToContactId) {
* array(mixed $value => string $label).
*/
public static function getAdditionalRecipients() {
- return array(
+ return [
'manual' => ts('Choose Recipient(s)'),
'group' => ts('Select Group'),
- );
+ ];
}
}
diff --git a/CRM/Core/BAO/Address.php b/CRM/Core/BAO/Address.php
index df274fd78888..3ce2b0cdbb2b 100644
--- a/CRM/Core/BAO/Address.php
+++ b/CRM/Core/BAO/Address.php
@@ -1,9 +1,9 @@
$params['entity_table'],
'entity_id' => $params['entity_id'],
- );
+ ];
$addresses = self::allEntityAddress($entityElements);
}
$isPrimary = $isBilling = TRUE;
- $blocks = array();
+ $blocks = [];
foreach ($params['address'] as $key => $value) {
if (!is_array($value)) {
continue;
@@ -92,7 +92,7 @@ public static function create(&$params, $fixAddress = TRUE, $entity = NULL) {
// $updateBlankLocInfo will help take appropriate decision. CRM-5969
if (isset($value['id']) && !$addressExists && $updateBlankLocInfo) {
//delete the existing record
- CRM_Core_BAO_Block::blockDelete('Address', array('id' => $value['id']));
+ CRM_Core_BAO_Block::blockDelete('Address', ['id' => $value['id']]);
continue;
}
elseif (!$addressExists) {
@@ -134,7 +134,7 @@ public static function create(&$params, $fixAddress = TRUE, $entity = NULL) {
*
* @return CRM_Core_BAO_Address|null
*/
- public static function add(&$params, $fixAddress) {
+ public static function add(&$params, $fixAddress = FALSE) {
$address = new CRM_Core_DAO_Address();
$checkPermissions = isset($params['check_permissions']) ? $params['check_permissions'] : TRUE;
@@ -152,6 +152,11 @@ public static function add(&$params, $fixAddress) {
CRM_Core_BAO_Block::handlePrimary($params, get_class());
}
+ // (prevent chaining 1 and 3) CRM-21214
+ if (isset($params['master_id']) && !CRM_Utils_System::isNull($params['master_id'])) {
+ self::fixSharedAddress($params);
+ }
+
$address->copyValues($params);
$address->save();
@@ -171,15 +176,11 @@ public static function add(&$params, $fixAddress) {
CRM_Core_BAO_CustomValueTable::store($addressCustom, 'civicrm_address', $address->id);
}
- //call the function to sync shared address
+ // call the function to sync shared address and create relationships
+ // if address is already shared, share master_id with all children and update relationships accordingly
+ // (prevent chaining 2) CRM-21214
self::processSharedAddress($address->id, $params);
- // call the function to create shared relationships
- // we only create create relationship if address is shared by Individual
- if (!CRM_Utils_System::isNull($address->master_id)) {
- self::processSharedAddressRelationship($address->master_id, $params);
- }
-
// lets call the post hook only after we've done all the follow on processing
CRM_Utils_Hook::post($hook, 'Address', $address->id, $address);
}
@@ -197,7 +198,7 @@ public static function fixAddress(&$params) {
if (!empty($params['billing_street_address'])) {
//Check address is coming from online contribution / registration page
//Fixed :CRM-5076
- $billing = array(
+ $billing = [
'street_address' => 'billing_street_address',
'city' => 'billing_city',
'postal_code' => 'billing_postal_code',
@@ -205,7 +206,7 @@ public static function fixAddress(&$params) {
'state_province_id' => 'billing_state_province_id',
'country' => 'billing_country',
'country_id' => 'billing_country_id',
- );
+ ];
foreach ($billing as $key => $val) {
if ($value = CRM_Utils_Array::value($val, $params)) {
@@ -341,51 +342,41 @@ public static function fixAddress(&$params) {
$params['country'] = CRM_Core_PseudoConstant::country($params['country_id']);
}
- $config = CRM_Core_Config::singleton();
-
$asp = Civi::settings()->get('address_standardization_provider');
// clean up the address via USPS web services if enabled
if ($asp === 'USPS' &&
$params['country_id'] == 1228
) {
CRM_Utils_Address_USPS::checkAddress($params);
+ }
+ // do street parsing again if enabled, since street address might have changed
+ $parseStreetAddress = CRM_Utils_Array::value(
+ 'street_address_parsing',
+ CRM_Core_BAO_Setting::valueOptions(
+ CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'address_options'
+ ),
+ FALSE
+ );
- // do street parsing again if enabled, since street address might have changed
- $parseStreetAddress = CRM_Utils_Array::value(
- 'street_address_parsing',
- CRM_Core_BAO_Setting::valueOptions(
- CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
- 'address_options'
- ),
- FALSE
- );
-
- if ($parseStreetAddress && !empty($params['street_address'])) {
- foreach (array(
- 'street_number',
- 'street_name',
- 'street_unit',
- 'street_number_suffix',
- ) as $fld) {
- unset($params[$fld]);
- }
- // main parse string.
- $parseString = CRM_Utils_Array::value('street_address', $params);
- $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
-
- // merge parse address in to main address block.
- $params = array_merge($params, $parsedFields);
+ if ($parseStreetAddress && !empty($params['street_address'])) {
+ foreach (['street_number', 'street_name', 'street_unit', 'street_number_suffix'] as $fld) {
+ unset($params[$fld]);
}
- }
+ // main parse string.
+ $parseString = CRM_Utils_Array::value('street_address', $params);
+ $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
- // check if geocode should be skipped (can be forced with an optional parameter through the api)
- $skip_geocode = (isset($params['skip_geocode']) && $params['skip_geocode']) ? TRUE : FALSE;
+ // merge parse address in to main address block.
+ $params = array_merge($params, $parsedFields);
+ }
- // add latitude and longitude and format address if needed
- if (!$skip_geocode && !empty($config->geocodeMethod) && ($config->geocodeMethod != 'CRM_Utils_Geocode_OpenStreetMaps') && empty($params['manual_geo_code'])) {
- $class = $config->geocodeMethod;
- $class::format($params);
+ // skip_geocode is an optional parameter through the api.
+ // manual_geo_code is on the contact edit form. They do the same thing....
+ if (empty($params['skip_geocode']) && empty($params['manual_geo_code'])) {
+ self::addGeocoderData($params);
}
+
}
/**
@@ -404,7 +395,7 @@ public static function dataExists(&$params) {
$config = CRM_Core_Config::singleton();
foreach ($params as $name => $value) {
- if (in_array($name, array(
+ if (in_array($name, [
'is_primary',
'location_type_id',
'id',
@@ -412,7 +403,7 @@ public static function dataExists(&$params) {
'is_billing',
'display',
'master_id',
- ))) {
+ ])) {
continue;
}
elseif (!CRM_Utils_System::isNull($value)) {
@@ -466,14 +457,14 @@ public static function &getValues($entityBlock, $microformat = FALSE, $fieldName
if (empty($entityBlock)) {
return NULL;
}
- $addresses = array();
+ $addresses = [];
$address = new CRM_Core_BAO_Address();
if (empty($entityBlock['entity_table'])) {
$address->$fieldName = CRM_Utils_Array::value($fieldName, $entityBlock);
}
else {
- $addressIds = array();
+ $addressIds = [];
$addressIds = self::allEntityAddress($entityBlock);
if (!empty($addressIds[1])) {
@@ -498,19 +489,14 @@ public static function &getValues($entityBlock, $microformat = FALSE, $fieldName
while ($address->fetch()) {
// deprecate reference.
if ($count > 1) {
- foreach (array(
- 'state',
- 'state_name',
- 'country',
- 'world_region',
- ) as $fld) {
+ foreach (['state', 'state_name', 'country', 'world_region'] as $fld) {
if (isset($address->$fld)) {
unset($address->$fld);
}
}
}
$stree = $address->street_address;
- $values = array();
+ $values = [];
CRM_Core_DAO::storeValues($address, $values);
// add state and country information: CRM-369
@@ -536,7 +522,7 @@ public static function &getValues($entityBlock, $microformat = FALSE, $fieldName
$values['display'] = $address->display;
$values['display_text'] = $address->display_text;
- if (is_numeric($address->master_id)) {
+ if (isset($address->master_id) && !CRM_Utils_System::isNull($address->master_id)) {
$values['use_shared_address'] = 1;
}
@@ -561,7 +547,7 @@ public static function &getValues($entityBlock, $microformat = FALSE, $fieldName
* Unexplained parameter that I've always wondered about.
*/
public function addDisplay($microformat = FALSE) {
- $fields = array(
+ $fields = [
// added this for CRM 1200
'address_id' => $this->id,
// CRM-4003
@@ -577,7 +563,7 @@ public function addDisplay($microformat = FALSE) {
'postal_code_suffix' => isset($this->postal_code_suffix) ? $this->postal_code_suffix : "",
'country' => isset($this->country) ? $this->country : "",
'world_region' => isset($this->world_region) ? $this->world_region : "",
- );
+ ];
if (isset($this->county_id) && $this->county_id) {
$fields['county'] = CRM_Core_PseudoConstant::county($this->county_id);
@@ -611,9 +597,9 @@ public static function allAddress($id, $updateBlankLocInfo = FALSE) {
FROM civicrm_contact, civicrm_address
WHERE civicrm_address.contact_id = civicrm_contact.id AND civicrm_contact.id = %1
ORDER BY civicrm_address.is_primary DESC, address_id ASC";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
- $addresses = array();
+ $addresses = [];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
@@ -638,7 +624,7 @@ public static function allAddress($id, $updateBlankLocInfo = FALSE) {
* the array of adrress data
*/
public static function allEntityAddress(&$entityElements) {
- $addresses = array();
+ $addresses = [];
if (empty($entityElements)) {
return $addresses;
}
@@ -655,7 +641,7 @@ public static function allEntityAddress(&$entityElements) {
AND ltype.id = civicrm_address.location_type_id
ORDER BY civicrm_address.is_primary DESC, civicrm_address.location_type_id DESC, address_id ASC ";
- $params = array(1 => array($entityId, 'Integer'));
+ $params = [1 => [$entityId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$locationCount = 1;
while ($dao->fetch()) {
@@ -678,21 +664,21 @@ public static function addressSequence() {
$countryState = $cityPostal = FALSE;
foreach ($addressSequence as $key => $field) {
if (
- in_array($field, array('country', 'state_province')) &&
+ in_array($field, ['country', 'state_province']) &&
!$countryState
) {
$countryState = TRUE;
$addressSequence[$key] = 'country_state_province';
}
elseif (
- in_array($field, array('city', 'postal_code')) &&
+ in_array($field, ['city', 'postal_code']) &&
!$cityPostal
) {
$cityPostal = TRUE;
$addressSequence[$key] = 'city_postal_code';
}
elseif (
- in_array($field, array('country', 'state_province', 'city', 'postal_code'))
+ in_array($field, ['country', 'state_province', 'city', 'postal_code'])
) {
unset($addressSequence[$key]);
}
@@ -718,31 +704,17 @@ public static function addressSequence() {
* parsed fields values.
*/
public static function parseStreetAddress($streetAddress, $locale = NULL) {
- $config = CRM_Core_Config::singleton();
-
- /* locales supported include:
- * en_US - http://pe.usps.com/cpim/ftp/pubs/pub28/pub28.pdf
- * en_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp
- * fr_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-f.asp
- * NB: common use of comma after street number also supported
- * default is en_US
- */
-
- $supportedLocalesForParsing = array('en_US', 'en_CA', 'fr_CA');
- if (!$locale) {
- $locale = $config->lcMessages;
- }
- // as different locale explicitly requested but is not available, display warning message and set $locale = 'en_US'
- if (!in_array($locale, $supportedLocalesForParsing)) {
- CRM_Core_Session::setStatus(ts('Unsupported locale specified to parseStreetAddress: %1. Proceeding with en_US locale.', array(1 => $locale)), ts('Unsupported Locale'), 'alert');
+ // use 'en_US' for address parsing if the requested locale is not supported.
+ if (!self::isSupportedParsingLocale($locale)) {
$locale = 'en_US';
}
- $emptyParseFields = $parseFields = array(
+
+ $emptyParseFields = $parseFields = [
'street_name' => '',
'street_unit' => '',
'street_number' => '',
'street_number_suffix' => '',
- );
+ ];
if (empty($streetAddress)) {
return $parseFields;
@@ -750,11 +722,9 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
$streetAddress = trim($streetAddress);
- $matches = array();
- if (in_array($locale, array(
- 'en_CA',
- 'fr_CA',
- )) && preg_match('/^([A-Za-z0-9]+)[ ]*\-[ ]*/', $streetAddress, $matches)
+ $matches = [];
+ if (in_array($locale, ['en_CA', 'fr_CA'])
+ && preg_match('/^([A-Za-z0-9]+)[ ]*\-[ ]*/', $streetAddress, $matches)
) {
$parseFields['street_unit'] = $matches[1];
// unset from rest of street address
@@ -762,7 +732,7 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
}
// get street number and suffix.
- $matches = array();
+ $matches = [];
//alter street number/suffix handling so that we accept -digit
if (preg_match('/^[A-Za-z0-9]+([\S]+)/', $streetAddress, $matches)) {
// check that $matches[0] is numeric, else assume no street number
@@ -770,7 +740,7 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
$streetNumAndSuffix = $matches[0];
// get street number.
- $matches = array();
+ $matches = [];
if (preg_match('/^(\d+)/', $streetNumAndSuffix, $matches)) {
$parseFields['street_number'] = $matches[0];
$suffix = preg_replace('/^(\d+)/', '', $streetNumAndSuffix);
@@ -789,8 +759,13 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
$streetAddress = trim($streetAddress);
}
+ // If street number is too large, we cannot store it.
+ if ($parseFields['street_number'] > CRM_Utils_Type::INT_MAX) {
+ return $emptyParseFields;
+ }
+
// suffix might be like 1/2
- $matches = array();
+ $matches = [];
if (preg_match('/^\d\/\d/', $streetAddress, $matches)) {
$parseFields['street_number_suffix'] .= $matches[0];
@@ -801,7 +776,7 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
// now get the street unit.
// supportable street unit formats.
- $streetUnitFormats = array(
+ $streetUnitFormats = [
'APT',
'APARTMENT',
'BSMT',
@@ -842,19 +817,19 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
'SUITE',
'UNIT',
'#',
- );
+ ];
// overwriting $streetUnitFormats for 'en_CA' and 'fr_CA' locale
- if (in_array($locale, array(
+ if (in_array($locale, [
'en_CA',
'fr_CA',
- ))) {
- $streetUnitFormats = array('APT', 'APP', 'SUITE', 'BUREAU', 'UNIT');
+ ])) {
+ $streetUnitFormats = ['APT', 'APP', 'SUITE', 'BUREAU', 'UNIT'];
}
//@todo per CRM-14459 this regex picks up words with the string in them - e.g APT picks up
//Captain - presuming fixing regex (& adding test) to ensure a-z does not preced string will fix
$streetUnitPreg = '/(' . implode('|\s', $streetUnitFormats) . ')(.+)?/i';
- $matches = array();
+ $matches = [];
if (preg_match($streetUnitPreg, $streetAddress, $matches)) {
$parseFields['street_unit'] = trim($matches[0]);
$streetAddress = str_replace($matches[0], '', $streetAddress);
@@ -880,6 +855,38 @@ public static function parseStreetAddress($streetAddress, $locale = NULL) {
return $parseFields;
}
+ /**
+ * Determines if the specified locale is
+ * supported by address parsing.
+ * If no locale is specified then it
+ * will check the default configured locale.
+ *
+ * locales supported include:
+ * en_US - http://pe.usps.com/cpim/ftp/pubs/pub28/pub28.pdf
+ * en_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp
+ * fr_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-f.asp
+ * NB: common use of comma after street number also supported
+ *
+ * @param string $locale
+ * The locale to be checked
+ *
+ * @return bool
+ */
+ public static function isSupportedParsingLocale($locale = NULL) {
+ if (!$locale) {
+ $config = CRM_Core_Config::singleton();
+ $locale = $config->lcMessages;
+ }
+
+ $parsingSupportedLocales = ['en_US', 'en_CA', 'fr_CA'];
+
+ if (in_array($locale, $parsingSupportedLocales)) {
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
/**
* Validate the address fields based on the address options enabled.
* in the Address Settings
@@ -920,7 +927,7 @@ public static function validateAddressOptions($fields) {
*/
public static function checkContactSharedAddress($addressId) {
$query = 'SELECT count(id) FROM civicrm_address WHERE master_id = %1';
- return CRM_Core_DAO::singleValueQuery($query, array(1 => array($addressId, 'Integer')));
+ return CRM_Core_DAO::singleValueQuery($query, [1 => [$addressId, 'Integer']]);
}
/**
@@ -937,7 +944,7 @@ public static function checkContactSharedAddressFields(&$fields, $contactId) {
return;
}
- $sharedLocations = array();
+ $sharedLocations = [];
$query = "
SELECT is_primary,
@@ -946,7 +953,7 @@ public static function checkContactSharedAddressFields(&$fields, $contactId) {
WHERE contact_id = %1
AND master_id IS NOT NULL";
- $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($contactId, 'Positive')));
+ $dao = CRM_Core_DAO::executeQuery($query, [1 => [$contactId, 'Positive']]);
while ($dao->fetch()) {
$sharedLocations[$dao->location_type_id] = $dao->location_type_id;
if ($dao->is_primary) {
@@ -959,7 +966,7 @@ public static function checkContactSharedAddressFields(&$fields, $contactId) {
return;
}
- $addressFields = array(
+ $addressFields = [
'city',
'county',
'country',
@@ -973,7 +980,7 @@ public static function checkContactSharedAddressFields(&$fields, $contactId) {
'supplemental_address_1',
'supplemental_address_2',
'supplemental_address_3',
- );
+ ];
foreach ($fields as $name => & $values) {
if (!is_array($values) || empty($values)) {
@@ -995,6 +1002,27 @@ public static function checkContactSharedAddressFields(&$fields, $contactId) {
}
}
+ /**
+ * Fix the shared address if address is already shared
+ * or if address will be shared with itself.
+ *
+ * @param array $params
+ * Associated array of address params.
+ */
+ public static function fixSharedAddress(&$params) {
+ // if address master address is shared, use its master (prevent chaining 1) CRM-21214
+ $masterMasterId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Address', $params['master_id'], 'master_id');
+ if ($masterMasterId > 0) {
+ $params['master_id'] = $masterMasterId;
+ }
+
+ // prevent an endless chain between two shared addresses (prevent chaining 3) CRM-21214
+ if (CRM_Utils_Array::value('id', $params) == $params['master_id']) {
+ $params['master_id'] = NULL;
+ CRM_Core_Session::setStatus(ts("You can't connect an address to itself"), '', 'warning');
+ }
+ }
+
/**
* Update the shared addresses if master address is modified.
*
@@ -1004,21 +1032,37 @@ public static function checkContactSharedAddressFields(&$fields, $contactId) {
* Associated array of address params.
*/
public static function processSharedAddress($addressId, $params) {
- $query = 'SELECT id FROM civicrm_address WHERE master_id = %1';
- $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($addressId, 'Integer')));
+ $query = 'SELECT id, contact_id FROM civicrm_address WHERE master_id = %1';
+ $dao = CRM_Core_DAO::executeQuery($query, [1 => [$addressId, 'Integer']]);
+
+ // Default to TRUE if not set to maintain api backward compatibility.
+ $createRelationship = isset($params['update_current_employer']) ? $params['update_current_employer'] : TRUE;
// unset contact id
- $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id', 'contact_id');
+ $skipFields = ['is_primary', 'location_type_id', 'is_billing', 'contact_id'];
+ if (isset($params['master_id']) && !CRM_Utils_System::isNull($params['master_id'])) {
+ if ($createRelationship) {
+ // call the function to create a relationship for the new shared address
+ self::processSharedAddressRelationship($params['master_id'], $params['contact_id']);
+ }
+ }
+ else {
+ // else no new shares will be created, only update shared addresses
+ $skipFields[] = 'master_id';
+ }
foreach ($skipFields as $value) {
unset($params[$value]);
}
$addressDAO = new CRM_Core_DAO_Address();
while ($dao->fetch()) {
+ // call the function to update the relationship
+ if ($createRelationship && isset($params['master_id']) && !CRM_Utils_System::isNull($params['master_id'])) {
+ self::processSharedAddressRelationship($params['master_id'], $dao->contact_id);
+ }
$addressDAO->copyValues($params);
$addressDAO->id = $dao->id;
$addressDAO->save();
- $addressDAO->free();
}
}
@@ -1028,7 +1072,7 @@ public static function processSharedAddress($addressId, $params) {
* Array[contact_id][contactDetails].
*/
public static function mergeSameAddress(&$rows) {
- $uniqueAddress = array();
+ $uniqueAddress = [];
foreach (array_keys($rows) as $rowID) {
// load complete address as array key
$address = trim($rows[$rowID]['street_address'])
@@ -1044,12 +1088,12 @@ public static function mergeSameAddress(&$rows) {
}
// CRM-15120
- $formatted = array(
+ $formatted = [
'first_name' => $rows[$rowID]['first_name'],
'individual_prefix' => $rows[$rowID]['individual_prefix'],
- );
+ ];
$format = Civi::settings()->get('display_name_format');
- $firstNameWithPrefix = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE);
+ $firstNameWithPrefix = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE);
$firstNameWithPrefix = trim($firstNameWithPrefix);
// fill uniqueAddress array with last/first name tree
@@ -1098,18 +1142,17 @@ public static function mergeSameAddress(&$rows) {
/**
* Create relationship between contacts who share an address.
*
- * Note that currently we create relationship only for Individual contacts
- * Individual + Household and Individual + Orgnization
+ * Note that currently we create relationship between
+ * Individual + Household and Individual + Organization
*
* @param int $masterAddressId
* Master address id.
- * @param array $params
- * Associated array of submitted values.
+ * @param int $currentContactId
+ * Current contact id.
*/
- public static function processSharedAddressRelationship($masterAddressId, $params) {
+ public static function processSharedAddressRelationship($masterAddressId, $currentContactId) {
// get the contact type of contact being edited / created
- $currentContactType = CRM_Contact_BAO_Contact::getContactType($params['contact_id']);
- $currentContactId = $params['contact_id'];
+ $currentContactType = CRM_Contact_BAO_Contact::getContactType($currentContactId);
// if current contact is not of type individual return
if ($currentContactType != 'Individual') {
@@ -1122,11 +1165,10 @@ public static function processSharedAddressRelationship($masterAddressId, $param
FROM civicrm_contact cc INNER JOIN civicrm_address ca ON cc.id = ca.contact_id
WHERE ca.id = %1';
- $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($masterAddressId, 'Integer')));
+ $dao = CRM_Core_DAO::executeQuery($query, [1 => [$masterAddressId, 'Integer']]);
$dao->fetch();
- // if current contact is not of type individual return, since we don't create relationship between
- // 2 individuals
+ // master address contact needs to be Household or Organization, otherwise return
if ($dao->contact_type == 'Individual') {
return;
}
@@ -1145,12 +1187,12 @@ public static function processSharedAddressRelationship($masterAddressId, $param
CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Household Member of'"));
}
- $relParam = array(
+ $relParam = [
'is_active' => TRUE,
'relationship_type_id' => $relTypeId,
'contact_id_a' => $currentContactId,
'contact_id_b' => $sharedContactId,
- );
+ ];
// If already there is a relationship record of $relParam criteria, avoid creating relationship again or else
// it will casue CRM-16588 as the Duplicate Relationship Exception will revert other contact field values on update
@@ -1197,10 +1239,10 @@ public static function setSharedAddressDeleteStatus($addressId = NULL, $contactI
WHERE ca1.contact_id = %1';
}
- $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($entityId, 'Integer')));
+ $dao = CRM_Core_DAO::executeQuery($query, [1 => [$entityId, 'Integer']]);
- $deleteStatus = array();
- $sharedContactList = array();
+ $deleteStatus = [];
+ $sharedContactList = [];
$statusMessage = NULL;
$addressCount = 0;
while ($dao->fetch()) {
@@ -1223,10 +1265,10 @@ public static function setSharedAddressDeleteStatus($addressId = NULL, $contactI
CRM_Core_Session::setStatus($statusMessage, '', 'info');
}
else {
- return array(
+ return [
'contactList' => $sharedContactList,
'count' => $addressCount,
- );
+ ];
}
}
@@ -1256,8 +1298,8 @@ public static function del($id) {
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
- $params = array();
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
+ $params = [];
// Special logic for fields whose options depend on context or properties
switch ($fieldName) {
// Filter state_province list based on chosen country or site defaults
@@ -1266,7 +1308,7 @@ public static function buildOptions($fieldName, $context = NULL, $props = array(
case 'state_province':
// change $fieldName to DB specific names.
$fieldName = 'state_province_id';
- if (empty($props['country_id'])) {
+ if (empty($props['country_id']) && $context !== 'validate') {
$config = CRM_Core_Config::singleton();
if (!empty($config->provinceLimit)) {
$props['country_id'] = $config->provinceLimit;
@@ -1275,7 +1317,7 @@ public static function buildOptions($fieldName, $context = NULL, $props = array(
$props['country_id'] = $config->defaultContactCountry;
}
}
- if (!empty($props['country_id']) && $context !== 'validate') {
+ if (!empty($props['country_id'])) {
$params['condition'] = 'country_id IN (' . implode(',', (array) $props['country_id']) . ')';
}
break;
@@ -1304,9 +1346,29 @@ public static function buildOptions($fieldName, $context = NULL, $props = array(
case 'world_region':
case 'worldregion':
case 'worldregion_id':
- return CRM_Core_PseudoConstant::worldRegion();
+ return CRM_Core_BAO_Country::buildOptions('region_id', $context, $props);
}
return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
}
+ /**
+ * Add data from the configured geocoding provider.
+ *
+ * Generally this means latitude & longitude data.
+ *
+ * @param array $params
+ * @return bool
+ * TRUE if params could be passed to a provider, else FALSE.
+ */
+ public static function addGeocoderData(&$params) {
+ try {
+ $provider = CRM_Utils_GeocodeProvider::getConfiguredProvider();
+ }
+ catch (CRM_Core_Exception $e) {
+ return FALSE;
+ }
+ $provider::format($params);
+ return TRUE;
+ }
+
}
diff --git a/CRM/Core/BAO/Block.php b/CRM/Core/BAO/Block.php
index f12aaa697894..d37b01d94e5d 100644
--- a/CRM/Core/BAO/Block.php
+++ b/CRM/Core/BAO/Block.php
@@ -1,9 +1,9 @@
array('email'),
- 'phone' => array('phone'),
- 'im' => array('name'),
- 'openid' => array('openid'),
- );
+ public static $requiredBlockFields = [
+ 'email' => ['email'],
+ 'phone' => ['phone'],
+ 'im' => ['name'],
+ 'openid' => ['openid'],
+ ];
/**
* Given the list of params in the params array, fetch the object
@@ -63,7 +64,7 @@ public static function &getValues($blockName, $params) {
$BAOString = 'CRM_Core_BAO_' . $blockName;
$block = new $BAOString();
- $blocks = array();
+ $blocks = [];
if (!isset($params['entity_table'])) {
$block->contact_id = $params['contact_id'];
if (!$block->contact_id) {
@@ -108,7 +109,7 @@ public static function retrieveBlock(&$block, $blockName) {
$block->find();
$count = 1;
- $blocks = array();
+ $blocks = [];
while ($block->fetch()) {
CRM_Core_DAO::storeValues($block, $blocks[$count]);
//unset is_primary after first block. Due to some bug in earlier version
@@ -178,7 +179,7 @@ public static function blockExists($blockName, &$params) {
*
*/
public static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
- $allBlocks = array();
+ $allBlocks = [];
$name = ucfirst($blockName);
if ($blockName == 'im') {
@@ -226,15 +227,15 @@ public static function create($blockName, &$params, $entity = NULL, $contactId =
$name = ucfirst($blockName);
$isPrimary = $isBilling = TRUE;
- $entityElements = $blocks = array();
+ $entityElements = $blocks = [];
$resetPrimaryId = NULL;
$primaryId = FALSE;
if ($entity) {
- $entityElements = array(
+ $entityElements = [
'entity_table' => $params['entity_table'],
'entity_id' => $params['entity_id'],
- );
+ ];
}
else {
$contactId = $params['contact_id'];
@@ -276,7 +277,6 @@ public static function create($blockName, &$params, $entity = NULL, $contactId =
$block->is_primary = FALSE;
$block->save();
}
- $block->free();
}
}
}
@@ -320,16 +320,16 @@ public static function create($blockName, &$params, $entity = NULL, $contactId =
// $updateBlankLocInfo will help take appropriate decision. CRM-5969
if (!empty($value['id']) && !$dataExists && $updateBlankLocInfo) {
//delete the existing record
- self::blockDelete($blockName, array('id' => $value['id']));
+ self::blockDelete($blockName, ['id' => $value['id']]);
continue;
}
elseif (!$dataExists) {
continue;
}
- $contactFields = array(
+ $contactFields = [
'contact_id' => $contactId,
'location_type_id' => CRM_Utils_Array::value('location_type_id', $value),
- );
+ ];
$contactFields['is_primary'] = 0;
if ($isPrimary && !empty($value['is_primary'])) {
@@ -422,11 +422,11 @@ public static function handlePrimary(&$params, $class) {
// if is_primary = 1
if (!empty($params['is_primary'])) {
$sql = "UPDATE $table SET is_primary = 0 WHERE contact_id = %1";
- $sqlParams = array(1 => array($contactId, 'Integer'));
+ $sqlParams = [1 => [$contactId, 'Integer']];
// we don't want to create unnecessary entries in the log_ tables so exclude the one we are working on
if (!empty($params['id'])) {
$sql .= " AND id <> %2";
- $sqlParams[2] = array($params['id'], 'Integer');
+ $sqlParams[2] = [$params['id'], 'Integer'];
}
CRM_Core_DAO::executeQuery($sql, $sqlParams);
return;
diff --git a/CRM/Core/BAO/CMSUser.php b/CRM/Core/BAO/CMSUser.php
index 3b23a1f7464a..36bb8bdb6f0c 100644
--- a/CRM/Core/BAO/CMSUser.php
+++ b/CRM/Core/BAO/CMSUser.php
@@ -1,9 +1,9 @@
"return showHideByValue('cms_create_account','','details','block','radio',false );",
- );
+ ];
$form->addElement('checkbox', 'cms_create_account', ts('Create an account?'), NULL, $extra);
$required = FALSE;
}
@@ -127,12 +127,12 @@ public static function buildForm(&$form, $gid, $emailPresent, $action = CRM_Core
$form->assign('isCMS', $required);
if (!$userID || $action & CRM_Core_Action::PREVIEW || $action & CRM_Core_Action::PROFILE) {
$form->add('text', 'cms_name', ts('Username'), NULL, $required);
- if (($isDrupal && !variable_get('user_email_verification', TRUE)) OR ($isJoomla) OR ($isWordPress)) {
+ if ($config->userSystem->isPasswordUserGenerated()) {
$form->add('password', 'cms_pass', ts('Password'));
$form->add('password', 'cms_confirm_pass', ts('Confirm Password'));
}
- $form->addFormRule(array('CRM_Core_BAO_CMSUser', 'formRule'), $form);
+ $form->addFormRule(['CRM_Core_BAO_CMSUser', 'formRule'], $form);
}
$showCMS = TRUE;
}
@@ -167,7 +167,7 @@ public static function formRule($fields, $files, $form) {
$isJoomla = ucfirst($config->userFramework) == 'Joomla' ? TRUE : FALSE;
$isWordPress = $config->userFramework == 'WordPress' ? TRUE : FALSE;
- $errors = array();
+ $errors = [];
if ($isDrupal || $isJoomla || $isWordPress) {
$emailName = NULL;
if (!empty($form->_bltID) && array_key_exists("email-{$form->_bltID}", $fields)) {
@@ -197,7 +197,7 @@ public static function formRule($fields, $files, $form) {
$errors[$emailName] = ts('Please specify a valid email address.');
}
- if (($isDrupal && !variable_get('user_email_verification', TRUE)) OR ($isJoomla) OR ($isWordPress)) {
+ if ($config->userSystem->isPasswordUserGenerated()) {
if (empty($fields['cms_pass']) ||
empty($fields['cms_confirm_pass'])
) {
@@ -213,11 +213,11 @@ public static function formRule($fields, $files, $form) {
}
// now check that the cms db does not have the user name and/or email
- if ($isDrupal OR $isJoomla OR $isWordPress) {
- $params = array(
+ if ($isDrupal or $isJoomla or $isWordPress) {
+ $params = [
'name' => $fields['cms_name'],
'mail' => $fields[$emailName],
- );
+ ];
}
$config->userSystem->checkUserNameEmailExists($params, $errors, $emailName);
diff --git a/CRM/Core/BAO/Cache.php b/CRM/Core/BAO/Cache.php
index 31c4355b6bea..13d59a848bdb 100644
--- a/CRM/Core/BAO/Cache.php
+++ b/CRM/Core/BAO/Cache.php
@@ -1,9 +1,9 @@
$cacheValue)
*/
- static $_cache = NULL;
+ public static $_cache = NULL;
/**
* Retrieve an item from the DB cache.
@@ -57,24 +65,34 @@ class CRM_Core_BAO_Cache extends CRM_Core_DAO_Cache {
*
* @return object
* The data if present in cache, else null
+ * @deprecated
*/
public static function &getItem($group, $path, $componentID = NULL) {
+ if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
+ $value = $adapter::getItem($group, $path, $componentID);
+ return $value;
+ }
+
if (self::$_cache === NULL) {
- self::$_cache = array();
+ self::$_cache = [];
}
$argString = "CRM_CT_{$group}_{$path}_{$componentID}";
if (!array_key_exists($argString, self::$_cache)) {
$cache = CRM_Utils_Cache::singleton();
- self::$_cache[$argString] = $cache->get($argString);
- if (!self::$_cache[$argString]) {
+ $cleanKey = self::cleanKey($argString);
+ self::$_cache[$argString] = $cache->get($cleanKey);
+ if (self::$_cache[$argString] === NULL) {
$table = self::getTableName();
$where = self::whereCache($group, $path, $componentID);
$rawData = CRM_Core_DAO::singleValueQuery("SELECT data FROM $table WHERE $where");
- $data = $rawData ? unserialize($rawData) : NULL;
+ $data = $rawData ? self::decode($rawData) : NULL;
self::$_cache[$argString] = $data;
- $cache->set($argString, self::$_cache[$argString]);
+ if ($data !== NULL) {
+ // Do not cache 'null' as that is most likely a cache miss & we shouldn't then cache it.
+ $cache->set($cleanKey, self::$_cache[$argString]);
+ }
}
}
return self::$_cache[$argString];
@@ -90,29 +108,34 @@ public static function &getItem($group, $path, $componentID = NULL) {
*
* @return object
* The data if present in cache, else null
+ * @deprecated
*/
public static function &getItems($group, $componentID = NULL) {
+ if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
+ return $adapter::getItems($group, $componentID);
+ }
+
if (self::$_cache === NULL) {
- self::$_cache = array();
+ self::$_cache = [];
}
$argString = "CRM_CT_CI_{$group}_{$componentID}";
if (!array_key_exists($argString, self::$_cache)) {
$cache = CRM_Utils_Cache::singleton();
- self::$_cache[$argString] = $cache->get($argString);
+ $cleanKey = self::cleanKey($argString);
+ self::$_cache[$argString] = $cache->get($cleanKey);
if (!self::$_cache[$argString]) {
$table = self::getTableName();
$where = self::whereCache($group, NULL, $componentID);
$dao = CRM_Core_DAO::executeQuery("SELECT path, data FROM $table WHERE $where");
- $result = array();
+ $result = [];
while ($dao->fetch()) {
- $result[$dao->path] = unserialize($dao->data);
+ $result[$dao->path] = self::decode($dao->data);
}
- $dao->free();
self::$_cache[$argString] = $result;
- $cache->set($argString, self::$_cache[$argString]);
+ $cache->set($cleanKey, self::$_cache[$argString]);
}
}
@@ -130,10 +153,15 @@ public static function &getItems($group, $componentID = NULL) {
* (required) The path under which this item is stored.
* @param int $componentID
* The optional component ID (so componenets can share the same name space).
+ * @deprecated
*/
public static function setItem(&$data, $group, $path, $componentID = NULL) {
+ if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
+ return $adapter::setItem($data, $group, $path, $componentID);
+ }
+
if (self::$_cache === NULL) {
- self::$_cache = array();
+ self::$_cache = [];
}
// get a lock so that multiple ajax requests on the same page
@@ -147,46 +175,45 @@ public static function setItem(&$data, $group, $path, $componentID = NULL) {
$table = self::getTableName();
$where = self::whereCache($group, $path, $componentID);
$dataExists = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM $table WHERE {$where}");
- $now = date('Y-m-d H:i:s'); // FIXME - Use SQL NOW() or CRM_Utils_Time?
- $dataSerialized = serialize($data);
+ // FIXME - Use SQL NOW() or CRM_Utils_Time?
+ $now = date('Y-m-d H:i:s');
+ $dataSerialized = self::encode($data);
// This table has a wonky index, so we cannot use REPLACE or
// "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
if ($dataExists) {
$sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
- $args = array(
- 1 => array($dataSerialized, 'String'),
- 2 => array($now, 'String'),
- );
+ $args = [
+ 1 => [$dataSerialized, 'String'],
+ 2 => [$now, 'String'],
+ ];
$dao = CRM_Core_DAO::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
}
else {
$insert = CRM_Utils_SQL_Insert::into($table)
- ->row(array(
+ ->row([
'group_name' => $group,
'path' => $path,
'component_id' => $componentID,
'data' => $dataSerialized,
'created_date' => $now,
- ));
- $dao = CRM_Core_DAO::executeQuery($insert->toSQL(), array(), TRUE, NULL, FALSE, FALSE);
+ ]);
+ $dao = CRM_Core_DAO::executeQuery($insert->toSQL(), [], TRUE, NULL, FALSE, FALSE);
}
$lock->release();
- $dao->free();
-
// cache coherency - refresh or remove dependent caches
$argString = "CRM_CT_{$group}_{$path}_{$componentID}";
$cache = CRM_Utils_Cache::singleton();
- $data = unserialize($dataSerialized);
+ $data = self::decode($dataSerialized);
self::$_cache[$argString] = $data;
- $cache->set($argString, $data);
+ $cache->set(self::cleanKey($argString), $data);
$argString = "CRM_CT_CI_{$group}_{$componentID}";
unset(self::$_cache[$argString]);
- $cache->delete($argString);
+ $cache->delete(self::cleanKey($argString));
}
/**
@@ -197,11 +224,17 @@ public static function setItem(&$data, $group, $path, $componentID = NULL) {
* @param string $path
* Path of the item that needs to be deleted.
* @param bool $clearAll clear all caches
+ * @deprecated
*/
public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
- $table = self::getTableName();
- $where = self::whereCache($group, $path, NULL);
- CRM_Core_DAO::executeQuery("DELETE FROM $table WHERE $where");
+ if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
+ return $adapter::deleteGroup($group, $path);
+ }
+ else {
+ $table = self::getTableName();
+ $where = self::whereCache($group, $path, NULL);
+ CRM_Core_DAO::executeQuery("DELETE FROM $table WHERE $where");
+ }
if ($clearAll) {
// also reset ACL Cache
@@ -237,7 +270,8 @@ public static function storeSessionToCache($names, $resetSession = TRUE) {
if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
$value = $_SESSION[$sessionName[0]][$sessionName[1]];
}
- self::setItem($value, 'CiviCRM Session', "{$sessionName[0]}_{$sessionName[1]}");
+ $key = "{$sessionName[0]}_{$sessionName[1]}";
+ Civi::cache('session')->set($key, $value, self::pickSessionTtl($key));
if ($resetSession) {
$_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
unset($_SESSION[$sessionName[0]][$sessionName[1]]);
@@ -248,7 +282,7 @@ public static function storeSessionToCache($names, $resetSession = TRUE) {
if (!empty($_SESSION[$sessionName])) {
$value = $_SESSION[$sessionName];
}
- self::setItem($value, 'CiviCRM Session', $sessionName);
+ Civi::cache('session')->set($sessionName, $value, self::pickSessionTtl($sessionName));
if ($resetSession) {
$_SESSION[$sessionName] = NULL;
unset($_SESSION[$sessionName]);
@@ -275,17 +309,13 @@ public static function storeSessionToCache($names, $resetSession = TRUE) {
public static function restoreSessionFromCache($names) {
foreach ($names as $key => $sessionName) {
if (is_array($sessionName)) {
- $value = self::getItem('CiviCRM Session',
- "{$sessionName[0]}_{$sessionName[1]}"
- );
+ $value = Civi::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
if ($value) {
$_SESSION[$sessionName[0]][$sessionName[1]] = $value;
}
}
else {
- $value = self::getItem('CiviCRM Session',
- $sessionName
- );
+ $value = Civi::cache('session')->get($sessionName);
if ($value) {
$_SESSION[$sessionName] = $value;
}
@@ -293,6 +323,32 @@ public static function restoreSessionFromCache($names) {
}
}
+ /**
+ * Determine how long session-state should be retained.
+ *
+ * @param string $sessionKey
+ * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
+ * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
+ * @return int
+ * Number of seconds.
+ */
+ protected static function pickSessionTtl($sessionKey) {
+ $secureSessionTimeoutMinutes = (int) Civi::settings()->get('secure_cache_timeout_minutes');
+ if ($secureSessionTimeoutMinutes) {
+ $transactionPages = [
+ 'CRM_Contribute_Controller_Contribution',
+ 'CRM_Event_Controller_Registration',
+ ];
+ foreach ($transactionPages as $transactionPage) {
+ if (strpos($sessionKey, $transactionPage) !== FALSE) {
+ return $secureSessionTimeoutMinutes * 60;
+ }
+ }
+ }
+
+ return self::DEFAULT_SESSION_TTL;
+ }
+
/**
* Do periodic cleanup of the CiviCRM session table.
*
@@ -303,34 +359,9 @@ public static function restoreSessionFromCache($names) {
* @param bool $session
* @param bool $table
* @param bool $prevNext
+ * @param bool $expired
*/
- public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE) {
- // first delete all sessions more than 20 minutes old which are related to any potential transaction
- $timeIntervalMins = (int) Civi::settings()->get('secure_cache_timeout_minutes');
- if ($timeIntervalMins && $session) {
- $transactionPages = array(
- 'CRM_Contribute_Controller_Contribution',
- 'CRM_Event_Controller_Registration',
- );
-
- $params = array(
- 1 => array(
- date('Y-m-d H:i:s', time() - $timeIntervalMins * 60),
- 'String',
- ),
- );
- foreach ($transactionPages as $trPage) {
- $params[] = array("%${trPage}%", 'String');
- $where[] = 'path LIKE %' . count($params);
- }
-
- $sql = "
-DELETE FROM civicrm_cache
-WHERE group_name = 'CiviCRM Session'
-AND created_date <= %1
-AND (" . implode(' OR ', $where) . ")";
- CRM_Core_DAO::executeQuery($sql, $params);
- }
+ public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
// clean up the session cache every $cacheCleanUpNumber probabilistically
$cleanUpNumber = 757;
@@ -338,10 +369,10 @@ public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FAL
$timeIntervalDays = 2;
if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
- $session = $table = $prevNext = TRUE;
+ $expired = $session = $table = $prevNext = TRUE;
}
- if (!$session && !$table && !$prevNext) {
+ if (!$session && !$table && !$prevNext && !$expired) {
return;
}
@@ -355,13 +386,43 @@ public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FAL
}
if ($session) {
+ // Session caches are just regular caches, so they expire naturally per TTL.
+ $expired = TRUE;
+ }
- $sql = "
-DELETE FROM civicrm_cache
-WHERE group_name = 'CiviCRM Session'
-AND created_date < date_sub( NOW( ), INTERVAL $timeIntervalDays DAY )
-";
- CRM_Core_DAO::executeQuery($sql);
+ if ($expired) {
+ $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
+ $params = [
+ 1 => [date(CRM_Utils_Cache_SqlGroup::TS_FMT, CRM_Utils_Time::getTimeRaw()), 'String'],
+ ];
+ CRM_Core_DAO::executeQuery($sql, $params);
+ }
+ }
+
+ /**
+ * (Quasi-private) Encode an object/array/string/int as a string.
+ *
+ * @param $mixed
+ * @return string
+ */
+ public static function encode($mixed) {
+ return base64_encode(serialize($mixed));
+ }
+
+ /**
+ * (Quasi-private) Decode an object/array/string/int from a string.
+ *
+ * @param $string
+ * @return mixed
+ */
+ public static function decode($string) {
+ // Upgrade support -- old records (serialize) always have this punctuation,
+ // and new records (base64) never do.
+ if (strpos($string, ':') !== FALSE || strpos($string, ';') !== FALSE) {
+ return unserialize($string);
+ }
+ else {
+ return unserialize(base64_decode($string));
}
}
@@ -379,7 +440,7 @@ public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FAL
* @return string
*/
protected static function whereCache($group, $path, $componentID) {
- $clauses = array();
+ $clauses = [];
$clauses[] = ('group_name = "' . CRM_Core_DAO::escapeString($group) . '"');
if ($path) {
$clauses[] = ('path = "' . CRM_Core_DAO::escapeString($path) . '"');
@@ -390,4 +451,35 @@ protected static function whereCache($group, $path, $componentID) {
return $clauses ? implode(' AND ', $clauses) : '(1)';
}
+ /**
+ * Normalize a cache key.
+ *
+ * This bridges an impedance mismatch between our traditional caching
+ * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
+ *
+ * @param string $key
+ * Ex: 'ab/cd:ef'
+ * @return string
+ * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
+ * A similar key, but suitable for use with PSR-16-compliant cache providers.
+ */
+ public static function cleanKey($key) {
+ if (!is_string($key) && !is_int($key)) {
+ throw new \RuntimeException("Malformed cache key");
+ }
+
+ $maxLen = 64;
+ $escape = '-';
+
+ if (strlen($key) >= $maxLen) {
+ return $escape . md5($key);
+ }
+
+ $r = preg_replace_callback(';[^A-Za-z0-9_\.];', function($m) use ($escape) {
+ return $escape . dechex(ord($m[0]));
+ }, $key);
+
+ return strlen($r) >= $maxLen ? $escape . md5($key) : $r;
+ }
+
}
diff --git a/CRM/Core/BAO/Cache/Psr16.php b/CRM/Core/BAO/Cache/Psr16.php
new file mode 100644
index 000000000000..03463d473ee5
--- /dev/null
+++ b/CRM/Core/BAO/Cache/Psr16.php
@@ -0,0 +1,210 @@
+warning('Unrecognized BAO cache group ({group}). This should work generally, but data may not be flushed in some edge-cases. Consider migrating explicitly to PSR-16.', [
+ 'group' => $group,
+ ]);
+ }
+
+ $cache = CRM_Utils_Cache::create([
+ 'name' => "bao_$group",
+ 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
+ // We're replacing CRM_Core_BAO_Cache, which traditionally used a front-cache
+ // that was not aware of TTLs. So it seems more consistent/performant to
+ // use 'fast' here.
+ 'withArray' => 'fast',
+ ]);
+ Civi::$statics[__CLASS__][$group] = $cache;
+ }
+ return Civi::$statics[__CLASS__][$group];
+ }
+
+ /**
+ * Retrieve an item from the DB cache.
+ *
+ * @param string $group
+ * (required) The group name of the item.
+ * @param string $path
+ * (required) The path under which this item is stored.
+ * @param int $componentID
+ * The optional component ID (so componenets can share the same name space).
+ *
+ * @return object
+ * The data if present in cache, else null
+ */
+ public static function getItem($group, $path, $componentID = NULL) {
+ // TODO: Generate a general deprecation notice.
+ if ($componentID) {
+ Civi::log()
+ ->warning('getItem({group},{path},...) uses unsupported componentID. Consider migrating explicitly to PSR-16.', [
+ 'group' => $group,
+ 'path' => $path,
+ ]);
+ }
+ return self::getGroup($group)->get(CRM_Core_BAO_Cache::cleanKey($path));
+ }
+
+ /**
+ * Retrieve all items in a group.
+ *
+ * @param string $group
+ * (required) The group name of the item.
+ * @param int $componentID
+ * The optional component ID (so componenets can share the same name space).
+ *
+ * @throws CRM_Core_Exception
+ */
+ public static function &getItems($group, $componentID = NULL) {
+ // Based on grepping universe, this function is not currently used.
+ // Moreover, it's hard to implement in PSR-16. (We'd have to extend the
+ // interface.) Let's wait and see if anyone actually needs this...
+ throw new \CRM_Core_Exception('Not implemented: CRM_Core_BAO_Cache_Psr16::getItems');
+ }
+
+ /**
+ * Store an item in the DB cache.
+ *
+ * @param object $data
+ * (required) A reference to the data that will be serialized and stored.
+ * @param string $group
+ * (required) The group name of the item.
+ * @param string $path
+ * (required) The path under which this item is stored.
+ * @param int $componentID
+ * The optional component ID (so componenets can share the same name space).
+ */
+ public static function setItem(&$data, $group, $path, $componentID = NULL) {
+ // TODO: Generate a general deprecation notice.
+
+ if ($componentID) {
+ Civi::log()
+ ->warning('setItem({group},{path},...) uses unsupported componentID. Consider migrating explicitly to PSR-16.', [
+ 'group' => $group,
+ 'path' => $path,
+ ]);
+ }
+ self::getGroup($group)
+ ->set(CRM_Core_BAO_Cache::cleanKey($path), $data, self::TTL);
+ }
+
+ /**
+ * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
+ *
+ * @param string $group
+ * The group name of the entries to be deleted.
+ * @param string $path
+ * Path of the item that needs to be deleted.
+ */
+ public static function deleteGroup($group = NULL, $path = NULL) {
+ // FIXME: Generate a general deprecation notice.
+
+ if ($path) {
+ self::getGroup($group)->delete(CRM_Core_BAO_Cache::cleanKey($path));
+ }
+ else {
+ self::getGroup($group)->clear();
+ }
+ }
+
+ /**
+ * Cleanup any caches that we've mapped.
+ *
+ * Traditional SQL-backed caches are cleared as a matter of course during a
+ * system flush (by way of "TRUNCATE TABLE civicrm_cache"). This provides
+ * a spot where the adapter can
+ */
+ public static function clearDBCache() {
+ foreach (self::getLegacyGroups() as $groupName) {
+ $group = self::getGroup($groupName);
+ $group->clear();
+ }
+ }
+
+ /**
+ * Get a list of known cache-groups
+ *
+ * @return array
+ */
+ public static function getLegacyGroups() {
+ return [
+ // Core
+ 'CiviCRM Search PrevNextCache',
+ 'contact fields',
+ 'navigation',
+ 'contact groups',
+ 'custom data',
+
+ // Universe
+
+ // be.chiro.civi.atomfeeds
+ 'dashboard',
+
+ // biz.jmaconsulting.lineitemedit
+ 'lineitem-editor',
+
+ // civihr/uk.co.compucorp.civicrm.hrcore
+ 'HRCore_Info',
+
+ // nz.co.fuzion.entitysetting
+ 'CiviCRM setting Spec',
+
+ // org.civicrm.multisite
+ 'descendant groups for an org',
+ ];
+ }
+
+}
diff --git a/CRM/Core/BAO/ConfigSetting.php b/CRM/Core/BAO/ConfigSetting.php
index 0e0d838d66de..946890452edb 100644
--- a/CRM/Core/BAO/ConfigSetting.php
+++ b/CRM/Core/BAO/ConfigSetting.php
@@ -1,9 +1,9 @@
selectAdd('config_backend');
}
else {
@@ -108,7 +108,7 @@ public static function retrieve(&$defaults) {
if ($domain->config_backend) {
$defaults = unserialize($domain->config_backend);
if ($defaults === FALSE || !is_array($defaults)) {
- $defaults = array();
+ $defaults = [];
return FALSE;
}
@@ -141,20 +141,22 @@ public static function applyLocale($settings, $activatedLocales) {
$session = CRM_Core_Session::singleton();
- // on multi-lang sites based on request and civicrm_uf_match
- if ($multiLang) {
- $languageLimit = array();
- if (is_array($settings->get('languageLimit'))) {
- $languageLimit = $settings->get('languageLimit');
- }
+ $permittedLanguages = CRM_Core_I18n::uiLanguages(TRUE);
+ // The locale to be used can come from various places:
+ // - the request (url)
+ // - the session
+ // - civicrm_uf_match
+ // - inherited from the CMS
+ // Only look at this if there is actually a choice of permitted languages
+ if (count($permittedLanguages) >= 2) {
$requestLocale = CRM_Utils_Request::retrieve('lcMessages', 'String');
- if (in_array($requestLocale, array_keys($languageLimit))) {
+ if (in_array($requestLocale, $permittedLanguages)) {
$chosenLocale = $requestLocale;
//CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
// Ed: This doesn't sound good.
- CRM_Core_BAO_Cache::deleteGroup('navigation');
+ // CRM_Core_BAO_Cache::deleteGroup('navigation');
}
else {
$requestLocale = NULL;
@@ -162,7 +164,7 @@ public static function applyLocale($settings, $activatedLocales) {
if (!$requestLocale) {
$sessionLocale = $session->get('lcMessages');
- if (in_array($sessionLocale, array_keys($languageLimit))) {
+ if (in_array($sessionLocale, $permittedLanguages)) {
$chosenLocale = $sessionLocale;
}
else {
@@ -184,7 +186,7 @@ public static function applyLocale($settings, $activatedLocales) {
$ufm = new CRM_Core_DAO_UFMatch();
$ufm->contact_id = $session->get('userID');
if ($ufm->find(TRUE) &&
- in_array($ufm->language, array_keys($languageLimit))
+ in_array($ufm->language, $permittedLanguages)
) {
$chosenLocale = $ufm->language;
}
@@ -196,7 +198,8 @@ public static function applyLocale($settings, $activatedLocales) {
// try to inherit the language from the hosting CMS
if ($settings->get('inheritLocale')) {
// FIXME: On multilanguage installs, CRM_Utils_System::getUFLocale() in many cases returns nothing if $dbLocale is not set
- $dbLocale = $multiLang ? ("_" . $settings->get('lcMessages')) : '';
+ $lcMessages = $settings->get('lcMessages');
+ $dbLocale = $multiLang && $lcMessages ? "_{$lcMessages}" : '';
$chosenLocale = CRM_Utils_System::getUFLocale();
if ($activatedLocales and !in_array($chosenLocale, explode(CRM_Core_DAO::VALUE_SEPARATOR, $activatedLocales))) {
$chosenLocale = NULL;
@@ -209,7 +212,7 @@ public static function applyLocale($settings, $activatedLocales) {
}
// set suffix for table names - use views if more than one language
- $dbLocale = $multiLang ? "_{$chosenLocale}" : '';
+ $dbLocale = $multiLang && $chosenLocale ? "_{$chosenLocale}" : '';
// FIXME: an ugly hack to fix CRM-4041
global $tsLocale;
@@ -228,7 +231,7 @@ public static function applyLocale($settings, $activatedLocales) {
* @return string
* @throws Exception
*/
- public static function doSiteMove($defaultValues = array()) {
+ public static function doSiteMove($defaultValues = []) {
$moveStatus = ts('Beginning site move process...') . ' ';
$settings = Civi::settings();
@@ -237,15 +240,15 @@ public static function doSiteMove($defaultValues = array()) {
if ($value && $value != $settings->getDefault($key)) {
if ($settings->getMandatory($key) === NULL) {
$settings->revert($key);
- $moveStatus .= ts("WARNING: The setting (%1) has been reverted.", array(
+ $moveStatus .= ts("WARNING: The setting (%1) has been reverted.", [
1 => $key,
- ));
+ ]);
$moveStatus .= ' ';
}
else {
- $moveStatus .= ts("WARNING: The setting (%1) is overridden and could not be reverted.", array(
+ $moveStatus .= ts("WARNING: The setting (%1) is overridden and could not be reverted.", [
1 => $key,
- ));
+ ]);
$moveStatus .= ' ';
}
}
@@ -259,6 +262,7 @@ public static function doSiteMove($defaultValues = array()) {
// clear all caches
CRM_Core_Config::clearDBCache();
+ Civi::cache('session')->clear();
$moveStatus .= ts('Database cache tables cleared.') . ' ';
$resetSessionTable = CRM_Utils_Request::retrieve('resetSessionTable',
@@ -332,7 +336,7 @@ public static function disableComponent($componentName) {
// get enabled-components from DB and add to the list
$enabledComponents = Civi::settings()->get('enable_components');
- $enabledComponents = array_diff($enabledComponents, array($componentName));
+ $enabledComponents = array_diff($enabledComponents, [$componentName]);
self::setEnabledComponents($enabledComponents);
@@ -356,7 +360,7 @@ public static function setEnabledComponents($enabledComponents) {
* @return array
*/
public static function skipVars() {
- return array(
+ return [
'dsn',
'templateCompileDir',
'userFrameworkDSN',
@@ -382,7 +386,7 @@ public static function skipVars() {
'autocompleteContactReference',
'checksumTimeout',
'checksum_timeout',
- );
+ ];
}
/**
@@ -406,26 +410,26 @@ public static function filterSkipVars($params) {
* @return array
*/
private static function getUrlSettings() {
- return array(
+ return [
'userFrameworkResourceURL',
'imageUploadURL',
'customCSSURL',
'extensionsURL',
- );
+ ];
}
/**
* @return array
*/
private static function getPathSettings() {
- return array(
+ return [
'uploadDir',
'imageUploadDir',
'customFileUploadDir',
'customTemplateDir',
'customPHPPathDir',
'extensionsDir',
- );
+ ];
}
}
diff --git a/CRM/Core/BAO/Country.php b/CRM/Core/BAO/Country.php
index 23b3d64eae46..df195660c008 100644
--- a/CRM/Core/BAO/Country.php
+++ b/CRM/Core/BAO/Country.php
@@ -1,9 +1,9 @@
get('provinceLimit');
- $country = array();
+ $country = [];
if (is_array($provinceLimit)) {
foreach ($provinceLimit as $val) {
// CRM-12007
@@ -74,7 +74,7 @@ public static function provinceLimit() {
public static function countryLimit() {
if (!isset(Civi::$statics[__CLASS__]['countryLimit'])) {
$countryIsoCodes = CRM_Core_PseudoConstant::countryIsoCode();
- $country = array();
+ $country = [];
$countryLimit = Civi::settings()->get('countryLimit');
if (is_array($countryLimit)) {
foreach ($countryLimit as $val) {
@@ -139,10 +139,10 @@ public static function defaultCurrencySymbol($defaultCurrency = NULL) {
if (!$cachedSymbol || $defaultCurrency) {
$currency = $defaultCurrency ? $defaultCurrency : Civi::settings()->get('defaultCurrency');
if ($currency) {
- $currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', array(
+ $currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
'labelColumn' => 'symbol',
'orderColumn' => TRUE,
- ));
+ ]);
$cachedSymbol = CRM_Utils_Array::value($currency, $currencySymbols, '');
}
else {
diff --git a/CRM/Core/BAO/CustomField.php b/CRM/Core/BAO/CustomField.php
index 21d093fc4805..19f1ce3bf507 100644
--- a/CRM/Core/BAO/CustomField.php
+++ b/CRM/Core/BAO/CustomField.php
@@ -1,9 +1,9 @@
CRM_Utils_Type
+ */
+ public static function dataToType() {
+ return [
+ 'String' => CRM_Utils_Type::T_STRING,
+ 'Int' => CRM_Utils_Type::T_INT,
+ 'Money' => CRM_Utils_Type::T_MONEY,
+ 'Memo' => CRM_Utils_Type::T_LONGTEXT,
+ 'Float' => CRM_Utils_Type::T_FLOAT,
+ 'Date' => CRM_Utils_Type::T_DATE,
+ 'DateTime' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
+ 'Boolean' => CRM_Utils_Type::T_BOOLEAN,
+ 'StateProvince' => CRM_Utils_Type::T_INT,
+ 'File' => CRM_Utils_Type::T_STRING,
+ 'Link' => CRM_Utils_Type::T_STRING,
+ 'ContactReference' => CRM_Utils_Type::T_INT,
+ 'Country' => CRM_Utils_Type::T_INT,
+ ];
+ }
+
/**
* Get data to html array.
*
@@ -99,7 +123,6 @@ public static function dataToHtml() {
'Radio' => 'Radio',
'CheckBox' => 'CheckBox',
'Multi-Select' => 'Multi-Select',
- 'AdvMulti-Select' => 'AdvMulti-Select',
'Autocomplete-Select' => 'Autocomplete-Select',
),
array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
@@ -167,7 +190,6 @@ public static function create(&$params) {
break;
case 'CheckBox':
- case 'AdvMulti-Select':
case 'Multi-Select':
if (isset($params['default_checkbox_option'])) {
$tempArray = array_keys($params['default_checkbox_option']);
@@ -193,21 +215,14 @@ public static function create(&$params) {
}
$transaction = new CRM_Core_Transaction();
- // create any option group & values if required
- if ($params['html_type'] != 'Text' &&
- in_array($params['data_type'], array(
- 'String',
- 'Int',
- 'Float',
- 'Money',
- ))
- ) {
- $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
- $params['custom_group_id'],
- 'table_name'
- );
+ $htmlType = CRM_Utils_Array::value('html_type', $params);
+ $dataType = CRM_Utils_Array::value('data_type', $params);
+ $allowedOptionTypes = array('String', 'Int', 'Float', 'Money');
+ // create any option group & values if required
+ if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
+ ) {
//CRM-16659: if option_value then create an option group for this custom field.
if ($params['option_type'] == 1 && (empty($params['option_group_id']) || !empty($params['option_value']))) {
// first create an option group for this custom group
@@ -215,7 +230,9 @@ public static function create(&$params) {
$optionGroup->name = "{$columnName}_" . date('YmdHis');
$optionGroup->title = $params['label'];
$optionGroup->is_active = 1;
- $optionGroup->data_type = $params['data_type'];
+ // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
+ $optionGroup->is_reserved = 0;
+ $optionGroup->data_type = $dataType;
$optionGroup->save();
$params['option_group_id'] = $optionGroup->id;
if (!empty($params['option_value']) && is_array($params['option_value'])) {
@@ -225,7 +242,7 @@ public static function create(&$params) {
$optionValue->option_group_id = $optionGroup->id;
$optionValue->label = $params['option_label'][$k];
$optionValue->name = CRM_Utils_String::titleToVar($params['option_label'][$k]);
- switch ($params['data_type']) {
+ switch ($dataType) {
case 'Money':
$optionValue->value = CRM_Utils_Rule::cleanMoney($v);
break;
@@ -262,7 +279,7 @@ public static function create(&$params) {
if (empty($params['default_value'])) {
//don't insert only value separator as default value, CRM-4579
$defaultValue = self::getOptionGroupDefault($params['option_group_id'],
- $params['html_type']
+ $htmlType
);
if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR,
@@ -275,19 +292,21 @@ public static function create(&$params) {
}
// since we need to save option group id :)
- if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
+ if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
$params['attributes'] = 'rows=4, cols=60';
}
$customField = new CRM_Core_DAO_CustomField();
$customField->copyValues($params);
- $customField->is_required = CRM_Utils_Array::value('is_required', $params, FALSE);
- $customField->is_searchable = CRM_Utils_Array::value('is_searchable', $params, FALSE);
- $customField->in_selector = CRM_Utils_Array::value('in_selector', $params, FALSE);
- $customField->is_search_range = CRM_Utils_Array::value('is_search_range', $params, FALSE);
- //CRM-15792 - Custom field gets disabled if is_active not set
- $customField->is_active = CRM_Utils_Array::value('is_active', $params, TRUE);
- $customField->is_view = CRM_Utils_Array::value('is_view', $params, FALSE);
+ if ($op == 'create') {
+ $customField->is_required = CRM_Utils_Array::value('is_required', $params, FALSE);
+ $customField->is_searchable = CRM_Utils_Array::value('is_searchable', $params, FALSE);
+ $customField->in_selector = CRM_Utils_Array::value('in_selector', $params, FALSE);
+ $customField->is_search_range = CRM_Utils_Array::value('is_search_range', $params, FALSE);
+ //CRM-15792 - Custom field gets disabled if is_active not set
+ $customField->is_active = CRM_Utils_Array::value('is_active', $params, TRUE);
+ $customField->is_view = CRM_Utils_Array::value('is_view', $params, FALSE);
+ }
$customField->save();
// make sure all values are present in the object for further processing
@@ -344,8 +363,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) {
@@ -383,6 +402,9 @@ public function getOptions($context = NULL) {
$this->find(TRUE);
}
+ // This will hold the list of options in format key => label
+ $options = [];
+
if (!empty($this->option_group_id)) {
$options = CRM_Core_OptionGroup::valuesByID(
$this->option_group_id,
@@ -402,9 +424,6 @@ public function getOptions($context = NULL) {
elseif ($this->data_type === 'Boolean') {
$options = $context == 'validate' ? array(0, 1) : CRM_Core_SelectValues::boolean();
}
- else {
- return FALSE;
- }
CRM_Utils_Hook::customFieldOptions($this->id, $options, FALSE);
CRM_Utils_Hook::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
return $options;
@@ -698,6 +717,7 @@ public static function getFieldsForImport(
$regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
$importableFields[$key] = array(
'name' => $key,
+ 'type' => CRM_Utils_Array::value(CRM_Utils_Array::value('data_type', $values), self::dataToType()),
'title' => CRM_Utils_Array::value('label', $values),
'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
'import' => 1,
@@ -803,6 +823,7 @@ public static function addQuickFormElement(
$field = self::getFieldObject($fieldId);
$widget = $field->html_type;
$element = NULL;
+ $customFieldAttributes = array();
// Custom field HTML should indicate group+field name
$groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
@@ -825,7 +846,6 @@ public static function addQuickFormElement(
'Multi-Select State/Province',
'Select Country',
'Multi-Select Country',
- 'AdvMulti-Select',
'CheckBox',
'Radio',
)));
@@ -834,29 +854,35 @@ public static function addQuickFormElement(
$options = $field->getOptions($search ? 'search' : 'create');
// Consolidate widget types to simplify the below switch statement
- if ($search || ($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
+ if ($search || (strpos($widget, 'Select') !== FALSE)) {
$widget = 'Select';
}
- $selectAttributes = array(
- 'data-crm-custom' => $dataCrmCustomVal,
- 'class' => 'crm-select2',
- );
+
+ $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
+ $selectAttributes = array('class' => 'crm-select2');
+
// Search field is always multi-select
if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
$selectAttributes['class'] .= ' huge';
$selectAttributes['multiple'] = 'multiple';
$selectAttributes['placeholder'] = $placeholder;
}
+
// Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
- if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
- $selectAttributes += array(
+ $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
+ $canEditOptions = CRM_Core_Permission::check('administer CiviCRM');
+ if ($field->option_group_id && !$search && $isSelect && $canEditOptions) {
+ $customFieldAttributes += array(
'data-api-entity' => $field->getEntity(),
'data-api-field' => 'custom_' . $field->id,
'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
);
+ $selectAttributes += $customFieldAttributes;
}
}
+ $rangeDataTypes = ['Int', 'Float', 'Money'];
+
if (!isset($label)) {
$label = $field->label;
}
@@ -866,7 +892,7 @@ public static function addQuickFormElement(
switch ($widget) {
case 'Text':
case 'Link':
- if ($field->is_search_range && $search) {
+ if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
$qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
$qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
}
@@ -932,65 +958,70 @@ public static function addQuickFormElement(
break;
case 'Radio':
- $choice = array();
- foreach ($options as $v => $l) {
- $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
- }
- $element = $qf->addGroup($choice, $elementName, $label);
- if ($useRequired && !$search) {
- $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
+ $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
+ $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
}
else {
- $element->setAttribute('allowClear', TRUE);
+ $choice = array();
+ parse_str($field->attributes, $radioAttributes);
+ $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
+
+ foreach ($options as $v => $l) {
+ $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
+ }
+ $element = $qf->addGroup($choice, $elementName, $label);
+ $optionEditKey = 'data-option-edit-path';
+ if (isset($selectAttributes[$optionEditKey])) {
+ $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
+ }
+
+ if ($useRequired && !$search) {
+ $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ }
+ else {
+ $element->setAttribute('allowClear', TRUE);
+ }
}
break;
// For all select elements
case 'Select':
- if (empty($selectAttributes['multiple'])) {
- $options = array('' => $placeholder) + $options;
- }
- $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
-
- // Add and/or option for fields that store multiple values
- if ($search && self::isSerialized($field)) {
-
- $operators = array(
- $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
- $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
- );
- $qf->addGroup($operators, $elementName . '_operator');
- $qf->setDefaults(array($elementName . '_operator' => 'or'));
+ if ($field->is_search_range && $search && in_array($field->data_type, $rangeDataTypes)) {
+ $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
+ $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
}
- break;
-
- case 'AdvMulti-Select':
- $element = $qf->addElement(
- 'advmultiselect',
- $elementName,
- $label, $options,
- array(
- 'size' => 5,
- 'style' => '',
- 'class' => 'advmultiselect',
- 'data-crm-custom' => $dataCrmCustomVal,
- )
- );
+ else {
+ if (empty($selectAttributes['multiple'])) {
+ $options = array('' => $placeholder) + $options;
+ }
+ $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
- $element->setButtonAttributes('add', array('value' => ts('Add >>')));
- $element->setButtonAttributes('remove', array('value' => ts('<< Remove')));
+ // Add and/or option for fields that store multiple values
+ if ($search && self::isSerialized($field)) {
- if ($useRequired && !$search) {
- $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ $operators = array(
+ $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
+ $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
+ );
+ $qf->addGroup($operators, $elementName . '_operator');
+ $qf->setDefaults(array($elementName . '_operator' => 'or'));
+ }
}
break;
case 'CheckBox':
$check = array();
foreach ($options as $v => $l) {
- $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
+ $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
+ }
+
+ $group = $element = $qf->addGroup($check, $elementName, $label);
+ $optionEditKey = 'data-option-edit-path';
+ if (isset($customFieldAttributes[$optionEditKey])) {
+ $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
}
- $element = $qf->addGroup($check, $elementName, $label);
+
if ($useRequired && !$search) {
$qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
}
@@ -1045,8 +1076,15 @@ public static function addQuickFormElement(
$element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
$urlParams = "context=customfield&id={$field->id}";
-
- $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref',
+ $idOfelement = $elementName;
+ // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
+ // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
+ // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
+ // rather than layering on more hacks.
+ if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
+ $idOfelement = substr(substr($elementName, (strpos($elementName, '[') + 1)), 0, -1);
+ }
+ $customUrls[$idOfelement] = CRM_Utils_System::url('civicrm/ajax/contactref',
$urlParams,
FALSE, NULL, FALSE
);
@@ -1055,11 +1093,11 @@ public static function addQuickFormElement(
else {
// FIXME: This won't work with customFieldOptions hook
$attributes += array(
- 'entity' => 'option_value',
+ 'entity' => 'OptionValue',
'placeholder' => $placeholder,
'multiple' => $search,
'api' => array(
- 'params' => array('option_group_id' => $field->option_group_id),
+ 'params' => array('option_group_id' => $field->option_group_id, 'is_active' => 1),
),
);
$element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
@@ -1141,12 +1179,12 @@ public static function deleteField($field) {
/**
* @param string|int|array|null $value
* @param CRM_Core_BAO_CustomField|int|array|string $field
- * @param $contactId
+ * @param int $entityId
*
* @return string
* @throws \Exception
*/
- public static function displayValue($value, $field, $contactId = NULL) {
+ public static function displayValue($value, $field, $entityId = NULL) {
$field = is_array($field) ? $field['id'] : $field;
$fieldId = is_object($field) ? $field->id : (int) str_replace('custom_', '', $field);
@@ -1160,7 +1198,7 @@ public static function displayValue($value, $field, $contactId = NULL) {
$fieldInfo = array('options' => $field->getOptions()) + (array) $field;
- return self::formatDisplayValue($value, $fieldInfo, $contactId);
+ return self::formatDisplayValue($value, $fieldInfo, $entityId);
}
/**
@@ -1178,8 +1216,8 @@ private static function formatDisplayValue($value, $field, $entityId = NULL) {
$value = CRM_Utils_Array::explodePadded($value);
}
// CRM-12989 fix
- if ($field['html_type'] == 'CheckBox') {
- CRM_Utils_Array::formatArrayKeys($value);
+ if ($field['html_type'] == 'CheckBox' && $value) {
+ $value = CRM_Utils_Array::convertCheckboxFormatToArray($value);
}
$display = is_array($value) ? implode(', ', $value) : (string) $value;
@@ -1192,12 +1230,16 @@ private static function formatDisplayValue($value, $field, $entityId = NULL) {
case 'Select Country':
case 'Select State/Province':
case 'CheckBox':
- case 'AdvMulti-Select':
case 'Multi-Select':
case 'Multi-Select State/Province':
case 'Multi-Select Country':
if ($field['data_type'] == 'ContactReference' && $value) {
- $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
+ if (is_numeric($value)) {
+ $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
+ }
+ else {
+ $display = $value;
+ }
}
elseif (is_array($value)) {
$v = array();
@@ -1247,7 +1289,13 @@ private static function formatDisplayValue($value, $field, $entityId = NULL) {
// In the context of displaying a profile, show file/image
if ($value) {
if ($entityId) {
- $url = self::getFileURL($entityId, $field['id']);
+ if (CRM_Utils_Rule::positiveInteger($value)) {
+ $fileId = $value;
+ }
+ else {
+ $fileId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
+ }
+ $url = self::getFileURL($entityId, $field['id'], $fileId);
if ($url) {
$display = $url['file_url'];
}
@@ -1276,7 +1324,7 @@ private static function formatDisplayValue($value, $field, $entityId = NULL) {
case 'Text':
if ($field['data_type'] == 'Money' && isset($value)) {
- //$value can also be an array(while using IN operator from search builder or api).
+ // $value can also be an array(while using IN operator from search builder or api).
foreach ((array) $value as $val) {
$disp[] = CRM_Utils_Money::format($val, NULL, NULL, TRUE);
}
@@ -1355,7 +1403,6 @@ public static function setProfileDefaults(
}
switch ($customField->html_type) {
case 'CheckBox':
- case 'AdvMulti-Select':
case 'Multi-Select':
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
$defaults[$elementName] = array();
@@ -1367,27 +1414,13 @@ public static function setProfileDefaults(
if ($customField->html_type == 'CheckBox') {
$defaults[$elementName][$val['value']] = 1;
}
- elseif ($customField->html_type == 'Multi-Select' ||
- $customField->html_type == 'AdvMulti-Select'
- ) {
+ elseif ($customField->html_type == 'Multi-Select') {
$defaults[$elementName][$val['value']] = $val['value'];
}
}
}
break;
- case 'Autocomplete-Select':
- if ($customField->data_type == 'ContactReference') {
- if (is_numeric($value)) {
- $defaults[$elementName . '_id'] = $value;
- $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
- }
- }
- else {
- $defaults[$elementName] = $value;
- }
- break;
-
default:
$defaults[$elementName] = $value;
}
@@ -1449,9 +1482,10 @@ public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute =
'entity_id',
'file_id'
);
- list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
+ list($path) = CRM_Core_BAO_File::path($fileID, $entityId);
+ $fileHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileID);
$url = CRM_Utils_System::url('civicrm/file',
- "reset=1&id=$fileID&eid=$contactID",
+ "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
$absolute, NULL, TRUE, TRUE
);
$result['file_url'] = CRM_Utils_File::getFileURL($path, $fileType, $url);
@@ -1462,8 +1496,9 @@ public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute =
$fileID,
'uri'
);
+ $fileHash = CRM_Core_BAO_File::generateFileHash($contactID, $fileID);
$url = CRM_Utils_System::url('civicrm/file',
- "reset=1&id=$fileID&eid=$contactID",
+ "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
$absolute, NULL, TRUE, TRUE
);
$result['file_url'] = CRM_Utils_File::getFileURL($uri, $fileType, $url);
@@ -1579,9 +1614,7 @@ public static function formatCustomField(
}
}
- if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
- $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
- ) {
+ if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
if ($value) {
$value = CRM_Utils_Array::implodePadded($value);
}
@@ -1591,7 +1624,6 @@ public static function formatCustomField(
}
if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
- $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
$customFields[$customFieldId]['html_type'] == 'CheckBox'
) &&
$customFields[$customFieldId]['data_type'] == 'String' &&
@@ -1646,7 +1678,7 @@ public static function formatCustomField(
$value = 0;
}
- $fileId = NULL;
+ $fileID = NULL;
if ($customFields[$customFieldId]['data_type'] == 'File') {
if (empty($value)) {
@@ -1685,20 +1717,20 @@ public static function formatCustomField(
FROM $tableName
WHERE id = %1";
$params = array(1 => array($customValueId, 'Integer'));
- $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
+ $fileID = CRM_Core_DAO::singleValueQuery($query, $params);
}
$fileDAO = new CRM_Core_DAO_File();
- if ($fileId) {
- $fileDAO->id = $fileId;
+ if ($fileID) {
+ $fileDAO->id = $fileID;
}
$fileDAO->uri = $filename;
$fileDAO->mime_type = $mimeType;
$fileDAO->upload_date = date('YmdHis');
$fileDAO->save();
- $fileId = $fileDAO->id;
+ $fileID = $fileDAO->id;
$value = $filename;
}
@@ -1726,7 +1758,7 @@ public static function formatCustomField(
'custom_group_id' => $groupID,
'table_name' => $tableName,
'column_name' => $columnName,
- 'file_id' => $fileId,
+ 'file_id' => $fileID,
'is_multiple' => $customFields[$customFieldId]['is_multiple'],
);
@@ -2006,7 +2038,6 @@ public static function getTableColumnGroup($fieldID, $force = FALSE) {
if (!$dao->fetch()) {
CRM_Core_Error::fatal();
}
- $dao->free();
$fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
$cache->set($cacheKey, $fieldValues);
}
@@ -2016,6 +2047,8 @@ public static function getTableColumnGroup($fieldID, $force = FALSE) {
/**
* Get custom option groups.
*
+ * @deprecated Use the API OptionGroup.get
+ *
* @param array $includeFieldIds
* Ids of custom fields for which option groups must be included.
*
@@ -2200,46 +2233,46 @@ public static function postProcess(
}
/**
+ * Get custom field ID from field/group name/title.
*
- */
-
- /**
- * Get custom field ID.
- *
- * @param string $fieldLabel
- * @param null $groupTitle
+ * @param string $fieldName Field name or label
+ * @param string|null $groupName (Optional) Group name or label
+ * @param bool $fullString Whether to return "custom_123" or "123"
*
- * @return int|null
+ * @return string|int|null
+ * @throws \CiviCRM_API3_Exception
*/
- public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
- $params = array(1 => array($fieldLabel, 'String'));
- if ($groupTitle) {
- $params[2] = array($groupTitle, 'String');
- $sql = "
-SELECT f.id
-FROM civicrm_custom_field f
-INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
-WHERE ( f.label = %1 OR f.name = %1 )
-AND ( g.title = %2 OR g.name = %2 )
-";
- }
- else {
- $sql = "
-SELECT f.id
-FROM civicrm_custom_field f
-WHERE ( f.label = %1 OR f.name = %1 )
-";
- }
+ public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
+ $cacheKey = $groupName . '.' . $fieldName;
+ if (!isset(Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
+ $customFieldParams = [
+ 'name' => $fieldName,
+ 'label' => $fieldName,
+ 'options' => ['or' => [["name", "label"]]],
+ ];
+
+ if ($groupName) {
+ $customFieldParams['custom_group_id.name'] = $groupName;
+ $customFieldParams['custom_group_id.title'] = $groupName;
+ $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
+ }
- $dao = CRM_Core_DAO::executeQuery($sql, $params);
- if ($dao->fetch() &&
- $dao->N == 1
- ) {
- return $dao->id;
+ $field = civicrm_api3('CustomField', 'get', $customFieldParams);
+
+ if (empty($field['id'])) {
+ Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
+ Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
+ }
+ else {
+ Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
+ Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
+ }
}
- else {
- return NULL;
+
+ if ($fullString) {
+ return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
}
+ return Civi::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
}
/**
@@ -2408,6 +2441,31 @@ public static function isMultiRecordField($customId) {
return $isMultipleWithGid;
}
+ /**
+ * Does this field type have any select options?
+ *
+ * @param array $field
+ *
+ * @return bool
+ */
+ public static function hasOptions($field) {
+ // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
+ $field = (array) $field;
+ // This will include boolean fields with Yes/No options.
+ if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
+ return TRUE;
+ }
+ // Do this before the "Select" string search because date fields have a "Select Date" html_type
+ // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
+ if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
+ return FALSE;
+ }
+ if (strpos($field['html_type'], 'Select') !== FALSE) {
+ return TRUE;
+ }
+ return !empty($field['option_group_id']);
+ }
+
/**
* Does this field store a serialized string?
*
diff --git a/CRM/Core/BAO/CustomGroup.php b/CRM/Core/BAO/CustomGroup.php
index 6bc5fe382598..d20a3188d916 100644
--- a/CRM/Core/BAO/CustomGroup.php
+++ b/CRM/Core/BAO/CustomGroup.php
@@ -1,9 +1,9 @@
title = $params['title'];
}
- if (in_array($params['extends'][0],
- array(
- 'ParticipantRole',
- 'ParticipantEventName',
- 'ParticipantEventType',
- )
- )) {
+ $extends = CRM_Utils_Array::value('extends', $params, []);
+ $extendsEntity = CRM_Utils_Array::value(0, $extends);
+
+ $participantEntities = [
+ 'ParticipantRole',
+ 'ParticipantEventName',
+ 'ParticipantEventType',
+ ];
+
+ if (in_array($extendsEntity, $participantEntities)) {
$group->extends = 'Participant';
}
else {
- $group->extends = $params['extends'][0];
+ $group->extends = $extendsEntity;
}
$group->extends_entity_column_id = 'null';
- if (
- $params['extends'][0] == 'ParticipantRole' ||
- $params['extends'][0] == 'ParticipantEventName' ||
- $params['extends'][0] == 'ParticipantEventType'
+ if (in_array($extendsEntity, $participantEntities)
) {
- $group->extends_entity_column_id = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
+ $group->extends_entity_column_id = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $extendsEntity, 'value', 'name');
}
- //this is format when form get submit.
- $extendsChildType = CRM_Utils_Array::value(1, $params['extends']);
- //lets allow user to pass direct child type value, CRM-6893
+ // this is format when form get submit.
+ $extendsChildType = CRM_Utils_Array::value(1, $extends);
+ // lets allow user to pass direct child type value, CRM-6893
if (!empty($params['extends_entity_column_value'])) {
$extendsChildType = $params['extends_entity_column_value'];
}
if (!CRM_Utils_System::isNull($extendsChildType)) {
$extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType);
- if (CRM_Utils_Array::value(0, $params['extends']) == 'Relationship') {
- $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
+ if (CRM_Utils_Array::value(0, $extends) == 'Relationship') {
+ $extendsChildType = str_replace(['_a_b', '_b_a'], [
'',
'',
- ), $extendsChildType);
+ ], $extendsChildType);
}
if (substr($extendsChildType, 0, 1) != CRM_Core_DAO::VALUE_SEPARATOR) {
$extendsChildType = CRM_Core_DAO::VALUE_SEPARATOR . $extendsChildType .
@@ -113,7 +114,7 @@ public static function create(&$params) {
$oldWeight = 0;
}
$group->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array::value('weight', $params, FALSE));
- $fields = array(
+ $fields = [
'style',
'collapse_display',
'collapse_adv_display',
@@ -121,38 +122,41 @@ public static function create(&$params) {
'help_post',
'is_active',
'is_multiple',
- );
+ ];
$current_db_version = CRM_Core_DAO::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config::domainID());
$is_public_version = $current_db_version >= '4.7.19' ? 1 : 0;
if ($is_public_version) {
$fields[] = 'is_public';
}
foreach ($fields as $field) {
- if (isset($params[$field]) || $field == 'is_multiple') {
- $group->$field = CRM_Utils_Array::value($field, $params, FALSE);
+ if (isset($params[$field])) {
+ $group->$field = $params[$field];
}
}
$group->max_multiple = isset($params['is_multiple']) ? (isset($params['max_multiple']) &&
$params['max_multiple'] >= '0'
) ? $params['max_multiple'] : 'null' : 'null';
- $tableName = $oldTableName = NULL;
+ $tableName = $tableNameNeedingIndexUpdate = NULL;
if (isset($params['id'])) {
$group->id = $params['id'];
- //check whether custom group was changed from single-valued to multiple-valued
- $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
- $params['id'],
- 'is_multiple'
- );
- if ((!empty($params['is_multiple']) || $isMultiple) &&
- ($params['is_multiple'] != $isMultiple)
- ) {
- $oldTableName = CRM_Core_DAO::getFieldValue(
- 'CRM_Core_DAO_CustomGroup',
+ if (isset($params['is_multiple'])) {
+ // check whether custom group was changed from single-valued to multiple-valued
+ $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
$params['id'],
- 'table_name'
+ 'is_multiple'
);
+
+ // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
+ $paramsIsMultiple = empty($params['is_multiple']) ? 0 : 1;
+ if ($paramsIsMultiple != $isMultiple) {
+ $tableNameNeedingIndexUpdate = CRM_Core_DAO::getFieldValue(
+ 'CRM_Core_DAO_CustomGroup',
+ $params['id'],
+ 'table_name'
+ );
+ }
}
}
else {
@@ -172,7 +176,7 @@ public static function create(&$params) {
if (CRM_Core_DAO_AllCoreTables::isCoreTable($tableName)) {
// Bad idea. Prevent group creation because it might lead to a broken configuration.
- CRM_Core_Error::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
+ CRM_Core_Error::fatal(ts("Cannot create custom table because %1 is already a core table.", ['1' => $tableName]));
}
}
}
@@ -189,7 +193,7 @@ public static function create(&$params) {
$group->save();
if (!isset($params['id'])) {
if (!isset($params['table_name'])) {
- $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 42));
+ $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 13));
$tableName = "civicrm_value_{$munged_title}_{$group->id}";
}
$group->table_name = $tableName;
@@ -202,8 +206,8 @@ public static function create(&$params) {
// now create the table associated with this group
self::createTable($group);
}
- elseif ($oldTableName) {
- CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($oldTableName, CRM_Utils_Array::value('is_multiple', $params));
+ elseif ($tableNameNeedingIndexUpdate) {
+ CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array::value('is_multiple', $params));
}
if (CRM_Utils_Array::value('overrideFKConstraint', $params) == 1) {
@@ -211,7 +215,7 @@ public static function create(&$params) {
$params['id'],
'table_name'
);
- CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($params['extends'][0]));
+ CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($extendsEntity));
}
$transaction->commit();
@@ -250,8 +254,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) {
// reset the cache
@@ -299,16 +303,17 @@ public static function autoCreateByActivityType($activityTypeId) {
if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
return TRUE;
}
- $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
- $params = array(
+ // everything
+ $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
+ $params = [
'version' => 3,
'extends' => 'Activity',
'extends_entity_column_id' => NULL,
- 'extends_entity_column_value' => CRM_Utils_Array::implodePadded(array($activityTypeId)),
- 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
+ 'extends_entity_column_value' => CRM_Utils_Array::implodePadded([$activityTypeId]),
+ 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
'style' => 'Inline',
'is_active' => 1,
- );
+ ];
$result = civicrm_api('CustomGroup', 'create', $params);
return !$result['is_error'];
}
@@ -350,13 +355,15 @@ public static function autoCreateByActivityType($activityTypeId) {
* @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
* The reason for the info array in unclear and it could be determined from parsing the group tree after creation
* With caching the performance impact would be small & the function would be cleaner
+ *
+ * @throws \CRM_Core_Exception
*/
public static function getTree(
$entityType,
- $toReturn = array(),
+ $toReturn = [],
$entityID = NULL,
$groupID = NULL,
- $subTypes = array(),
+ $subTypes = [],
$subName = NULL,
$fromCache = TRUE,
$onlySubType = NULL,
@@ -370,7 +377,7 @@ public static function getTree(
}
if (!is_array($subTypes)) {
if (empty($subTypes)) {
- $subTypes = array();
+ $subTypes = [];
}
else {
if (stristr($subTypes, ',')) {
@@ -383,11 +390,10 @@ public static function getTree(
}
// create a new tree
- $strWhere = $orderBy = '';
// legacy hardcoded list of data to return
- $tableData = array(
- 'custom_field' => array(
+ $tableData = [
+ 'custom_field' => [
'id',
'name',
'label',
@@ -407,8 +413,8 @@ public static function getTree(
'time_format',
'option_group_id',
'in_selector',
- ),
- 'custom_group' => array(
+ ],
+ 'custom_group' => [
'id',
'name',
'table_name',
@@ -422,8 +428,8 @@ public static function getTree(
'extends_entity_column_id',
'extends_entity_column_value',
'max_multiple',
- ),
- );
+ ],
+ ];
$current_db_version = CRM_Core_DAO::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config::domainID());
$is_public_version = $current_db_version >= '4.7.19' ? 1 : 0;
if ($is_public_version) {
@@ -436,15 +442,15 @@ public static function getTree(
// Supply defaults and remove unknown array keys
$toReturn = array_intersect_key(array_filter($toReturn) + $tableData, $tableData);
// Merge in required fields that we must have
- $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], array('id', 'column_name', 'data_type')));
- $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], array('id', 'is_multiple', 'table_name', 'name')));
+ $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
+ $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
// Validate return fields
$toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField::fieldKeys()));
$toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup::fieldKeys()));
}
// create select
- $select = array();
+ $select = [];
foreach ($toReturn as $tableName => $tableColumn) {
foreach ($tableColumn as $columnName) {
$select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
@@ -473,11 +479,13 @@ public static function getTree(
$in = "'$entityType'";
}
+ $params = [];
+ $sqlParamKey = 1;
if (!empty($subTypes)) {
foreach ($subTypes as $key => $subType) {
$subTypeClauses[] = self::whereListHas("civicrm_custom_group.extends_entity_column_value", self::validateSubTypeByEntity($entityType, $subType));
}
- $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
+ $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
if (!$onlySubType) {
$subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
}
@@ -489,7 +497,9 @@ public static function getTree(
AND $subTypeClause
";
if ($subName) {
- $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
+ $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
+ $params[$sqlParamKey] = [$subName, 'String'];
+ $sqlParamKey = $sqlParamKey + 1;
}
}
else {
@@ -503,11 +513,10 @@ public static function getTree(
}
}
- $params = array();
if ($groupID > 0) {
// since we want a specific group id we add it to the where clause
- $strWhere .= " AND civicrm_custom_group.id = %1";
- $params[1] = array($groupID, 'Integer');
+ $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
+ $params[$sqlParamKey] = [$groupID, 'Integer'];
}
elseif (!$groupID) {
// since groupID is false we need to show all Inline groups
@@ -547,16 +556,15 @@ public static function getTree(
$cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
$multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
$cache = CRM_Utils_Cache::singleton();
- $tablesWithEntityData = array();
if ($fromCache) {
$groupTree = $cache->get($cacheKey);
$multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
}
if (empty($groupTree)) {
- $groupTree = $multipleFieldGroups = array();
+ $groupTree = $multipleFieldGroups = [];
$crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
- $customValueTables = array();
+ $customValueTables = [];
// process records
while ($crmDAO->fetch()) {
@@ -568,7 +576,7 @@ public static function getTree(
}
// create an array for groups if it does not exist
if (!array_key_exists($groupID, $groupTree)) {
- $groupTree[$groupID] = array();
+ $groupTree[$groupID] = [];
$groupTree[$groupID]['id'] = $groupID;
// populate the group information
@@ -587,15 +595,15 @@ public static function getTree(
}
$groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
}
- $groupTree[$groupID]['fields'] = array();
+ $groupTree[$groupID]['fields'] = [];
- $customValueTables[$crmDAO->civicrm_custom_group_table_name] = array();
+ $customValueTables[$crmDAO->civicrm_custom_group_table_name] = [];
}
// add the fields now (note - the query row will always contain a field)
// we only reset this once, since multiple values come is as multiple rows
if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
- $groupTree[$groupID]['fields'][$fieldId] = array();
+ $groupTree[$groupID]['fields'][$fieldId] = [];
}
$customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
@@ -613,16 +621,16 @@ public static function getTree(
}
if (!empty($customValueTables)) {
- $groupTree['info'] = array('tables' => $customValueTables);
+ $groupTree['info'] = ['tables' => $customValueTables];
}
$cache->set($cacheKey, $groupTree);
$cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
}
- //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
+ // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
// and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
- $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
- $singleFieldTables = array();
+ $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
+ $singleFieldTables = [];
// now that we have all the groups and fields, lets get the values
// since we need to know the table and field names
// add info to groupTree
@@ -630,15 +638,15 @@ public static function getTree(
if (isset($groupTree['info']) && !empty($groupTree['info']) &&
!empty($groupTree['info']['tables']) && $singleRecord != 'new'
) {
- $select = $from = $where = array();
+ $select = $from = $where = [];
$groupTree['info']['where'] = NULL;
foreach ($groupTree['info']['tables'] as $table => $fields) {
$groupTree['info']['from'][] = $table;
- $select = array(
+ $select = [
"{$table}.id as {$table}_id",
"{$table}.entity_id as {$table}_entity_id",
- );
+ ];
foreach ($fields as $column => $dontCare) {
$select[] = "{$table}.{$column} as {$table}_{$column}";
}
@@ -677,7 +685,6 @@ public static function getTree(
*
* @return string
* @throws \CRM_Core_Exception
- * @throws \CiviCRM_API3_Exception
*/
protected static function validateSubTypeByEntity($entityType, $subType) {
$subType = trim($subType, CRM_Core_DAO::VALUE_SEPARATOR);
@@ -686,7 +693,7 @@ protected static function validateSubTypeByEntity($entityType, $subType) {
}
$contactTypes = CRM_Contact_BAO_ContactType::basicTypeInfo(TRUE);
- $contactTypes = array_merge($contactTypes, array('Event' => 1));
+ $contactTypes = array_merge($contactTypes, ['Event' => 1]);
if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
throw new CRM_Core_Exception('Invalid Entity Filter');
@@ -709,8 +716,9 @@ protected static function validateSubTypeByEntity($entityType, $subType) {
* @return string
* SQL condition.
*/
- static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO::VALUE_SEPARATOR) {
- $bareValue = trim($value, $delimiter); // ?
+ private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO::VALUE_SEPARATOR) {
+ // ?
+ $bareValue = trim($value, $delimiter);
$escapedValue = CRM_Utils_Type::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
return "($column LIKE \"$escapedValue\")";
}
@@ -718,7 +726,6 @@ static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO:
/**
* Check whether the custom group has any data for the given entity.
*
- *
* @param int $entityID
* Id of entity for whom we are checking data for.
* @param string $table
@@ -729,7 +736,7 @@ static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO:
* @return bool
* does this entity have data in this custom table
*/
- static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
+ public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
$query = "
SELECT count(id)
FROM $table
@@ -758,7 +765,7 @@ static public function customGroupDataExistsForEntity($entityID, $table, $getCou
* @param array $singleFieldTablesWithEntityData
* Array of tables in which this entity has data.
*/
- static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
+ public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
$select = implode(', ', $entitySingleSelectClauses);
$fromSQL = " (SELECT $entityID as entity_id ) as first ";
foreach ($singleFieldTablesWithEntityData as $table) {
@@ -786,10 +793,10 @@ static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $enti
* Array of select clauses relevant to the entity.
* @param array $multipleFieldTablesWithEntityData
* Array of tables in which this entity has data.
- * @param varchar $singleRecord
+ * @param string|int $singleRecord
* holds 'new' or id if view/edit/copy form for a single record is being loaded.
*/
- static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
+ public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
$select = implode(',', $selectClauses);
$query = "
@@ -801,7 +808,7 @@ static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $en
$offset = $singleRecord - 1;
$query .= " LIMIT {$offset}, 1";
}
- self::buildTreeEntityDataFromQuery($groupTree, $query, array($table), $singleRecord);
+ self::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
}
}
@@ -817,10 +824,10 @@ static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $en
* @param array $includedTables
* Tables to include - required because the function (for historical reasons).
* iterates through the group tree
- * @param varchar $singleRecord
+ * @param string|int $singleRecord
* holds 'new' OR id if view/edit/copy form for a single record is being loaded.
*/
- static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
+ public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
foreach ($groupTree as $groupID => $group) {
@@ -854,10 +861,10 @@ static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includ
* Custom group ID.
* @param int $fieldID
* Custom field ID.
- * @param varchar $singleRecord
+ * @param string|int $singleRecord
* holds 'new' or id if loading view/edit/copy for a single record.
*/
- static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
+ public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
$column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
$idName = "{$table}_id";
$fieldName = "{$table}_{$column}";
@@ -870,28 +877,30 @@ static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID,
if ($fileDAO->find(TRUE)) {
$entityIDName = "{$table}_entity_id";
+ $fileHash = CRM_Core_BAO_File::generateFileHash($dao->$entityIDName, $fileDAO->id);
$customValue['id'] = $dao->$idName;
$customValue['data'] = $fileDAO->uri;
$customValue['fid'] = $fileDAO->id;
- $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
+ $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
$customValue['displayURL'] = NULL;
$deleteExtra = ts('Are you sure you want to delete attached file.');
- $deleteURL = array(
- CRM_Core_Action::DELETE => array(
+ $deleteURL = [
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete Attached File'),
'url' => 'civicrm/file',
- 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
+ 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
. '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
- ),
- );
+ ],
+ ];
$customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL,
CRM_Core_Action::DELETE,
- array(
+ [
'id' => $fileDAO->id,
'eid' => $dao->$entityIDName,
'fid' => $fieldID,
- ),
+ 'fcs' => $fileHash,
+ ],
ts('more'),
FALSE,
'file.manage.delete',
@@ -914,7 +923,7 @@ static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID,
);
$customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) .
$fileDAO->uri;
- list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId, NULL, NULL);
+ list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId);
if ($path && file_exists($path)) {
list($imageWidth, $imageHeight) = getimagesize($path);
list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
@@ -925,27 +934,27 @@ static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID,
}
}
else {
- $customValue = array(
+ $customValue = [
'id' => $dao->$idName,
'data' => '',
- );
+ ];
}
}
else {
- $customValue = array(
+ $customValue = [
'id' => $dao->$idName,
'data' => $dao->$fieldName,
- );
+ ];
}
if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
- $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
+ $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
}
if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
- $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array($singleRecord => $customValue);
+ $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
}
elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
- $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
+ $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
}
else {
$groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
@@ -977,21 +986,18 @@ public static function getTitle($id) {
* @param array $extends
* Which table does it extend if any.
*
- * @param null $inSelector
+ * @param bool $inSelector
*
* @return array
* array consisting of all group and field details
*/
public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
// create a new tree
- $groupTree = array();
- $select = $from = $where = $orderBy = '';
-
- $tableData = array();
+ $groupTree = [];
// using tableData to build the queryString
- $tableData = array(
- 'civicrm_custom_field' => array(
+ $tableData = [
+ 'civicrm_custom_field' => [
'id',
'label',
'data_type',
@@ -1014,8 +1020,8 @@ public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$ex
'is_view',
'option_group_id',
'in_selector',
- ),
- 'civicrm_custom_group' => array(
+ ],
+ 'civicrm_custom_group' => [
'id',
'name',
'title',
@@ -1027,25 +1033,25 @@ public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$ex
'extends_entity_column_value',
'table_name',
'is_multiple',
- ),
- );
+ ],
+ ];
// create select
- $s = array();
+ $s = [];
foreach ($tableData as $tableName => $tableColumn) {
foreach ($tableColumn as $columnName) {
$s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
}
}
$select = 'SELECT ' . implode(', ', $s);
- $params = array();
+ $params = [];
// from, where, order by
$from = " FROM civicrm_custom_field, civicrm_custom_group";
$where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
AND civicrm_custom_group.is_active = 1
AND civicrm_custom_field.is_active = 1 ";
if ($groupId) {
- $params[1] = array($groupId, 'Integer');
+ $params[1] = [$groupId, 'Integer'];
$where .= " AND civicrm_custom_group.id = %1";
}
@@ -1058,7 +1064,7 @@ public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$ex
}
if ($extends) {
- $clause = array();
+ $clause = [];
foreach ($extends as $e) {
$clause[] = "civicrm_custom_group.extends = '$e'";
}
@@ -1068,7 +1074,7 @@ public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$ex
if (in_array('Activity', $extends)) {
$extendValues = implode(',', array_keys(CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
$where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
- $params[2] = array(CRM_Core_DAO::VALUE_SEPARATOR, 'String');
+ $params[2] = [CRM_Core_DAO::VALUE_SEPARATOR, 'String'];
}
}
@@ -1093,7 +1099,7 @@ public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$ex
// create an array for groups if it does not exist
if (!array_key_exists($groupId, $groupTree)) {
- $groupTree[$groupId] = array();
+ $groupTree[$groupId] = [];
$groupTree[$groupId]['id'] = $groupId;
foreach ($tableData['civicrm_custom_group'] as $v) {
@@ -1106,11 +1112,11 @@ public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$ex
$groupTree[$groupId][$v] = $crmDAO->$fullField;
}
- $groupTree[$groupId]['fields'] = array();
+ $groupTree[$groupId]['fields'] = [];
}
// add the fields now (note - the query row will always contain a field)
- $groupTree[$groupId]['fields'][$fieldId] = array();
+ $groupTree[$groupId]['fields'][$fieldId] = [];
$groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
foreach ($tableData['civicrm_custom_field'] as $v) {
@@ -1143,7 +1149,7 @@ public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%
// add whereAdd for entity type
self::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
- $groups = array();
+ $groups = [];
$permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, NULL, TRUE);
$customGroupDAO->whereAdd($permissionClause);
@@ -1154,12 +1160,12 @@ public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%
// process each group with menu tab
while ($customGroupDAO->fetch()) {
- $group = array();
+ $group = [];
$group['id'] = $customGroupDAO->id;
$group['path'] = $path;
$group['title'] = "$customGroupDAO->title";
$group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
- $group['extra'] = array('gid' => $customGroupDAO->id);
+ $group['extra'] = ['gid' => $customGroupDAO->id];
$group['table_name'] = $customGroupDAO->table_name;
$group['is_multiple'] = $customGroupDAO->is_multiple;
$groups[] = $group;
@@ -1259,6 +1265,10 @@ public static function getAllCustomGroupsByBaseEntity($entityType) {
*/
private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
$addSubtypeClause = FALSE;
+ // This function isn't really accessible with user data but since the string
+ // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
+ // precaution.
+ $entityType = CRM_Core_DAO::escapeString($entityType);
switch ($entityType) {
case 'Contact':
@@ -1281,13 +1291,7 @@ private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID =
}
break;
- case 'Case':
- case 'Location':
- case 'Address':
- case 'Activity':
- case 'Contribution':
- case 'Membership':
- case 'Participant':
+ default:
$customGroupDAO->whereAdd("extends IN ('$entityType')");
break;
}
@@ -1296,7 +1300,7 @@ private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID =
$csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
if (!empty($csType)) {
- $subtypeClause = array();
+ $subtypeClause = [];
foreach ($csType as $subtype) {
$subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype .
CRM_Core_DAO::VALUE_SEPARATOR;
@@ -1388,9 +1392,8 @@ public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $
switch ($field['html_type']) {
case 'Multi-Select':
- case 'AdvMulti-Select':
case 'CheckBox':
- $defaults[$elementName] = array();
+ $defaults[$elementName] = [];
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
if ($viewMode) {
$checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
@@ -1508,7 +1511,6 @@ public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
//added Multi-Select option in the below if-statement
if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
- $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
) {
$groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
@@ -1525,13 +1527,12 @@ public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
// field exists in db so populate value from "form".
- $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
+ $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
}
switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
- //added for CheckBox
-
+ // added for CheckBox
case 'CheckBox':
if (!empty($v)) {
$customValue = array_keys($v);
@@ -1544,10 +1545,6 @@ public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
}
break;
- //added for Advanced Multi-Select
-
- case 'AdvMulti-Select':
- //added for Multi-Select
case 'Multi-Select':
if (!empty($v)) {
$groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR
@@ -1566,12 +1563,12 @@ public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
case 'File':
if ($skipFile) {
- continue;
+ break;
}
- //store the file in d/b
+ // store the file in d/b
$entityId = explode('=', $groupTree['info']['where'][0]);
- $fileParams = array('upload_date' => date('YmdHis'));
+ $fileParams = ['upload_date' => date('YmdHis')];
if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
$fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
@@ -1590,11 +1587,11 @@ public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
$v['type']
);
}
- $defaults = array();
- $paramsFile = array(
+ $defaults = [];
+ $paramsFile = [
'entity_table' => $groupTree[$groupID]['table_name'],
'entity_id' => $entityId[1],
- );
+ ];
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_EntityFile',
$paramsFile,
@@ -1623,6 +1620,8 @@ public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
* Return inactive custom groups.
* @param string $prefix
* Prefix for custom grouptree assigned to template.
+ *
+ * @throws \CiviCRM_API3_Exception
*/
public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
$form->assign_by_ref("{$prefix}groupTree", $groupTree);
@@ -1641,6 +1640,9 @@ public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FAL
$fieldId = $field['id'];
$elementName = $field['element_name'];
CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $required);
+ if ($form->getAction() == CRM_Core_Action::VIEW) {
+ $form->getElement($elementName)->freeze();
+ }
}
}
}
@@ -1654,21 +1656,22 @@ public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FAL
* The type of custom group we are using.
*
* @return array
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public static function extractGetParams(&$form, $type) {
if (empty($_GET)) {
- return array();
+ return [];
}
$groupTree = CRM_Core_BAO_CustomGroup::getTree($type);
- $customValue = array();
- $htmlType = array(
+ $customValue = [];
+ $htmlType = [
'CheckBox',
'Multi-Select',
- 'AdvMulti-Select',
'Select',
'Radio',
- );
+ ];
foreach ($groupTree as $group) {
if (!isset($group['fields'])) {
@@ -1686,13 +1689,12 @@ public static function extractGetParams(&$form, $type) {
$valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value);
}
if ($field['html_type'] == 'CheckBox' ||
- $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
) {
$value = str_replace("|", ",", $value);
$mulValues = explode(',', $value);
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
- $val = array();
+ $val = [];
foreach ($mulValues as $v1) {
foreach ($customOption as $coID => $coValue) {
if (strtolower(trim($coValue['label'])) ==
@@ -1726,19 +1728,7 @@ public static function extractGetParams(&$form, $type) {
}
}
elseif ($field['data_type'] == 'Date') {
- if (!empty($value)) {
- $time = NULL;
- if (!empty($field['time_format'])) {
- $time = CRM_Utils_Request::retrieve($fieldName .
- '_time', 'String', $form, FALSE, NULL, 'GET');
- }
- list($value, $time) = CRM_Utils_Date::setDateDefaults($value .
- ' ' . $time);
- if (!empty($field['time_format'])) {
- $customValue[$fieldName . '_time'] = $time;
- }
- }
- $valid = TRUE;
+ $valid = CRM_Utils_Rule::date($value);
}
if ($valid) {
@@ -1834,7 +1824,7 @@ public static function mapTableName($table) {
default:
$query = "
SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
- $qParams = array(1 => array($table, 'String'));
+ $qParams = [1 => [$table, 'String']];
$result = CRM_Core_DAO::singleValueQuery($query, $qParams);
if ($result) {
@@ -1852,13 +1842,15 @@ public static function mapTableName($table) {
/**
* @param $group
+ *
+ * @throws \Exception
*/
public static function createTable($group) {
- $params = array(
+ $params = [
'name' => $group->table_name,
'is_multiple' => $group->is_multiple ? 1 : 0,
'extends_name' => self::mapTableName($group->extends),
- );
+ ];
$tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params);
@@ -1866,18 +1858,19 @@ public static function createTable($group) {
}
/**
- * Function returns formatted groupTree, sothat form can be easily build in template
+ * Function returns formatted groupTree, so that form can be easily built in template
*
* @param array $groupTree
* @param int $groupCount
- * Group count by default 1, but can varry for multiple value custom data.
- * @param object $form
+ * Group count by default 1, but can vary for multiple value custom data.
+ * @param \CRM_Core_Form $form
*
* @return array
+ * @throws \CRM_Core_Exception
*/
public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
- $formattedGroupTree = array();
- $uploadNames = $formValues = array();
+ $formattedGroupTree = [];
+ $uploadNames = $formValues = [];
// retrieve qf key from url
$qfKey = CRM_Utils_Request::retrieve('qf', 'String');
@@ -1961,7 +1954,7 @@ public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NU
/**
* Build custom data view.
*
- * @param CRM_Core_Form $form
+ * @param CRM_Core_Form|CRM_Core_Page $form
* Page object.
* @param array $groupTree
* @param bool $returnCount
@@ -1972,9 +1965,10 @@ public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NU
* @param int $entityId
*
* @return array|int
+ * @throws \Exception
*/
public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
- $details = array();
+ $details = [];
foreach ($groupTree as $key => $group) {
if ($key === 'info') {
continue;
@@ -1994,13 +1988,13 @@ public static function buildCustomDataView(&$form, &$groupTree, $returnCount = F
$details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
$details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
$details[$groupID][$values['id']]['style'] = CRM_Utils_Array::value('style', $group);
- $details[$groupID][$values['id']]['fields'][$k] = array(
+ $details[$groupID][$values['id']]['fields'][$k] = [
'field_title' => CRM_Utils_Array::value('label', $properties),
'field_type' => CRM_Utils_Array::value('html_type', $properties),
'field_data_type' => CRM_Utils_Array::value('data_type', $properties),
'field_value' => CRM_Core_BAO_CustomField::displayValue($values['data'], $properties['id'], $entityId),
'options_per_line' => CRM_Utils_Array::value('options_per_line', $properties),
- );
+ ];
// editable = whether this set contains any non-read-only fields
if (!isset($details[$groupID][$values['id']]['editable'])) {
$details[$groupID][$values['id']]['editable'] = FALSE;
@@ -2027,19 +2021,19 @@ public static function buildCustomDataView(&$form, &$groupTree, $returnCount = F
$details[$groupID][0]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
$details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
$details[$groupID][0]['style'] = CRM_Utils_Array::value('style', $group);
- $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties));
+ $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array::value('label', $properties)];
}
}
}
if ($returnCount) {
- //return a single value count if group id is passed to function
- //else return a groupId and count mapped array
+ // return a single value count if group id is passed to function
+ // else return a groupId and count mapped array
if (!empty($gID)) {
return count($details[$gID]);
}
else {
- $countValue = array();
+ $countValue = [];
foreach ($details as $key => $value) {
$countValue[$key] = count($details[$key]);
}
@@ -2066,7 +2060,7 @@ public static function getGroupTitles($fieldIds) {
return NULL;
}
- $groupLabels = array();
+ $groupLabels = [];
$fIds = "(" . implode(',', $fieldIds) . ")";
$query = "
@@ -2078,12 +2072,12 @@ public static function getGroupTitles($fieldIds) {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $groupLabels[$dao->fieldID] = array(
+ $groupLabels[$dao->fieldID] = [
'fieldID' => $dao->fieldID,
'fieldLabel' => $dao->fieldLabel,
'groupID' => $dao->groupID,
'groupTitle' => $dao->groupTitle,
- );
+ ];
}
return $groupLabels;
@@ -2136,13 +2130,14 @@ public static function isGroupEmpty($gID) {
*
* @return array
* Array of types.
+ * @throws \Exception
*/
- public static function getExtendedObjectTypes(&$types = array()) {
- static $flag = FALSE, $objTypes = array();
+ public static function getExtendedObjectTypes(&$types = []) {
+ static $flag = FALSE, $objTypes = [];
if (!$flag) {
- $extendObjs = array();
- CRM_Core_OptionValue::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
+ $extendObjs = [];
+ CRM_Core_OptionValue::getValues(['name' => 'cg_extend_objects'], $extendObjs);
foreach ($extendObjs as $ovId => $ovValues) {
if ($ovValues['description']) {
@@ -2150,7 +2145,7 @@ public static function getExtendedObjectTypes(&$types = array()) {
list($callback, $args) = explode(';', trim($ovValues['description']));
if (empty($args)) {
- $args = array();
+ $args = [];
}
if (!is_array($args)) {
@@ -2158,8 +2153,7 @@ public static function getExtendedObjectTypes(&$types = array()) {
}
list($className) = explode('::', $callback);
- require_once str_replace('_', DIRECTORY_SEPARATOR, $className) .
- '.php';
+ require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
$objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
}
@@ -2178,7 +2172,7 @@ public static function getExtendedObjectTypes(&$types = array()) {
* @return bool
*/
public static function hasReachedMaxLimit($customGroupId, $entityId) {
- //check whether the group is multiple
+ // check whether the group is multiple
$isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
$isMultiple = ($isMultiple) ? TRUE : FALSE;
$hasReachedMax = FALSE;
@@ -2190,9 +2184,9 @@ public static function hasReachedMaxLimit($customGroupId, $entityId) {
}
else {
$tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
- //count the number of entries for a entity
+ // count the number of entries for a entity
$sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
- $params = array(1 => array($entityId, 'Integer'));
+ $params = [1 => [$entityId, 'Integer']];
$count = CRM_Core_DAO::singleValueQuery($sql, $params);
if ($count >= $maxMultiple) {
@@ -2207,7 +2201,7 @@ public static function hasReachedMaxLimit($customGroupId, $entityId) {
* @return array
*/
public static function getMultipleFieldGroup() {
- $multipleGroup = array();
+ $multipleGroup = [];
$dao = new CRM_Core_DAO_CustomGroup();
$dao->is_multiple = 1;
$dao->is_active = 1;
diff --git a/CRM/Core/BAO/CustomOption.php b/CRM/Core/BAO/CustomOption.php
index efbb6518c4e6..0eb77b2cfff9 100644
--- a/CRM/Core/BAO/CustomOption.php
+++ b/CRM/Core/BAO/CustomOption.php
@@ -1,9 +1,9 @@
$label) {
- $options[] = array(
+ $options[] = [
'label' => $label,
'value' => $value,
- );
+ ];
}
return $options;
@@ -102,8 +102,8 @@ public static function getCustomOption(
* -rp = rowcount
* -page= offset
*/
- static public function getOptionListSelector(&$params) {
- $options = array();
+ public static function getOptionListSelector(&$params) {
+ $options = [];
$field = CRM_Core_BAO_CustomField::getFieldObject($params['fid']);
$defVal = CRM_Utils_Array::explodePadded($field->default_value);
@@ -115,7 +115,7 @@ static public function getOptionListSelector(&$params) {
if (!$field->option_group_id) {
return $options;
}
- $queryParams = array(1 => array($field->option_group_id, 'Integer'));
+ $queryParams = [1 => [$field->option_group_id, 'Integer']];
$total = "SELECT COUNT(*) FROM civicrm_option_value WHERE option_group_id = %1";
$params['total'] = CRM_Core_DAO::singleValueQuery($total, $queryParams);
@@ -126,10 +126,10 @@ static public function getOptionListSelector(&$params) {
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
$links = CRM_Custom_Page_Option::actionLinks();
- $fields = array('id', 'label', 'value');
+ $fields = ['id', 'label', 'value'];
$config = CRM_Core_Config::singleton();
while ($dao->fetch()) {
- $options[$dao->id] = array();
+ $options[$dao->id] = [];
foreach ($fields as $k) {
$options[$dao->id][$k] = $dao->$k;
}
@@ -143,7 +143,19 @@ static public function getOptionListSelector(&$params) {
$class .= ' disabled';
$action -= CRM_Core_Action::DISABLE;
}
- if (in_array($field->html_type, array('CheckBox', 'AdvMulti-Select', 'Multi-Select'))) {
+
+ $isGroupLocked = (bool) CRM_Core_DAO::getFieldValue(
+ CRM_Core_DAO_OptionGroup::class,
+ $field->option_group_id,
+ 'is_locked'
+ );
+
+ // disable deletion of option values for locked option groups
+ if (($action & CRM_Core_Action::DELETE) && $isGroupLocked) {
+ $action -= CRM_Core_Action::DELETE;
+ }
+
+ if (in_array($field->html_type, ['CheckBox', 'Multi-Select'])) {
if (isset($defVal) && in_array($dao->value, $defVal)) {
$options[$dao->id]['is_default'] = '';
}
@@ -159,16 +171,16 @@ static public function getOptionListSelector(&$params) {
$options[$dao->id]['is_default'] = '';
}
}
-
+ $options[$dao->id]['description'] = $dao->description;
$options[$dao->id]['class'] = $dao->id . ',' . $class;
$options[$dao->id]['is_active'] = empty($dao->is_active) ? ts('No') : ts('Yes');
$options[$dao->id]['links'] = CRM_Core_Action::formLink($links,
$action,
- array(
+ [
'id' => $dao->id,
'fid' => $params['fid'],
'gid' => $params['gid'],
- ),
+ ],
ts('more'),
FALSE,
'customOption.row.actions',
@@ -197,22 +209,22 @@ public static function del($optionId) {
WHERE v.id = %1
AND g.id = f.option_group_id
AND g.id = v.option_group_id";
- $params = array(1 => array($optionId, 'Integer'));
+ $params = [1 => [$optionId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
if (in_array($dao->dataType,
- array('Int', 'Float', 'Money', 'Boolean')
+ ['Int', 'Float', 'Money', 'Boolean']
)) {
$value = 0;
}
else {
$value = '';
}
- $params = array(
+ $params = [
'optionId' => $optionId,
'fieldId' => $dao->id,
'value' => $value,
- );
+ ];
// delete this value from the tables
self::updateCustomValues($params);
@@ -221,7 +233,7 @@ public static function del($optionId) {
DELETE
FROM civicrm_option_value
WHERE id = %1";
- $params = array(1 => array($optionId, 'Integer'));
+ $params = [1 => [$optionId, 'Integer']];
CRM_Core_DAO::executeQuery($query, $params);
}
}
@@ -247,7 +259,7 @@ public static function updateCustomValues($params) {
civicrm_custom_field f
WHERE f.custom_group_id = g.id
AND f.id = %1";
- $queryParams = array(1 => array($params['fieldId'], 'Integer'));
+ $queryParams = [1 => [$params['fieldId'], 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
if ($dao->fetch()) {
if ($dao->dataType == 'Money') {
@@ -267,19 +279,18 @@ public static function updateCustomValues($params) {
else {
$dataType = $dao->dataType;
}
- $queryParams = array(
- 1 => array(
+ $queryParams = [
+ 1 => [
$params['value'],
$dataType,
- ),
- 2 => array(
+ ],
+ 2 => [
$params['optionId'],
'Integer',
- ),
- );
+ ],
+ ];
break;
- case 'AdvMulti-Select':
case 'Multi-Select':
case 'CheckBox':
$oldString = CRM_Core_DAO::VALUE_SEPARATOR . $oldValue . CRM_Core_DAO::VALUE_SEPARATOR;
@@ -287,10 +298,10 @@ public static function updateCustomValues($params) {
$query = "
UPDATE {$dao->tableName}
SET {$dao->columnName} = REPLACE( {$dao->columnName}, %1, %2 )";
- $queryParams = array(
- 1 => array($oldString, 'String'),
- 2 => array($newString, 'String'),
- );
+ $queryParams = [
+ 1 => [$oldString, 'String'],
+ 2 => [$newString, 'String'],
+ ];
break;
default:
@@ -323,24 +334,22 @@ public static function updateValue($optionId, $newValue) {
$customGroup->id = $customField->custom_group_id;
$customGroup->find(TRUE);
if (CRM_Core_BAO_CustomField::isSerialized($customField)) {
- $params = array(
- 1 => array(CRM_Utils_Array::implodePadded($oldValue), 'String'),
- 2 => array(CRM_Utils_Array::implodePadded($newValue), 'String'),
- 3 => array('%' . CRM_Utils_Array::implodePadded($oldValue) . '%', 'String'),
- );
+ $params = [
+ 1 => [CRM_Utils_Array::implodePadded($oldValue), 'String'],
+ 2 => [CRM_Utils_Array::implodePadded($newValue), 'String'],
+ 3 => ['%' . CRM_Utils_Array::implodePadded($oldValue) . '%', 'String'],
+ ];
}
else {
- $params = array(
- 1 => array($oldValue, 'String'),
- 2 => array($newValue, 'String'),
- 3 => array($oldValue, 'String'),
- );
+ $params = [
+ 1 => [$oldValue, 'String'],
+ 2 => [$newValue, 'String'],
+ 3 => [$oldValue, 'String'],
+ ];
}
$sql = "UPDATE `{$customGroup->table_name}` SET `{$customField->column_name}` = REPLACE(`{$customField->column_name}`, %1, %2) WHERE `{$customField->column_name}` LIKE %3";
- $customGroup->free();
CRM_Core_DAO::executeQuery($sql, $params);
}
- $customField->free();
}
}
diff --git a/CRM/Core/BAO/CustomQuery.php b/CRM/Core/BAO/CustomQuery.php
index 81e5eb876f7a..790487e43891 100644
--- a/CRM/Core/BAO/CustomQuery.php
+++ b/CRM/Core/BAO/CustomQuery.php
@@ -1,9 +1,9 @@
'civicrm_contact',
'Individual' => 'civicrm_contact',
'Household' => 'civicrm_contact',
@@ -126,7 +126,7 @@ class CRM_Core_BAO_CustomQuery {
'Address' => 'civicrm_address',
'Campaign' => 'civicrm_campaign',
'Survey' => 'civicrm_survey',
- );
+ ];
/**
* Class constructor.
@@ -140,19 +140,19 @@ class CRM_Core_BAO_CustomQuery {
* @param bool $contactSearch
* @param array $locationSpecificFields
*/
- public function __construct($ids, $contactSearch = FALSE, $locationSpecificFields = array()) {
+ public function __construct($ids, $contactSearch = FALSE, $locationSpecificFields = []) {
$this->_ids = &$ids;
$this->_locationSpecificCustomFields = $locationSpecificFields;
- $this->_select = array();
- $this->_element = array();
- $this->_tables = array();
- $this->_whereTables = array();
- $this->_where = array();
- $this->_qill = array();
- $this->_options = array();
+ $this->_select = [];
+ $this->_element = [];
+ $this->_tables = [];
+ $this->_whereTables = [];
+ $this->_where = [];
+ $this->_qill = [];
+ $this->_options = [];
- $this->_fields = array();
+ $this->_fields = [];
$this->_contactSearch = $contactSearch;
if (empty($this->_ids)) {
@@ -179,6 +179,7 @@ public function __construct($ids, $contactSearch = FALSE, $locationSpecificField
while ($dao->fetch()) {
// get the group dao to figure which class this custom field extends
$extends = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $dao->custom_group_id, 'extends');
+ $extendsTable = '';
if (array_key_exists($extends, self::$extendsMap)) {
$extendsTable = self::$extendsMap[$extends];
}
@@ -186,7 +187,7 @@ public function __construct($ids, $contactSearch = FALSE, $locationSpecificField
// if $extends is a subtype, refer contact table
$extendsTable = self::$extendsMap['Contact'];
}
- $this->_fields[$dao->id] = array(
+ $this->_fields[$dao->id] = [
'id' => $dao->id,
'label' => $dao->label,
'extends' => $extendsTable,
@@ -196,18 +197,18 @@ public function __construct($ids, $contactSearch = FALSE, $locationSpecificField
'column_name' => $dao->column_name,
'table_name' => $dao->table_name,
'option_group_id' => $dao->option_group_id,
- );
+ ];
// Deprecated (and poorly named) cache of field attributes
- $this->_options[$dao->id] = array(
- 'attributes' => array(
+ $this->_options[$dao->id] = [
+ 'attributes' => [
'label' => $dao->label,
'data_type' => $dao->data_type,
'html_type' => $dao->html_type,
- ),
- );
+ ],
+ ];
- $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $dao->id, array(), 'search');
+ $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $dao->id, [], 'search');
if ($options) {
$this->_options[$dao->id] += $options;
}
@@ -294,8 +295,6 @@ public function where() {
continue;
}
- $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
-
foreach ($values as $tuple) {
list($name, $op, $value, $grouping, $wildcard) = $tuple;
@@ -334,12 +333,12 @@ public function where() {
// fix $value here to escape sql injection attacks
if (!is_array($value)) {
if ($field['data_type'] == 'String') {
- $value = CRM_Utils_Type::escape($strtolower($value), 'String');
+ $value = CRM_Utils_Type::escape($value, 'String');
}
elseif ($value) {
$value = CRM_Utils_Type::escape($value, 'Integer');
}
- $value = str_replace(array('[', ']', ','), array('\[', '\]', '[:comma:]'), $value);
+ $value = str_replace(['[', ']', ','], ['\[', '\]', '[:comma:]'], $value);
$value = str_replace('|', '[:separator:]', $value);
}
elseif ($isSerialized) {
@@ -350,7 +349,7 @@ public function where() {
// CRM-19006: escape characters like comma, | before building regex pattern
$value = (array) $value;
foreach ($value as $key => $val) {
- $value[$key] = str_replace(array('[', ']', ','), array('\[', '\]', '[:comma:]'), $val);
+ $value[$key] = str_replace(['[', ']', ','], ['\[', '\]', '[:comma:]'], $val);
$value[$key] = str_replace('|', '[:separator:]', $value[$key]);
}
$value = implode(',', $value);
@@ -360,7 +359,7 @@ public function where() {
if ($isSerialized && !CRM_Utils_System::isNull($value) && !strstr($op, 'NULL') && !strstr($op, 'LIKE')) {
$sp = CRM_Core_DAO::VALUE_SEPARATOR;
$value = str_replace(",", "$sp|$sp", $value);
- $value = str_replace(array('[:comma:]', '(', ')'), array(',', '[[.left-parenthesis.]]', '[[.right-parenthesis.]]'), $value);
+ $value = str_replace(['[:comma:]', '(', ')'], [',', '[(]', '[)]'], $value);
$op = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT RLIKE' : 'RLIKE';
$value = $sp . $value . $sp;
@@ -391,7 +390,7 @@ public function where() {
case 'Int':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));;
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['label'], 2 => $qillOp, 3 => $qillValue]);;
break;
case 'Boolean':
@@ -406,34 +405,40 @@ public function where() {
$qillValue = $value ? 'Yes' : 'No';
}
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['label'], 2 => $qillOp, 3 => $qillValue]);
break;
case 'Link':
case 'Memo':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['label'], 2 => $qillOp, 3 => $qillValue]);
break;
case 'Money':
$value = CRM_Utils_Array::value($op, (array) $value, $value);
if (is_array($value)) {
foreach ($value as $key => $val) {
- $value[$key] = CRM_Utils_Rule::cleanMoney($value[$key]);
+ // @todo - this clean money should be in the form layer - it's highly likely to be doing more harm than good here
+ // Note the only place I can find that this code is reached by is searching a custom money field in advanced search.
+ // with euro style comma separators this doesn't work - with or without this cleanMoney.
+ // So this should be removed but is not increasing the brokeness IMHO
+ $value[$op][$key] = CRM_Utils_Rule::cleanMoney($value[$key]);
}
}
else {
+ // @todo - this clean money should be in the form layer - it's highly likely to be doing more harm than good here
+ // comments per above apply. cleanMoney
$value = CRM_Utils_Rule::cleanMoney($value);
}
case 'Float':
$this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
- $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
+ $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['label'], 2 => $qillOp, 3 => $qillValue]);
break;
case 'Date':
- $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
- list($qillOp, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $field['label'], $value, $op, array(), CRM_Utils_Type::T_DATE);
+ $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Date');
+ list($qillOp, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $field['label'], $value, $op, [], CRM_Utils_Type::T_DATE);
$this->_qill[$grouping][] = "{$field['label']} $qillOp '$qillVal'";
break;
@@ -471,7 +476,7 @@ public function query() {
$whereStr = NULL;
if (!empty($this->_where)) {
- $clauses = array();
+ $clauses = [];
foreach ($this->_where as $grouping => $values) {
if (!empty($values)) {
$clauses[] = ' ( ' . implode(' AND ', $values) . ' ) ';
@@ -482,11 +487,11 @@ public function query() {
}
}
- return array(
+ return [
implode(' , ', $this->_select),
implode(' ', $this->_tables),
$whereStr,
- );
+ ];
}
}
diff --git a/CRM/Core/BAO/CustomValue.php b/CRM/Core/BAO/CustomValue.php
index 0134869a4840..7df55cc393e1 100644
--- a/CRM/Core/BAO/CustomValue.php
+++ b/CRM/Core/BAO/CustomValue.php
@@ -1,9 +1,9 @@
$formValues[$key]);
+ $formValues[$key] = ['IN' => $formValues[$key]];
}
}
elseif (($htmlType == 'TextArea' ||
($htmlType == 'Text' && $dataType == 'String')
) && strstr($formValues[$key], '%')
) {
- $formValues[$key] = array('LIKE' => $formValues[$key]);
+ $formValues[$key] = ['LIKE' => $formValues[$key]];
}
}
}
@@ -207,13 +206,18 @@ public static function deleteCustomValue($customValueID, $customGroupID) {
// first we need to find custom value table, from custom group ID
$tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupID, 'table_name');
+ // Retrieve the $entityId so we can pass that to the hook.
+ $entityID = CRM_Core_DAO::singleValueQuery("SELECT entity_id FROM {$tableName} WHERE id = %1", [
+ 1 => [$customValueID, 'Integer'],
+ ]);
+
// delete custom value from corresponding custom value table
$sql = "DELETE FROM {$tableName} WHERE id = {$customValueID}";
CRM_Core_DAO::executeQuery($sql);
CRM_Utils_Hook::custom('delete',
$customGroupID,
- NULL,
+ $entityID,
$customValueID
);
}
diff --git a/CRM/Core/BAO/CustomValueTable.php b/CRM/Core/BAO/CustomValueTable.php
index 9d8245380c59..759e83a71954 100644
--- a/CRM/Core/BAO/CustomValueTable.php
+++ b/CRM/Core/BAO/CustomValueTable.php
@@ -1,9 +1,9 @@
$tables) {
foreach ($tables as $index => $fields) {
$sqlOP = NULL;
@@ -53,8 +55,8 @@ public static function create(&$customParams) {
$hookOP = NULL;
$entityID = NULL;
$isMultiple = FALSE;
- $set = array();
- $params = array();
+ $set = [];
+ $params = [];
$count = 1;
foreach ($fields as $field) {
if (!$sqlOP) {
@@ -64,7 +66,7 @@ public static function create(&$customParams) {
if (array_key_exists('id', $field)) {
$sqlOP = "UPDATE $tableName ";
$where = " WHERE id = %{$count}";
- $params[$count] = array($field['id'], 'Integer');
+ $params[$count] = [$field['id'], 'Integer'];
$count++;
$hookOP = 'edit';
}
@@ -88,9 +90,9 @@ public static function create(&$customParams) {
elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) {
//fix for multi select state, CRM-3437
$mulValues = explode(',', $value);
- $validStates = array();
+ $validStates = [];
foreach ($mulValues as $key => $stateVal) {
- $states = array();
+ $states = [];
$states['state_province'] = trim($stateVal);
CRM_Utils_Array::lookupValue($states, 'state_province',
@@ -122,7 +124,6 @@ public static function create(&$customParams) {
case 'Country':
$type = 'Integer';
- $mulValues = explode(',', $value);
if (is_array($value)) {
$value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
$type = 'String';
@@ -130,9 +131,9 @@ public static function create(&$customParams) {
elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) {
//fix for multi select country, CRM-3437
$mulValues = explode(',', $value);
- $validCountries = array();
+ $validCountries = [];
foreach ($mulValues as $key => $countryVal) {
- $countries = array();
+ $countries = [];
$countries['country'] = trim($countryVal);
CRM_Utils_Array::lookupValue($countries, 'country',
CRM_Core_PseudoConstant::country(), TRUE
@@ -175,7 +176,6 @@ public static function create(&$customParams) {
$entityFileDAO->entity_id = $field['entity_id'];
$entityFileDAO->file_id = $field['file_id'];
$entityFileDAO->save();
- $entityFileDAO->free();
$value = $field['file_id'];
$type = 'String';
break;
@@ -217,20 +217,31 @@ public static function create(&$customParams) {
default:
break;
}
- if (strtolower($value) === "null") {
+ if ($value === 'null') {
// when unsetting a value to null, we don't need to validate the type
// https://projectllr.atlassian.net/browse/VGQBMP-20
$set[$field['column_name']] = $value;
}
else {
$set[$field['column_name']] = "%{$count}";
- $params[$count] = array($value, $type);
+ $params[$count] = [$value, $type];
$count++;
}
+
+ $fieldExtends = CRM_Utils_Array::value('extends', $field);
+ if (
+ CRM_Utils_Array::value('entity_table', $field) == 'civicrm_contact'
+ || $fieldExtends == 'Contact'
+ || $fieldExtends == 'Individual'
+ || $fieldExtends == 'Organization'
+ || $fieldExtends == 'Household'
+ ) {
+ $paramFieldsExtendContactForEntities[$entityID]['custom_' . CRM_Utils_Array::value('custom_field_id', $field)] = CRM_Utils_Array::value('custom_field_id', $field);
+ }
}
if (!empty($set)) {
- $setClause = array();
+ $setClause = [];
foreach ($set as $n => $v) {
$setClause[] = "$n = $v";
}
@@ -238,7 +249,7 @@ public static function create(&$customParams) {
if (!$where) {
// do this only for insert
$set['entity_id'] = "%{$count}";
- $params[$count] = array($entityID, 'Integer');
+ $params[$count] = [$entityID, 'Integer'];
$count++;
$fieldNames = implode(',', CRM_Utils_Type::escapeAll(array_keys($set), 'MysqlColumnNameOrAlias'));
@@ -262,6 +273,10 @@ public static function create(&$customParams) {
}
}
}
+
+ if (!empty($paramFieldsExtendContactForEntities)) {
+ CRM_Contact_BAO_Contact::updateGreetingsOnTokenFieldChange($paramFieldsExtendContactForEntities, ['contact_id' => $entityID]);
+ }
}
/**
@@ -324,10 +339,10 @@ public static function fieldToSQLType($type, $maxLength = 255) {
* @param int $entityID
*/
public static function store(&$params, $entityTable, $entityID) {
- $cvParams = array();
+ $cvParams = [];
foreach ($params as $fieldID => $param) {
foreach ($param as $index => $customValue) {
- $cvParam = array(
+ $cvParam = [
'entity_table' => $entityTable,
'entity_id' => $entityID,
'value' => $customValue['value'],
@@ -338,7 +353,7 @@ public static function store(&$params, $entityTable, $entityID) {
'column_name' => $customValue['column_name'],
'is_multiple' => CRM_Utils_Array::value('is_multiple', $customValue),
'file_id' => $customValue['file_id'],
- );
+ ];
// Fix Date type to be timestamp, since that is how we store in db.
if ($cvParam['type'] == 'Date') {
@@ -349,11 +364,11 @@ public static function store(&$params, $entityTable, $entityID) {
$cvParam['id'] = $customValue['id'];
}
if (!array_key_exists($customValue['table_name'], $cvParams)) {
- $cvParams[$customValue['table_name']] = array();
+ $cvParams[$customValue['table_name']] = [];
}
if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
- $cvParams[$customValue['table_name']][$index] = array();
+ $cvParams[$customValue['table_name']][$index] = [];
}
$cvParams[$customValue['table_name']][$index][] = $cvParam;
@@ -415,7 +430,7 @@ public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs
return NULL;
}
- $cond = array();
+ $cond = [];
if ($entityType) {
$cond[] = "cg.extends IN ( '$entityType' )";
}
@@ -455,12 +470,12 @@ public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs
";
$dao = CRM_Core_DAO::executeQuery($query);
- $select = $fields = $isMultiple = array();
+ $select = $fields = $isMultiple = [];
while ($dao->fetch()) {
if (!array_key_exists($dao->table_name, $select)) {
- $fields[$dao->table_name] = array();
- $select[$dao->table_name] = array();
+ $fields[$dao->table_name] = [];
+ $select[$dao->table_name] = [];
}
$fields[$dao->table_name][] = $dao->fieldID;
$select[$dao->table_name][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
@@ -468,7 +483,7 @@ public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs
$file[$dao->table_name][$dao->fieldID] = $dao->fieldDataType;
}
- $result = $sortedResult = array();
+ $result = $sortedResult = [];
foreach ($select as $tableName => $clauses) {
if (!empty($DTparams['sort'])) {
$query = CRM_Core_DAO::executeQuery("SELECT id FROM {$tableName} WHERE entity_id = {$entityID}");
@@ -520,36 +535,37 @@ public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs
* @return array
*/
public static function setValues(&$params) {
+ // For legacy reasons, accept this param in either format
+ if (empty($params['entityID']) && !empty($params['entity_id'])) {
+ $params['entityID'] = $params['entity_id'];
+ }
- if (!isset($params['entityID']) ||
- CRM_Utils_Type::escape($params['entityID'], 'Integer', FALSE) === NULL
- ) {
- return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
+ if (!isset($params['entityID']) || !CRM_Utils_Type::validate($params['entityID'], 'Integer', FALSE)) {
+ return CRM_Core_Error::createAPIError(ts('entity_id needs to be set and of type Integer'));
}
// first collect all the id/value pairs. The format is:
// custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
- $values = array();
- $fieldValues = array();
+ $fieldValues = [];
foreach ($params as $n => $v) {
if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($n, TRUE)) {
$fieldID = (int ) $customFieldInfo[0];
if (CRM_Utils_Type::escape($fieldID, 'Integer', FALSE) === NULL) {
return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
- array(1 => $fieldID)
+ [1 => $fieldID]
));
}
if (!array_key_exists($fieldID, $fieldValues)) {
- $fieldValues[$fieldID] = array();
+ $fieldValues[$fieldID] = [];
}
$id = -1;
if ($customFieldInfo[1]) {
$id = (int ) $customFieldInfo[1];
}
- $fieldValues[$fieldID][] = array(
+ $fieldValues[$fieldID][] = [
'value' => $v,
'id' => $id,
- );
+ ];
}
}
@@ -560,6 +576,7 @@ public static function setValues(&$params) {
SELECT cg.table_name as table_name ,
cg.id as cg_id ,
cg.is_multiple as is_multiple,
+ cg.extends as extends,
cf.column_name as column_name,
cf.id as cf_id ,
cf.data_type as data_type
@@ -570,7 +587,7 @@ public static function setValues(&$params) {
";
$dao = CRM_Core_DAO::executeQuery($sql);
- $cvParams = array();
+ $cvParams = [];
while ($dao->fetch()) {
$dataType = $dao->data_type == 'Date' ? 'Timestamp' : $dao->data_type;
@@ -600,14 +617,14 @@ public static function setValues(&$params) {
// Ensure that value is of the right data type
elseif (CRM_Utils_Type::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
return CRM_Core_Error::createAPIError(ts('value: %1 is not of the right field data type: %2',
- array(
+ [
1 => $fieldValue['value'],
2 => $dao->data_type,
- )
+ ]
));
}
- $cvParam = array(
+ $cvParam = [
'entity_id' => $params['entityID'],
'value' => $fieldValue['value'],
'type' => $dataType,
@@ -616,18 +633,23 @@ public static function setValues(&$params) {
'table_name' => $dao->table_name,
'column_name' => $dao->column_name,
'is_multiple' => $dao->is_multiple,
- );
+ 'extends' => $dao->extends,
+ ];
+
+ if (!empty($params['id'])) {
+ $cvParam['id'] = $params['id'];
+ }
if ($cvParam['type'] == 'File') {
$cvParam['file_id'] = $fieldValue['value'];
}
if (!array_key_exists($dao->table_name, $cvParams)) {
- $cvParams[$dao->table_name] = array();
+ $cvParams[$dao->table_name] = [];
}
if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name])) {
- $cvParams[$dao->table_name][$fieldValue['id']] = array();
+ $cvParams[$dao->table_name][$fieldValue['id']] = [];
}
if ($fieldValue['id'] > 0) {
@@ -639,7 +661,7 @@ public static function setValues(&$params) {
if (!empty($cvParams)) {
self::create($cvParams);
- return array('is_error' => 0, 'result' => 1);
+ return ['is_error' => 0, 'result' => 1];
}
return CRM_Core_Error::createAPIError(ts('Unknown error'));
@@ -677,21 +699,21 @@ public static function &getValues(&$params) {
// first collect all the ids. The format is:
// custom_ID
- $fieldIDs = array();
+ $fieldIDs = [];
foreach ($params as $n => $v) {
$key = $idx = NULL;
if (substr($n, 0, 7) == 'custom_') {
$idx = substr($n, 7);
if (CRM_Utils_Type::escape($idx, 'Integer', FALSE) === NULL) {
return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
- array(1 => $idx)
+ [1 => $idx]
));
}
$fieldIDs[] = (int ) $idx;
}
}
- $default = array('Contact', 'Individual', 'Household', 'Organization');
+ $default = ['Contact', 'Individual', 'Household', 'Organization'];
if (!($type = CRM_Utils_Array::value('entityType', $params)) ||
in_array($params['entityType'], $default)
) {
@@ -720,17 +742,17 @@ public static function &getValues(&$params) {
// note that this behaviour is undesirable from an API point of view - it should return an empty array
// since this is also called by the merger code & not sure the consequences of changing
// are just handling undoing this in the api layer. ie. converting the error back into a success
- $result = array(
+ $result = [
'is_error' => 1,
'error_message' => 'No values found for the specified entity ID and custom field(s).',
- );
+ ];
return $result;
}
else {
- $result = array(
+ $result = [
'is_error' => 0,
'entityID' => $params['entityID'],
- );
+ ];
foreach ($values as $id => $value) {
$result["custom_{$id}"] = $value;
}
diff --git a/CRM/Core/BAO/Dashboard.php b/CRM/Core/BAO/Dashboard.php
index 5b2cbffe993b..8b61cf0c0d66 100644
--- a/CRM/Core/BAO/Dashboard.php
+++ b/CRM/Core/BAO/Dashboard.php
@@ -1,9 +1,9 @@
id] = $values;
}
@@ -101,15 +102,15 @@ public static function getDashlets($all = TRUE, $checkPermission = TRUE) {
*/
public static function getContactDashlets($contactID = NULL) {
$contactID = $contactID ? $contactID : CRM_Core_Session::getLoggedInContactID();
- $dashlets = array();
+ $dashlets = [];
// Get contact dashboard dashlets.
- $results = civicrm_api3('DashboardContact', 'get', array(
+ $results = civicrm_api3('DashboardContact', 'get', [
'contact_id' => $contactID,
'is_active' => 1,
'dashboard_id.is_active' => 1,
- 'options' => array('sort' => 'weight', 'limit' => 0),
- 'return' => array(
+ 'options' => ['sort' => 'weight', 'limit' => 0],
+ 'return' => [
'id',
'weight',
'column_no',
@@ -121,12 +122,12 @@ public static function getContactDashlets($contactID = NULL) {
'dashboard_id.cache_minutes',
'dashboard_id.permission',
'dashboard_id.permission_operator',
- ),
- ));
+ ],
+ ]);
foreach ($results['values'] as $item) {
if (self::checkPermission(CRM_Utils_Array::value('dashboard_id.permission', $item), CRM_Utils_Array::value('dashboard_id.permission_operator', $item))) {
- $dashlets[$item['id']] = array(
+ $dashlets[$item['id']] = [
'dashboard_id' => $item['dashboard_id'],
'weight' => $item['weight'],
'column_no' => $item['column_no'],
@@ -135,14 +136,14 @@ public static function getContactDashlets($contactID = NULL) {
'url' => $item['dashboard_id.url'],
'cache_minutes' => $item['dashboard_id.cache_minutes'],
'fullscreen_url' => CRM_Utils_Array::value('dashboard_id.fullscreen_url', $item),
- );
+ ];
}
}
// If empty, then initialize default dashlets for this user.
if (!$results['count']) {
// They may just have disabled all their dashlets. Check if any records exist for this contact.
- if (!civicrm_api3('DashboardContact', 'getcount', array('contact_id' => $contactID))) {
+ if (!civicrm_api3('DashboardContact', 'getcount', ['contact_id' => $contactID])) {
$dashlets = self::initializeDashlets();
}
}
@@ -154,16 +155,16 @@ public static function getContactDashlets($contactID = NULL) {
* @return array
*/
public static function getContactDashletsForJS() {
- $data = array(array(), array());
+ $data = [[], []];
foreach (self::getContactDashlets() as $item) {
- $data[$item['column_no']][] = array(
+ $data[$item['column_no']][] = [
'id' => (int) $item['dashboard_id'],
'name' => $item['name'],
'title' => $item['label'],
'url' => self::parseUrl($item['url']),
'cacheMinutes' => $item['cache_minutes'],
'fullscreenUrl' => self::parseUrl($item['fullscreen_url']),
- );
+ ];
}
return $data;
}
@@ -175,27 +176,27 @@ public static function getContactDashletsForJS() {
* the default dashlets.
*
* @return array
- * Array of dashboard_id's
+ * Array of dashboard_id's
* @throws \CiviCRM_API3_Exception
*/
public static function initializeDashlets() {
- $dashlets = array();
- $getDashlets = civicrm_api3("Dashboard", "get", array(
- 'domain_id' => CRM_Core_Config::domainID(),
- 'option.limit' => 0,
- ));
+ $dashlets = [];
+ $getDashlets = civicrm_api3("Dashboard", "get", [
+ 'domain_id' => CRM_Core_Config::domainID(),
+ 'option.limit' => 0,
+ ]);
$contactID = CRM_Core_Session::getLoggedInContactID();
- $allDashlets = CRM_Utils_Array::index(array('name'), $getDashlets['values']);
- $defaultDashlets = array();
- $defaults = array('blog' => 1, 'getting-started' => '0');
+ $allDashlets = CRM_Utils_Array::index(['name'], $getDashlets['values']);
+ $defaultDashlets = [];
+ $defaults = ['blog' => 1, 'getting-started' => '0'];
foreach ($defaults as $name => $column) {
if (!empty($allDashlets[$name]) && !empty($allDashlets[$name]['id'])) {
- $defaultDashlets[$name] = array(
+ $defaultDashlets[$name] = [
'dashboard_id' => $allDashlets[$name]['id'],
'is_active' => 1,
'column_no' => $column,
'contact_id' => $contactID,
- );
+ ];
}
}
CRM_Utils_Hook::dashboard_defaults($allDashlets, $defaultDashlets);
@@ -209,7 +210,7 @@ public static function initializeDashlets() {
else {
$assignDashlets = civicrm_api3("dashboard_contact", "create", $defaultDashlet);
$values = $assignDashlets['values'][$assignDashlets['id']];
- $dashlets[$assignDashlets['id']] = array(
+ $dashlets[$assignDashlets['id']] = [
'dashboard_id' => $values['dashboard_id'],
'weight' => $values['weight'],
'column_no' => $values['column_no'],
@@ -218,7 +219,7 @@ public static function initializeDashlets() {
'cache_minutes' => $dashlet['cache_minutes'],
'url' => $dashlet['url'],
'fullscreen_url' => CRM_Utils_Array::value('fullscreen_url', $dashlet),
- );
+ ];
}
}
}
@@ -271,10 +272,8 @@ public static function checkPermission($permission, $operator) {
}
// hack to handle case permissions
- if (!$componentName && in_array($key, array(
- 'access my cases and activities',
- 'access all cases and activities',
- ))
+ if (!$componentName
+ && in_array($key, ['access my cases and activities', 'access all cases and activities'])
) {
$componentName = 'CiviCase';
}
@@ -335,7 +334,7 @@ public static function saveDashletChanges($columns, $contactID = NULL) {
throw new RuntimeException("Failed to determine contact ID");
}
- $dashletIDs = array();
+ $dashletIDs = [];
if (is_array($columns)) {
foreach ($columns as $colNo => $dashlets) {
if (!is_int($colNo)) {
@@ -428,7 +427,7 @@ public static function addContactDashlet($dashlet) {
// if dashlet is created by admin then you need to add it all contacts.
// else just add to contact who is creating this dashlet
- $contactIDs = array();
+ $contactIDs = [];
if ($admin) {
$query = "SELECT distinct( contact_id )
FROM civicrm_dashboard_contact";
@@ -475,7 +474,7 @@ public static function addContactDashlet($dashlet) {
*/
public static function addContactDashletToDashboard(&$params) {
$valuesString = NULL;
- $columns = array();
+ $columns = [];
foreach ($params as $dashboardIDs) {
$contactID = CRM_Utils_Array::value('contact_id', $dashboardIDs);
$dashboardID = CRM_Utils_Array::value('dashboard_id', $dashboardIDs);
diff --git a/CRM/Core/BAO/Discount.php b/CRM/Core/BAO/Discount.php
index 5fc881edf939..dfef62e32882 100644
--- a/CRM/Core/BAO/Discount.php
+++ b/CRM/Core/BAO/Discount.php
@@ -1,9 +1,9 @@
entity_id = $entityId;
$dao->entity_table = $entityTable;
diff --git a/CRM/Core/BAO/Domain.php b/CRM/Core/BAO/Domain.php
index 5c519baf1f15..d4ccd6c9d1d0 100644
--- a/CRM/Core/BAO/Domain.php
+++ b/CRM/Core/BAO/Domain.php
@@ -1,9 +1,9 @@
_location == NULL) {
$domain = self::getDomain(NULL);
- $params = array(
+ $params = [
'contact_id' => $domain->contact_id,
- );
+ ];
$this->_location = CRM_Core_BAO_Location::getValues($params, TRUE);
if (empty($this->_location)) {
@@ -142,7 +144,7 @@ public static function edit(&$params, &$id) {
*/
public static function create($params) {
$domain = new CRM_Core_DAO_Domain();
- $domain->copyValues($params);
+ $domain->copyValues($params, TRUE);
$domain->save();
return $domain;
}
@@ -164,30 +166,35 @@ public static function multipleDomains() {
/**
* @param bool $skipFatal
- *
+ * @param bool $returnString
* @return array
* name & email for domain
* @throws Exception
*/
- public static function getNameAndEmail($skipFatal = FALSE) {
+ public static function getNameAndEmail($skipFatal = FALSE, $returnString = FALSE) {
$fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
if (!empty($fromEmailAddress)) {
+ if ($returnString) {
+ // Return a string like: "Demonstrators Anonymous"
+ return $fromEmailAddress;
+ }
foreach ($fromEmailAddress as $key => $value) {
$email = CRM_Utils_Mail::pluckEmailFromHeader($value);
$fromArray = explode('"', $value);
$fromName = CRM_Utils_Array::value(1, $fromArray);
break;
}
- return array($fromName, $email);
+ return [$fromName, $email];
}
- elseif ($skipFatal) {
- return array('', '');
+
+ if ($skipFatal) {
+ return [NULL, NULL];
}
- $url = CRM_Utils_System::url('civicrm/admin/domain',
- 'action=update&reset=1'
+ $url = CRM_Utils_System::url('civicrm/admin/options/from_email_address',
+ 'reset=1'
);
- $status = ts("There is no valid default from email address configured for the domain. You can configure here Configure From Email Address.", array(1 => $url));
+ $status = ts("There is no valid default from email address configured for the domain. You can configure here Configure From Email Address.", [1 => $url]);
CRM_Core_Error::fatal($status);
}
@@ -201,7 +208,7 @@ public static function addContactToDomainGroup($contactID) {
$groupID = self::getGroupId();
if ($groupID) {
- $contactIDs = array($contactID);
+ $contactIDs = [$contactID];
CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
return $groupID;
@@ -252,7 +259,7 @@ public static function isDomainGroup($groupId) {
*/
public static function getChildGroupIds() {
$domainGroupID = self::getGroupId();
- $childGrps = array();
+ $childGrps = [];
if ($domainGroupID) {
$childGrps = CRM_Contact_BAO_GroupNesting::getChildGroupIds($domainGroupID);
@@ -268,7 +275,7 @@ public static function getChildGroupIds() {
*/
public static function getContactList() {
$siteGroups = CRM_Core_BAO_Domain::getChildGroupIds();
- $siteContacts = array();
+ $siteContacts = [];
if (!empty($siteGroups)) {
$query = "
@@ -287,26 +294,39 @@ public static function getContactList() {
/**
* CRM-20308 & CRM-19657
- * Return domain information / user information for the useage in receipts
- * Try default from adress then fall back to using logged in user details
+ * Return domain information / user information for the usage in receipts
+ * Try default from address then fall back to using logged in user details
*/
public static function getDefaultReceiptFrom() {
- $domain = civicrm_api3('domain', 'getsingle', array('id' => CRM_Core_Config::domainID()));
+ $domain = civicrm_api3('domain', 'getsingle', ['id' => CRM_Core_Config::domainID()]);
if (!empty($domain['from_email'])) {
- return array($domain['from_name'], $domain['from_email']);
+ return [$domain['from_name'], $domain['from_email']];
}
if (!empty($domain['domain_email'])) {
- return array($domain['name'], $domain['domain_email']);
+ return [$domain['name'], $domain['domain_email']];
}
- $userID = CRM_Core_Session::singleton()->getLoggedInContactID();
$userName = '';
$userEmail = '';
+
+ if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ return [$userName, $userEmail];
+ }
+
+ $userID = CRM_Core_Session::singleton()->getLoggedInContactID();
if (!empty($userID)) {
list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
}
// If still empty fall back to the logged in user details.
// return empty values no matter what.
- return array($userName, $userEmail);
+ return [$userName, $userEmail];
+ }
+
+ /**
+ * Get address to be used for system from addresses when a reply is not expected.
+ */
+ public static function getNoReplyEmailAddress() {
+ $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
+ return "do-not-reply@$emailDomain";
}
}
diff --git a/CRM/Core/BAO/Email.php b/CRM/Core/BAO/Email.php
index 3bfee2724e89..20c6875d6a68 100644
--- a/CRM/Core/BAO/Email.php
+++ b/CRM/Core/BAO/Email.php
@@ -1,9 +1,9 @@
array(
+ $params = [
+ 1 => [
$id,
'Integer',
- ),
- );
+ ],
+ ];
- $emails = $values = array();
+ $emails = $values = [];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
- $values = array(
+ $values = [
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'on_hold' => $dao->on_hold,
'id' => $dao->email_id,
'email' => $dao->email,
'locationTypeId' => $dao->locationTypeId,
- );
+ ];
if ($updateBlankLocInfo) {
$emails[$count++] = $values;
@@ -207,24 +207,24 @@ public static function allEntityEmails(&$entityElements) {
AND ltype.id = e.location_type_id
ORDER BY e.is_primary DESC, email_id ASC ";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$entityId,
'Integer',
- ),
- );
+ ],
+ ];
- $emails = array();
+ $emails = [];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
- $emails[$dao->email_id] = array(
+ $emails[$dao->email_id] = [
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'on_hold' => $dao->on_hold,
'id' => $dao->email_id,
'email' => $dao->email,
'locationTypeId' => $dao->locationTypeId,
- );
+ ];
}
return $emails;
@@ -237,10 +237,20 @@ public static function allEntityEmails(&$entityElements) {
* Email object.
*/
public static function holdEmail(&$email) {
+ if ($email->id && $email->on_hold === NULL) {
+ // email is being updated but no change to on_hold.
+ return;
+ }
+ if ($email->on_hold === 'null' || $email->on_hold === NULL) {
+ // legacy handling, deprecated.
+ $email->on_hold = 0;
+ }
+ $email->on_hold = (int) $email->on_hold;
+
//check for update mode
if ($email->id) {
- $params = array(1 => array($email->id, 'Integer'));
- if ($email->on_hold && $email->on_hold != 'null') {
+ $params = [1 => [$email->id, 'Integer']];
+ if ($email->on_hold) {
$sql = "
SELECT id
FROM civicrm_email
@@ -252,7 +262,8 @@ public static function holdEmail(&$email) {
$email->reset_date = 'null';
}
}
- elseif ($email->on_hold == 'null') {
+ elseif ($email->on_hold === 0) {
+ // we do this lookup to see if reset_date should be changed.
$sql = "
SELECT id
FROM civicrm_email
@@ -269,12 +280,26 @@ public static function holdEmail(&$email) {
}
}
else {
- if (($email->on_hold != 'null') && $email->on_hold) {
+ if ($email->on_hold) {
$email->hold_date = date('YmdHis');
}
}
}
+ /**
+ * Generate an array of Domain email addresses.
+ * @return array $domainEmails;
+ */
+ public static function domainEmails() {
+ $domainEmails = [];
+ $domainFrom = (array) CRM_Core_OptionGroup::values('from_email_address');
+ foreach (array_keys($domainFrom) as $k) {
+ $domainEmail = $domainFrom[$k];
+ $domainEmails[$domainEmail] = htmlspecialchars($domainEmail);
+ }
+ return $domainEmails;
+ }
+
/**
* Build From Email as the combination of all the email ids of the logged in user and
* the domain email id
@@ -283,22 +308,21 @@ public static function holdEmail(&$email) {
* an array of email ids
*/
public static function getFromEmail() {
- $contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
- $fromEmailValues = array();
-
// add all configured FROM email addresses
- $domainFrom = CRM_Core_OptionGroup::values('from_email_address');
- foreach (array_keys($domainFrom) as $k) {
- $domainEmail = $domainFrom[$k];
- $fromEmailValues[$domainEmail] = htmlspecialchars($domainEmail);
+ $fromEmailValues = self::domainEmails();
+
+ if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ return $fromEmailValues;
}
+ $contactFromEmails = [];
// add logged in user's active email ids
+ $contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
if ($contactID) {
$contactEmails = self::allEmails($contactID);
- $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
+ $fromDisplayName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
- foreach ($contactEmails as $emailVal) {
+ foreach ($contactEmails as $emailId => $emailVal) {
$email = trim($emailVal['email']);
if (!$email || $emailVal['on_hold']) {
continue;
@@ -309,10 +333,10 @@ public static function getFromEmail() {
if (!empty($emailVal['is_primary'])) {
$fromEmailHtml .= ' ' . ts('(preferred)');
}
- $fromEmailValues[$fromEmail] = $fromEmailHtml;
+ $contactFromEmails[$emailId] = $fromEmailHtml;
}
}
- return $fromEmailValues;
+ return CRM_Utils_Array::crmArrayMerge($contactFromEmails, $fromEmailValues);
}
/**
diff --git a/CRM/Core/BAO/EntityTag.php b/CRM/Core/BAO/EntityTag.php
index accc5d6d0826..e7ec387c7971 100644
--- a/CRM/Core/BAO/EntityTag.php
+++ b/CRM/Core/BAO/EntityTag.php
@@ -1,9 +1,9 @@
entity_id = $entityID;
@@ -89,7 +89,7 @@ public static function add(&$params) {
//invoke post hook on entityTag
// we are using this format to keep things consistent between the single and bulk operations
// so a bit different from other post hooks
- $object = array(0 => array(0 => $params['entity_id']), 1 => $params['entity_table']);
+ $object = [0 => [0 => $params['entity_id']], 1 => $params['entity_table']];
CRM_Utils_Hook::post('create', 'EntityTag', $params['tag_id'], $object);
}
return $entityTag;
@@ -125,7 +125,7 @@ public static function del(&$params) {
//invoke post hook on entityTag
if (!empty($params['tag_id'])) {
- $object = array(0 => array(0 => $params['entity_id']), 1 => $params['entity_table']);
+ $object = [0 => [0 => $params['entity_id']], 1 => $params['entity_table']];
CRM_Utils_Hook::post('delete', 'EntityTag', $params['tag_id'], $object);
}
}
@@ -148,10 +148,10 @@ public static function del(&$params) {
public static function addEntitiesToTag(&$entityIds, $tagId, $entityTable, $applyPermissions) {
$numEntitiesAdded = 0;
$numEntitiesNotAdded = 0;
- $entityIdsAdded = array();
+ $entityIdsAdded = [];
//invoke pre hook for entityTag
- $preObject = array($entityIds, $entityTable);
+ $preObject = [$entityIds, $entityTable];
CRM_Utils_Hook::pre('create', 'EntityTag', $tagId, $preObject);
foreach ($entityIds as $entityId) {
@@ -177,12 +177,12 @@ public static function addEntitiesToTag(&$entityIds, $tagId, $entityTable, $appl
}
//invoke post hook on entityTag
- $object = array($entityIdsAdded, $entityTable);
+ $object = [$entityIdsAdded, $entityTable];
CRM_Utils_Hook::post('create', 'EntityTag', $tagId, $object);
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
- return array(count($entityIds), $numEntitiesAdded, $numEntitiesNotAdded);
+ return [count($entityIds), $numEntitiesAdded, $numEntitiesNotAdded];
}
/**
@@ -226,10 +226,10 @@ public static function checkPermissionOnEntityTag($entityID, $entityTable) {
public static function removeEntitiesFromTag(&$entityIds, $tagId, $entityTable, $applyPermissions) {
$numEntitiesRemoved = 0;
$numEntitiesNotRemoved = 0;
- $entityIdsRemoved = array();
+ $entityIdsRemoved = [];
//invoke pre hook for entityTag
- $preObject = array($entityIds, $entityTable);
+ $preObject = [$entityIds, $entityTable];
CRM_Utils_Hook::pre('delete', 'EntityTag', $tagId, $preObject);
foreach ($entityIds as $entityId) {
@@ -255,12 +255,12 @@ public static function removeEntitiesFromTag(&$entityIds, $tagId, $entityTable,
}
//invoke post hook on entityTag
- $object = array($entityIdsRemoved, $entityTable);
+ $object = [$entityIdsRemoved, $entityTable];
CRM_Utils_Hook::post('delete', 'EntityTag', $tagId, $object);
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
- return array(count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved);
+ return [count($entityIds), $numEntitiesRemoved, $numEntitiesNotRemoved];
}
/**
@@ -280,12 +280,12 @@ public static function create(&$params, $entityTable, $entityID) {
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($params)) {
- $params = array();
+ $params = [];
}
// this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
if (!is_array($entityTag)) {
- $entityTag = array();
+ $entityTag = [];
}
// check which values has to be inserted/deleted for contact
@@ -315,7 +315,7 @@ public static function create(&$params, $entityTable, $entityID) {
* array of entity ids
*/
public function getEntitiesByTag($tag) {
- $entityIds = array();
+ $entityIds = [];
$entityTagDAO = new CRM_Core_DAO_EntityTag();
$entityTagDAO->tag_id = $tag->id;
$entityTagDAO->find();
@@ -334,7 +334,7 @@ public function getEntitiesByTag($tag) {
* @return array
*/
public static function getContactTags($contactID, $count = FALSE) {
- $contactTags = array();
+ $contactTags = [];
if (!$count) {
$select = "SELECT ct.id, ct.name ";
}
@@ -373,7 +373,7 @@ public static function getContactTags($contactID, $count = FALSE) {
* @return array
*/
public static function getChildEntityTags($parentId, $entityId, $entityTable = 'civicrm_contact') {
- $entityTags = array();
+ $entityTags = [];
$query = "SELECT ct.id as tag_id, name FROM civicrm_tag ct
INNER JOIN civicrm_entity_tag et ON ( et.entity_id = {$entityId} AND
et.entity_table = '{$entityTable}' AND et.tag_id = ct.id)
@@ -382,10 +382,10 @@ public static function getChildEntityTags($parentId, $entityId, $entityTable = '
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $entityTags[$dao->tag_id] = array(
+ $entityTags[$dao->tag_id] = [
'id' => $dao->tag_id,
'name' => $dao->name,
- );
+ ];
}
return $entityTags;
@@ -403,26 +403,26 @@ public static function getChildEntityTags($parentId, $entityId, $entityTable = '
* @return array
*/
public function mergeTags($tagAId, $tagBId) {
- $queryParams = array(
- 1 => array($tagAId, 'Integer'),
- 2 => array($tagBId, 'Integer'),
- );
+ $queryParams = [
+ 1 => [$tagAId, 'Integer'],
+ 2 => [$tagBId, 'Integer'],
+ ];
// re-compute used_for field
$query = "SELECT id, name, used_for FROM civicrm_tag WHERE id IN (%1, %2)";
$dao = CRM_Core_DAO::executeQuery($query, $queryParams);
- $tags = array();
+ $tags = [];
while ($dao->fetch()) {
$label = ($dao->id == $tagAId) ? 'tagA' : 'tagB';
$tags[$label] = $dao->name;
- $tags["{$label}_used_for"] = $dao->used_for ? explode(",", $dao->used_for) : array();
+ $tags["{$label}_used_for"] = $dao->used_for ? explode(",", $dao->used_for) : [];
}
$usedFor = array_merge($tags["tagA_used_for"], $tags["tagB_used_for"]);
$usedFor = implode(',', array_unique($usedFor));
$tags["used_for"] = explode(",", $usedFor);
// get all merge queries together
- $sqls = array(
+ $sqls = [
// 1. update entity tag entries
"UPDATE IGNORE civicrm_entity_tag SET tag_id = %1 WHERE tag_id = %2",
// 2. move children
@@ -435,8 +435,8 @@ public function mergeTags($tagAId, $tagBId) {
"DELETE et2.* from civicrm_entity_tag et1 INNER JOIN civicrm_entity_tag et2 ON et1.entity_table = et2.entity_table AND et1.entity_id = et2.entity_id AND et1.tag_id = et2.tag_id WHERE et1.id < et2.id",
// 6. remove orphaned entity_tags
"DELETE FROM civicrm_entity_tag WHERE tag_id = %2",
- );
- $tables = array('civicrm_entity_tag', 'civicrm_tag');
+ ];
+ $tables = ['civicrm_entity_tag', 'civicrm_tag'];
// Allow hook_civicrm_merge() to add SQL statements for the merge operation AND / OR
// perform any other actions like logging
@@ -467,8 +467,8 @@ public function mergeTags($tagAId, $tagBId) {
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
- $params = array();
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
+ $params = [];
if ($fieldName == 'tag' || $fieldName == 'tag_id') {
if (!empty($props['entity_table'])) {
@@ -479,7 +479,7 @@ public static function buildOptions($fieldName, $context = NULL, $props = array(
// Output tag list as nested hierarchy
// TODO: This will only work when api.entity is "entity_tag". What about others?
if ($context == 'search' || $context == 'create') {
- $dummyArray = array();
+ $dummyArray = [];
return CRM_Core_BAO_Tag::getTags(CRM_Utils_Array::value('entity_table', $props, 'civicrm_contact'), $dummyArray, CRM_Utils_Array::value('parent_id', $params), '- ');
}
}
@@ -487,8 +487,8 @@ public static function buildOptions($fieldName, $context = NULL, $props = array(
$options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
// Special formatting for validate/match context
- if ($fieldName == 'entity_table' && in_array($context, array('validate', 'match'))) {
- $options = array();
+ if ($fieldName == 'entity_table' && in_array($context, ['validate', 'match'])) {
+ $options = [];
foreach (self::buildOptions($fieldName) as $tableName => $label) {
$bao = CRM_Core_DAO_AllCoreTables::getClassForTable($tableName);
$apiName = CRM_Core_DAO_AllCoreTables::getBriefName($bao);
diff --git a/CRM/Core/BAO/Extension.php b/CRM/Core/BAO/Extension.php
index ebfcc5c16e82..8bbe63fffacf 100644
--- a/CRM/Core/BAO/Extension.php
+++ b/CRM/Core/BAO/Extension.php
@@ -1,9 +1,9 @@
array($schemaVersion, 'String'),
- 2 => array($fullName, 'String'),
- );
+ $params = [
+ 1 => [$schemaVersion, 'String'],
+ 2 => [$fullName, 'String'],
+ ];
return CRM_Core_DAO::executeQuery($sql, $params);
}
@@ -98,9 +98,9 @@ public static function setSchemaVersion($fullName, $schemaVersion) {
*/
public static function getSchemaVersion($fullName) {
$sql = 'SELECT schema_version FROM civicrm_extension WHERE full_name = %1';
- $params = array(
- 1 => array($fullName, 'String'),
- );
+ $params = [
+ 1 => [$fullName, 'String'],
+ ];
return CRM_Core_DAO::singleValueQuery($sql, $params);
}
diff --git a/CRM/Core/BAO/File.php b/CRM/Core/BAO/File.php
index 7b0ade3794b2..c2c06bd279fb 100644
--- a/CRM/Core/BAO/File.php
+++ b/CRM/Core/BAO/File.php
@@ -1,9 +1,9 @@
copyValues($params);
+
+ if (empty($params['id']) && empty($params['created_id'])) {
+ $fileDAO->created_id = CRM_Core_Session::getLoggedInContactID();
+ }
+
+ $fileDAO->save();
+
+ CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
+
+ return $fileDAO;
+ }
/**
* @param int $fileID
* @param int $entityID
- * @param null $entityTable
*
* @return array
*/
- public static function path($fileID, $entityID, $entityTable = NULL) {
+ public static function path($fileID, $entityID) {
$entityFileDAO = new CRM_Core_DAO_EntityFile();
- if ($entityTable) {
- $entityFileDAO->entity_table = $entityTable;
- }
$entityFileDAO->entity_id = $entityID;
$entityFileDAO->file_id = $fileID;
@@ -63,15 +87,14 @@ public static function path($fileID, $entityID, $entityTable = NULL) {
$path = $config->customFileUploadDir . $fileDAO->uri;
if (file_exists($path) && is_readable($path)) {
- return array($path, $fileDAO->mime_type);
+ return [$path, $fileDAO->mime_type];
}
}
}
- return array(NULL, NULL);
+ return [NULL, NULL];
}
-
/**
* @param $data
* @param int $fileTypeID
@@ -187,7 +210,7 @@ public static function deleteFileReferences($fileID, $entityID, $fieldID) {
$fileDAO = new CRM_Core_DAO_File();
$fileDAO->id = $fileID;
if (!$fileDAO->find(TRUE)) {
- CRM_Core_Error::fatal();
+ throw new CRM_Core_Exception(ts('File not found'));
}
// lets call a pre hook before the delete, so attachments hooks can get the info before things
@@ -203,7 +226,7 @@ public static function deleteFileReferences($fileID, $entityID, $fieldID) {
$entityFileDAO->entity_table = $tableName;
if (!$entityFileDAO->find(TRUE)) {
- CRM_Core_Error::fatal(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
+ throw new CRM_Core_Exception(sprintf('No record found for given file ID - %d and entity ID - %d', $fileID, $entityID));
}
$entityFileDAO->delete();
@@ -211,7 +234,7 @@ public static function deleteFileReferences($fileID, $entityID, $fieldID) {
// also set the value to null of the table and column
$query = "UPDATE $tableName SET $columnName = null WHERE $columnName = %1";
- $params = array(1 => array($fileID, 'Integer'));
+ $params = [1 => [$fileID, 'Integer']];
CRM_Core_DAO::executeQuery($query, $params);
}
@@ -246,8 +269,8 @@ public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = N
list($sql, $params) = self::sql($entityTable, $entityID, $fileTypeID, $fileID);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
- $cfIDs = array();
- $cefIDs = array();
+ $cfIDs = [];
+ $cefIDs = [];
while ($dao->fetch()) {
$cfIDs[$dao->cfID] = $dao->uri;
$cefIDs[] = $dao->cefID;
@@ -262,13 +285,13 @@ public static function deleteEntityFile($entityTable, $entityID, $fileTypeID = N
if (!empty($cfIDs)) {
// Delete file only if there no any entity using this file.
- $deleteFiles = array();
+ $deleteFiles = [];
foreach ($cfIDs as $fId => $fUri) {
//delete tags from entity tag table
- $tagParams = array(
+ $tagParams = [
'entity_table' => 'civicrm_file',
'entity_id' => $fId,
- );
+ ];
CRM_Core_BAO_EntityTag::del($tagParams);
@@ -307,8 +330,9 @@ public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = F
list($sql, $params) = self::sql($entityTable, $entityID, NULL);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
- $results = array();
+ $results = [];
while ($dao->fetch()) {
+ $fileHash = self::generateFileHash($dao->entity_id, $dao->cfID);
$result['fileID'] = $dao->cfID;
$result['entityID'] = $dao->cefID;
$result['mime_type'] = $dao->mime_type;
@@ -316,7 +340,7 @@ public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = F
$result['description'] = $dao->description;
$result['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri);
$result['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
- $result['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}");
+ $result['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->cfID}&eid={$dao->entity_id}&fcs={$fileHash}");
$result['href'] = "{$result['cleanName']}";
$result['tag'] = CRM_Core_BAO_EntityTag::getTag($dao->cfID, 'civicrm_file');
$result['icon'] = CRM_Utils_File::getIconFromMimeType($dao->mime_type);
@@ -327,11 +351,11 @@ public static function getEntityFile($entityTable, $entityID, $addDeleteArgs = F
}
//fix tag names
- $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
+ $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]);
foreach ($results as &$values) {
if (!empty($values['tag'])) {
- $tagNames = array();
+ $tagNames = [];
foreach ($values['tag'] as $tid) {
$tagNames[] = $tags[$tid];
}
@@ -386,22 +410,22 @@ public static function sql($entityTable, $entityID, $fileTypeID = NULL, $fileID
AND CEF.entity_id = %2";
}
- $params = array(
- 1 => array($entityTable, 'String'),
- 2 => array($entityID, 'Integer'),
- );
+ $params = [
+ 1 => [$entityTable, 'String'],
+ 2 => [$entityID, 'Integer'],
+ ];
if ($fileTypeID !== NULL) {
$sql .= " AND CF.file_type_id = %3";
- $params[3] = array($fileTypeID, 'Integer');
+ $params[3] = [$fileTypeID, 'Integer'];
}
if ($fileID !== NULL) {
$sql .= " AND CF.id = %4";
- $params[4] = array($fileID, 'Integer');
+ $params[4] = [$fileID, 'Integer'];
}
- return array($sql, $params);
+ return [$sql, $params];
}
/**
@@ -458,25 +482,25 @@ public static function buildAttachment(&$form, $entityTable, $entityID = NULL, $
$form->setMaxFileSize($maxFileSize * 1024 * 1024);
$form->addRule("attachFile_$i",
ts('File size should be less than %1 MByte(s)',
- array(1 => $maxFileSize)
+ [1 => $maxFileSize]
),
'maxfilesize',
$maxFileSize * 1024 * 1024
);
- $form->addElement('text', "attachDesc_$i", NULL, array(
+ $form->addElement('text', "attachDesc_$i", NULL, [
'size' => 40,
'maxlength' => 255,
'placeholder' => ts('Description'),
- ));
+ ]);
if (!empty($tags)) {
$form->add('select', "tag_$i", ts('Tags'), $tags, FALSE,
- array(
+ [
'id' => "tags_$i",
'multiple' => 'multiple',
'class' => 'huge crm-select2',
'placeholder' => ts('- none -'),
- )
+ ]
);
}
CRM_Core_Form_Tag::buildQuickForm($form, $parentNames, 'civicrm_file', NULL, FALSE, TRUE, "file_taglist_$i");
@@ -504,7 +528,7 @@ public static function attachmentInfo($entityTable, $entityID, $separator = ' $attach) {
$currentAttachmentURL[] = $attach['href'];
}
@@ -541,7 +565,7 @@ public static function formatAttachment(
$attachFreeTags = "file_taglist_$i";
if (isset($formValues[$attachName]) && !empty($formValues[$attachName])) {
// add static tags if selects
- $tagParams = array();
+ $tagParams = [];
if (!empty($formValues[$attachTags])) {
foreach ($formValues[$attachTags] as $tag) {
$tagParams[$tag] = 1;
@@ -550,11 +574,11 @@ public static function formatAttachment(
// we dont care if the file is empty or not
// CRM-7448
- $extraParams = array(
+ $extraParams = [
'description' => $formValues[$attachDesc],
'tag' => $tagParams,
- 'attachment_taglist' => CRM_Utils_Array::value($attachFreeTags, $formValues, array()),
- );
+ 'attachment_taglist' => CRM_Utils_Array::value($attachFreeTags, $formValues, []),
+ ];
CRM_Utils_File::formatFile($formValues, $attachName, $extraParams);
@@ -601,7 +625,7 @@ public static function processAttachment(&$params, $entityTable, $entityID) {
public static function uploadNames() {
$numAttachments = Civi::settings()->get('max_attachments');
- $names = array();
+ $names = [];
for ($i = 1; $i <= $numAttachments; $i++) {
$names[] = "attachFile_{$i}";
}
@@ -655,7 +679,7 @@ public static function deleteURLArgs($entityTable, $entityID, $fileID) {
*
*/
public static function deleteAttachment() {
- $params = array();
+ $params = [];
$params['entityTable'] = CRM_Utils_Request::retrieve('entityTable', 'String', CRM_Core_DAO::$_nullObject, TRUE);
$params['entityID'] = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
$params['fileID'] = CRM_Utils_Request::retrieve('fileID', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
@@ -670,7 +694,6 @@ public static function deleteAttachment() {
self::deleteEntityFile($params['entityTable'], $params['entityID'], NULL, $params['fileID']);
}
-
/**
* Display paper icon for a file attachment -- CRM-13624
*
@@ -731,7 +754,7 @@ public static function paperIconAttachment($entityTable, $entityID) {
* @return CRM_Core_FileSearchInterface|NULL
*/
public static function getSearchService() {
- $fileSearches = array();
+ $fileSearches = [];
CRM_Utils_Hook::fileSearches($fileSearches);
// use the first available search
@@ -742,4 +765,58 @@ public static function getSearchService() {
return NULL;
}
+ /**
+ * Generates an access-token for downloading a specific file.
+ *
+ * @param int $entityId entity id the file is attached to
+ * @param int $fileId file ID
+ * @param int $genTs
+ * @param int $life
+ * @return string
+ */
+ public static function generateFileHash($entityId = NULL, $fileId = NULL, $genTs = NULL, $life = NULL) {
+ // Use multiple (but stable) inputs for hash information.
+ $siteKey = CRM_Utils_Constant::value('CIVICRM_SITE_KEY');
+ if (!$siteKey) {
+ throw new \CRM_Core_Exception("Cannot generate file access token. Please set CIVICRM_SITE_KEY.");
+ }
+
+ if (!$genTs) {
+ $genTs = time();
+ }
+ if (!$life) {
+ $days = Civi::settings()->get('checksum_timeout');
+ $life = 24 * $days;
+ }
+ // Trim 8 chars off the string, make it slightly easier to find
+ // but reveals less information from the hash.
+ $cs = hash_hmac('sha256', "entity={$entityId}&file={$fileId}&life={$life}", $siteKey);
+ return "{$cs}_{$genTs}_{$life}";
+ }
+
+ /**
+ * Validate a file access token.
+ *
+ * @param string $hash
+ * @param int $entityId Entity Id the file is attached to
+ * @param int $fileId File Id
+ * @return bool
+ */
+ public static function validateFileHash($hash, $entityId, $fileId) {
+ $input = CRM_Utils_System::explode('_', $hash, 3);
+ $inputTs = CRM_Utils_Array::value(1, $input);
+ $inputLF = CRM_Utils_Array::value(2, $input);
+ $testHash = CRM_Core_BAO_File::generateFileHash($entityId, $fileId, $inputTs, $inputLF);
+ if (hash_equals($testHash, $hash)) {
+ $now = time();
+ if ($inputTs + ($inputLF * 60 * 60) >= $now) {
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+ }
+ return FALSE;
+ }
+
}
diff --git a/CRM/Core/BAO/FinancialTrxn.php b/CRM/Core/BAO/FinancialTrxn.php
index 06f1021d38b2..6b3d45336992 100644
--- a/CRM/Core/BAO/FinancialTrxn.php
+++ b/CRM/Core/BAO/FinancialTrxn.php
@@ -1,9 +1,9 @@
CRM_Utils_Array::value('entity_table', $params, 'civicrm_contribution'),
'entity_id' => CRM_Utils_Array::value('entity_id', $params, CRM_Utils_Array::value('contribution_id', $params)),
'financial_trxn_id' => $trxn->id,
'amount' => $params['total_amount'],
- );
+ ];
$entityTrxn = new CRM_Financial_DAO_EntityFinancialTrxn();
$entityTrxn->copyValues($entityFinancialTrxnParams);
@@ -92,11 +93,11 @@ public static function getBalanceTrxnAmt($contributionId, $contributionFinancial
$toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionFinancialTypeId, 'Accounts Receivable Account is');
$q = "SELECT ft.id, ft.total_amount FROM civicrm_financial_trxn ft INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution') WHERE eft.entity_id = %1 AND ft.to_financial_account_id = %2";
- $p[1] = array($contributionId, 'Integer');
- $p[2] = array($toFinancialAccount, 'Integer');
+ $p[1] = [$contributionId, 'Integer'];
+ $p[2] = [$toFinancialAccount, 'Integer'];
$balanceAmtDAO = CRM_Core_DAO::executeQuery($q, $p);
- $ret = array();
+ $ret = [];
if ($balanceAmtDAO->N) {
$ret['total_amount'] = 0;
}
@@ -116,7 +117,7 @@ public static function getBalanceTrxnAmt($contributionId, $contributionFinancial
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
- * @return CRM_Contribute_BAO_ContributionType
+ * @return \CRM_Financial_DAO_FinancialTrxn
*/
public static function retrieve(&$params, &$defaults) {
$financialItem = new CRM_Financial_DAO_FinancialTrxn();
@@ -139,15 +140,16 @@ public static function retrieve(&$params, &$defaults) {
* @param bool $newTrxn
* @param string $whereClause
* Additional where parameters
+ * @param int $fromAccountID
*
* @return array
* array of category id's the contact belongs to.
*
*/
public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn = FALSE, $whereClause = '', $fromAccountID = NULL) {
- $ids = array('entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL);
+ $ids = ['entityFinancialTrxnId' => NULL, 'financialTrxnId' => NULL];
- $params = array(1 => array($entity_id, 'Integer'));
+ $params = [1 => [$entity_id, 'Integer']];
$condition = "";
if (!$newTrxn) {
$condition = " AND ((ceft1.entity_table IS NOT NULL) OR (cft.payment_instrument_id IS NOT NULL AND ceft1.entity_table IS NULL)) ";
@@ -155,7 +157,7 @@ public static function getFinancialTrxnId($entity_id, $orderBy = 'ASC', $newTrxn
if ($fromAccountID) {
$condition .= " AND (cft.from_financial_account_id <> %2 OR cft.from_financial_account_id IS NULL)";
- $params[2] = array($fromAccountID, 'Integer');
+ $params[2] = [$fromAccountID, 'Integer'];
}
if ($orderBy) {
$orderBy = CRM_Utils_Type::escape($orderBy, 'String');
@@ -197,7 +199,7 @@ public static function getRefundTransactionTrxnID($contributionID) {
* Get the transaction id for the (latest) refund associated with a contribution.
*
* @param int $contributionID
- * @return string
+ * @return array
*/
public static function getRefundTransactionIDs($contributionID) {
$refundStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
@@ -222,7 +224,7 @@ public static function getFinancialTrxnTotal($entity_id) {
WHERE ft.entity_table = 'civicrm_contribution' AND ft.entity_id = %1
";
- $sqlParams = array(1 => array($entity_id, 'Integer'));
+ $sqlParams = [1 => [$entity_id, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $sqlParams);
}
@@ -255,10 +257,10 @@ public static function getPayments($financial_trxn_id) {
AND ef2.entity_table = 'civicrm_financial_trxn'
AND ef1.entity_table = 'civicrm_financial_trxn'";
- $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
+ $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
$i = 0;
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$i]['financial_trxn_id'] = $dao->financial_trxn_id;
$result[$i]['amount'] = $dao->amount;
@@ -267,7 +269,7 @@ public static function getPayments($financial_trxn_id) {
if (empty($result)) {
$query = "SELECT sum( amount ) amount FROM civicrm_entity_financial_trxn WHERE financial_trxn_id =%1 AND entity_table = 'civicrm_financial_item'";
- $sqlParams = array(1 => array($financial_trxn_id, 'Integer'));
+ $sqlParams = [1 => [$financial_trxn_id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
if ($dao->fetch()) {
@@ -297,7 +299,7 @@ public static function getFinancialTrxnLineTotal($entity_id, $entity_table = 'ci
LEFT JOIN civicrm_line_item AS lt ON lt.id = fi.entity_id AND lt.entity_table = %2
WHERE lt.entity_id = %1 ";
- $sqlParams = array(1 => array($entity_id, 'Integer'), 2 => array($entity_table, 'String'));
+ $sqlParams = [1 => [$entity_id, 'Integer'], 2 => [$entity_table, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
while ($dao->fetch()) {
$result[$dao->financial_trxn_id][$dao->id] = $dao->amount;
@@ -326,7 +328,7 @@ public static function deleteFinancialTrxn($entity_id) {
LEFT JOIN civicrm_financial_item cfi
ON ceft1.entity_table = 'civicrm_financial_item' and cfi.id = ceft1.entity_id
WHERE ceft.entity_id = %1";
- CRM_Core_DAO::executeQuery($query, array(1 => array($entity_id, 'Integer')));
+ CRM_Core_DAO::executeQuery($query, [1 => [$entity_id, 'Integer']]);
return TRUE;
}
@@ -350,8 +352,7 @@ public static function createPremiumTrxn($params) {
$contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$toFinancialAccountType = !empty($params['isDeleted']) ? 'Premiums Inventory Account is' : 'Cost of Sales Account is';
$fromFinancialAccountType = !empty($params['isDeleted']) ? 'Cost of Sales Account is' : 'Premiums Inventory Account is';
- $accountRelationship = array_flip($accountRelationship);
- $financialtrxn = array(
+ $financialtrxn = [
'to_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $toFinancialAccountType),
'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $fromFinancialAccountType),
'trxn_date' => date('YmdHis'),
@@ -360,23 +361,23 @@ public static function createPremiumTrxn($params) {
'status_id' => array_search('Completed', $contributionStatuses),
'entity_table' => 'civicrm_contribution',
'entity_id' => $params['contributionId'],
- );
+ ];
CRM_Core_BAO_FinancialTrxn::create($financialtrxn);
}
if (!empty($params['oldPremium'])) {
- $premiumParams = array(
+ $premiumParams = [
'id' => $params['oldPremium']['product_id'],
- );
- $productDetails = array();
- CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
- $params = array(
+ ];
+ $productDetails = [];
+ CRM_Contribute_BAO_Product::retrieve($premiumParams, $productDetails);
+ $params = [
'cost' => CRM_Utils_Array::value('cost', $productDetails),
'currency' => CRM_Utils_Array::value('currency', $productDetails),
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
'contributionId' => $params['oldPremium']['contribution_id'],
'isDeleted' => TRUE,
- );
+ ];
CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($params);
}
}
@@ -387,7 +388,7 @@ public static function createPremiumTrxn($params) {
* @param array $params
* To create trxn entries.
*
- * @return bool
+ * @return bool|void
*/
public static function recordFees($params) {
$domainId = CRM_Core_Config::domainID();
@@ -406,7 +407,7 @@ public static function recordFees($params) {
else {
$financialTypeId = $params['financial_type_id'];
}
- $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
+ $financialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($financialTypeId, 'Expense Account is');
$params['trxnParams']['from_financial_account_id'] = $params['to_financial_account_id'];
$params['trxnParams']['to_financial_account_id'] = $financialAccount;
@@ -421,7 +422,7 @@ public static function recordFees($params) {
$params['entity_id'] = $financialTrxnID['financialTrxnId'];
}
$fItemParams
- = array(
+ = [
'financial_account_id' => $financialAccount,
'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id'),
'created_date' => date('YmdHis'),
@@ -432,29 +433,33 @@ public static function recordFees($params) {
'entity_table' => 'civicrm_financial_trxn',
'entity_id' => $params['entity_id'],
'currency' => $params['trxnParams']['currency'],
- );
+ ];
$trxnIDS['id'] = $trxn->id;
CRM_Financial_BAO_FinancialItem::create($fItemParams, NULL, $trxnIDS);
}
/**
- * get partial payment amount and type of it.
+ * get partial payment amount.
+ *
+ * @deprecated
+ *
+ * This function basically calls CRM_Contribute_BAO_Contribution::getContributionBalance
+ * - just do that. If need be we could have a fn to get the contribution id but
+ * chances are the calling functions already know it anyway.
*
* @param int $entityId
* @param string $entityName
- * @param bool $returnType
* @param int $lineItemTotal
*
- * @return array|int|NULL|string
- * [payment type => amount]
- * payment type: 'amount_owed' or 'refund_due'
+ * @return array
*/
- public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $returnType = TRUE, $lineItemTotal = NULL) {
+ public static function getPartialPaymentWithType($entityId, $entityName = 'participant', $lineItemTotal = NULL) {
$value = NULL;
if (empty($entityName)) {
return $value;
}
+ // @todo - deprecate passing in entity & type - just figure out contribution id FIRST
if ($entityName == 'participant') {
$contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $entityId, 'contribution_id', 'participant_id');
}
@@ -467,80 +472,40 @@ public static function getPartialPaymentWithType($entityId, $entityName = 'parti
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
if ($contributionId && $financialTypeId) {
- $statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
- $refundStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
- if (empty($lineItemTotal)) {
- $lineItemTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
+ $paymentVal = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $lineItemTotal);
+ $value = [];
+ if ($paymentVal < 0) {
+ $value['refund_due'] = $paymentVal;
}
- $sqlFtTotalAmt = "
-SELECT SUM(ft.total_amount)
-FROM civicrm_financial_trxn ft
- INNER JOIN civicrm_entity_financial_trxn eft ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution' AND eft.entity_id = {$contributionId})
-WHERE ft.is_payment = 1
- AND ft.status_id IN ({$statusId}, {$refundStatusId})
-";
-
- $ftTotalAmt = CRM_Core_DAO::singleValueQuery($sqlFtTotalAmt);
- $value = 0;
- if (!$ftTotalAmt) {
- $ftTotalAmt = 0;
- }
- $value = $paymentVal = $lineItemTotal - $ftTotalAmt;
- if ($returnType) {
- $value = array();
- if ($paymentVal < 0) {
- $value['refund_due'] = $paymentVal;
- }
- elseif ($paymentVal > 0) {
- $value['amount_owed'] = $paymentVal;
- }
- elseif ($lineItemTotal == $ftTotalAmt) {
- $value['full_paid'] = $ftTotalAmt;
- }
+ elseif ($paymentVal > 0) {
+ $value['amount_owed'] = $paymentVal;
}
}
return $value;
}
/**
- * @param int $contributionId
+ * @param int $contributionID
+ * @param bool $includeRefund
*
- * @return array
+ * @return string
*/
- public static function getTotalPayments($contributionId) {
- $statusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+ public static function getTotalPayments($contributionID, $includeRefund = FALSE) {
+ $statusIDs = [CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')];
+
+ if ($includeRefund) {
+ $statusIDs[] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
+ }
$sql = "SELECT SUM(ft.total_amount) FROM civicrm_financial_trxn ft
INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
- WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id = %2";
-
- $params = array(
- 1 => array($contributionId, 'Integer'),
- 2 => array($statusId, 'Integer'),
- );
-
- return CRM_Core_DAO::singleValueQuery($sql, $params);
- }
+ WHERE eft.entity_id = %1 AND ft.is_payment = 1 AND ft.status_id IN (%2) ";
- /**
- * Function records partial payment, complete's contribution if payment is fully paid
- * and returns latest payment ie financial trxn
- *
- * @param array $contribution
- * @param array $params
- *
- * @return CRM_Core_BAO_FinancialTrxn
- */
- public static function getPartialPaymentTrxn($contribution, $params) {
- $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
- $paid = CRM_Core_BAO_FinancialTrxn::getTotalPayments($params['contribution_id']);
- $total = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution_id'], 'total_amount');
- $cmp = bccomp($total, $paid, 5);
- if ($cmp == 0 || $cmp == -1) {// If paid amount is greater or equal to total amount
- civicrm_api3('Contribution', 'completetransaction', array('id' => $contribution['id']));
- }
- return $trxn;
+ return CRM_Core_DAO::singleValueQuery($sql, [
+ 1 => [$contributionID, 'Integer'],
+ 2 => [implode(',', $statusIDs), 'CommaSeparatedIntegers'],
+ ]);
}
/**
@@ -551,10 +516,10 @@ public static function getPartialPaymentTrxn($contribution, $params) {
* @return array
*/
public static function getMembershipRevenueAmount($lineItem) {
- $revenueAmount = array();
- $membershipDetail = civicrm_api3('Membership', 'getsingle', array(
+ $revenueAmount = [];
+ $membershipDetail = civicrm_api3('Membership', 'getsingle', [
'id' => $lineItem['entity_id'],
- ));
+ ]);
if (empty($membershipDetail['end_date'])) {
return $revenueAmount;
}
@@ -607,7 +572,7 @@ public static function createDeferredTrxn($lineItems, $contributionDetails, $upd
) {
return;
}
- $trxnParams = array(
+ $trxnParams = [
'contribution_id' => $contributionDetails->id,
'fee_amount' => '0.00',
'currency' => $contributionDetails->currency,
@@ -615,9 +580,9 @@ public static function createDeferredTrxn($lineItems, $contributionDetails, $upd
'status_id' => $contributionDetails->contribution_status_id,
'payment_instrument_id' => $contributionDetails->payment_instrument_id,
'check_number' => $contributionDetails->check_number,
- );
+ ];
- $deferredRevenues = array();
+ $deferredRevenues = [];
foreach ($lineItems as $priceSetID => $lineItem) {
if (!$priceSetID) {
continue;
@@ -632,12 +597,12 @@ public static function createDeferredTrxn($lineItems, $contributionDetails, $upd
$deferredRevenues[$key]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_LineItem', $item['id'], 'financial_type_id');
}
if (in_array($item['entity_table'],
- array('civicrm_participant', 'civicrm_contribution'))
+ ['civicrm_participant', 'civicrm_contribution'])
) {
- $deferredRevenues[$key]['revenue'][] = array(
+ $deferredRevenues[$key]['revenue'][] = [
'amount' => $lineTotal,
'revenue_date' => $revenueRecognitionDate,
- );
+ ];
}
else {
// for membership
@@ -651,11 +616,11 @@ public static function createDeferredTrxn($lineItems, $contributionDetails, $upd
CRM_Utils_Hook::alterDeferredRevenueItems($deferredRevenues, $contributionDetails, $update, $context);
foreach ($deferredRevenues as $key => $deferredRevenue) {
- $results = civicrm_api3('EntityFinancialAccount', 'get', array(
+ $results = civicrm_api3('EntityFinancialAccount', 'get', [
'entity_table' => 'civicrm_financial_type',
'entity_id' => $deferredRevenue['financial_type_id'],
- 'account_relationship' => array('IN' => array('Income Account is', 'Deferred Revenue Account is')),
- ));
+ 'account_relationship' => ['IN' => ['Income Account is', 'Deferred Revenue Account is']],
+ ]);
if ($results['count'] != 2) {
continue;
}
@@ -671,12 +636,12 @@ public static function createDeferredTrxn($lineItems, $contributionDetails, $upd
$trxnParams['total_amount'] = $trxnParams['net_amount'] = $revenue['amount'];
$trxnParams['trxn_date'] = CRM_Utils_Date::isoToMysql($revenue['revenue_date']);
$financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
- $entityParams = array(
+ $entityParams = [
'entity_id' => $deferredRevenue['financial_item_id'],
'entity_table' => 'civicrm_financial_item',
'amount' => $revenue['amount'],
'financial_trxn_id' => $financialTxn->id,
- );
+ ];
civicrm_api3('EntityFinancialTrxn', 'create', $entityParams);
}
}
@@ -692,13 +657,13 @@ public static function createDeferredTrxn($lineItems, $contributionDetails, $upd
*
*/
public static function updateCreditCardDetails($contributionID, $panTruncation, $cardType) {
- $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', array(
- 'return' => array('financial_trxn_id.payment_processor_id', 'financial_trxn_id'),
+ $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'get', [
+ 'return' => ['financial_trxn_id.payment_processor_id', 'financial_trxn_id'],
'entity_table' => 'civicrm_contribution',
'entity_id' => $contributionID,
'financial_trxn_id.is_payment' => TRUE,
- 'options' => array('sort' => 'financial_trxn_id DESC', 'limit' => 1),
- ));
+ 'options' => ['sort' => 'financial_trxn_id DESC', 'limit' => 1],
+ ]);
// In case of Contribution status is Pending From Incomplete Transaction or Failed there is no Financial Entries created for Contribution.
// Above api will return 0 count, in such case we won't update card type and pan truncation field.
@@ -714,7 +679,7 @@ public static function updateCreditCardDetails($contributionID, $panTruncation,
}
$financialTrxnId = $financialTrxn['financial_trxn_id'];
- $trxnparams = array('id' => $financialTrxnId);
+ $trxnparams = ['id' => $financialTrxnId];
if (isset($cardType)) {
$trxnparams['card_type_id'] = $cardType;
}
@@ -751,19 +716,19 @@ public static function updateFinancialAccountsOnPaymentInstrumentChange($inputPa
// If payment instrument is changed reverse the last payment
// in terms of reversing financial item and trxn
- $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', array('id' => $lastFinancialTrxnId['financialTrxnId']));
+ $lastFinancialTrxn = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $lastFinancialTrxnId['financialTrxnId']]);
unset($lastFinancialTrxn['id']);
$lastFinancialTrxn['trxn_date'] = $inputParams['trxnParams']['trxn_date'];
$lastFinancialTrxn['total_amount'] = -$inputParams['trxnParams']['total_amount'];
$lastFinancialTrxn['net_amount'] = -$inputParams['trxnParams']['net_amount'];
$lastFinancialTrxn['fee_amount'] = -$inputParams['trxnParams']['fee_amount'];
$lastFinancialTrxn['contribution_id'] = $prevContribution->id;
- foreach (array($lastFinancialTrxn, $inputParams['trxnParams']) as $financialTrxnParams) {
+ foreach ([$lastFinancialTrxn, $inputParams['trxnParams']] as $financialTrxnParams) {
$trxn = CRM_Core_BAO_FinancialTrxn::create($financialTrxnParams);
- $trxnParams = array(
+ $trxnParams = [
'total_amount' => $trxn->total_amount,
'contribution_id' => $currentContribution->id,
- );
+ ];
CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $trxn->id, $prevContribution->total_amount);
}
diff --git a/CRM/Core/BAO/IM.php b/CRM/Core/BAO/IM.php
index c23b28058e15..a64d22341ede 100644
--- a/CRM/Core/BAO/IM.php
+++ b/CRM/Core/BAO/IM.php
@@ -1,9 +1,9 @@
array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
- $ims = $values = array();
+ $ims = $values = [];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
while ($dao->fetch()) {
- $values = array(
+ $values = [
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->im_id,
'name' => $dao->im,
'locationTypeId' => $dao->locationTypeId,
'providerId' => $dao->providerId,
- );
+ ];
if ($updateBlankLocInfo) {
$ims[$count++] = $values;
@@ -147,18 +147,18 @@ public static function allEntityIMs(&$entityElements) {
AND ltype.id = cim.location_type_id
ORDER BY cim.is_primary DESC, im_id ASC ";
- $params = array(1 => array($entityId, 'Integer'));
+ $params = [1 => [$entityId, 'Integer']];
- $ims = array();
+ $ims = [];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
while ($dao->fetch()) {
- $ims[$dao->im_id] = array(
+ $ims[$dao->im_id] = [
'locationType' => $dao->locationType,
'is_primary' => $dao->is_primary,
'id' => $dao->im_id,
'name' => $dao->im,
'locationTypeId' => $dao->locationTypeId,
- );
+ ];
}
return $ims;
}
diff --git a/CRM/Core/BAO/Job.php b/CRM/Core/BAO/Job.php
index 2034fccba35a..867a0433754a 100644
--- a/CRM/Core/BAO/Job.php
+++ b/CRM/Core/BAO/Job.php
@@ -1,9 +1,9 @@
[
+ 'name' => ' - ' . ts('Copy'),
+ ],
+ 'replace' => $params,
+ ];
+ $copy = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_Job', ['id' => $id], NULL, $fieldsFix);
+ $copy->save();
+ CRM_Utils_Hook::copy('Job', $copy);
+
+ return $copy;
+ }
+
}
diff --git a/CRM/Core/BAO/LabelFormat.php b/CRM/Core/BAO/LabelFormat.php
index ba4ca660e4f3..3ff7966611b0 100644
--- a/CRM/Core/BAO/LabelFormat.php
+++ b/CRM/Core/BAO/LabelFormat.php
@@ -1,7 +1,7 @@
array(
+ private static $optionValueFields = [
+ 'paper-size' => [
// Paper size: names defined in option_value table (option_group = 'paper_size')
'name' => 'paper-size',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'letter',
- ),
- 'orientation' => array(
+ ],
+ 'orientation' => [
// Paper orientation: 'portrait' or 'landscape'
'name' => 'orientation',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'portrait',
- ),
- 'font-name' => array(
+ ],
+ 'font-name' => [
// Font name: 'courier', 'helvetica', 'times'
'name' => 'font-name',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'helvetica',
- ),
- 'font-size' => array(
+ ],
+ 'font-size' => [
// Font size: always in points
'name' => 'font-size',
'type' => CRM_Utils_Type::T_INT,
'default' => 8,
- ),
- 'font-style' => array(
+ ],
+ 'font-style' => [
// Font style: 'B' bold, 'I' italic, 'BI' bold+italic
'name' => 'font-style',
'type' => CRM_Utils_Type::T_STRING,
'default' => '',
- ),
- 'NX' => array(
+ ],
+ 'NX' => [
// Number of labels horizontally
'name' => 'NX',
'type' => CRM_Utils_Type::T_INT,
'default' => 3,
- ),
- 'NY' => array(
+ ],
+ 'NY' => [
// Number of labels vertically
'name' => 'NY',
'type' => CRM_Utils_Type::T_INT,
'default' => 10,
- ),
- 'metric' => array(
+ ],
+ 'metric' => [
// Unit of measurement for all of the following fields
'name' => 'metric',
'type' => CRM_Utils_Type::T_STRING,
'default' => 'mm',
- ),
- 'lMargin' => array(
+ ],
+ 'lMargin' => [
// Left margin
'name' => 'lMargin',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 4.7625,
- ),
- 'tMargin' => array(
+ ],
+ 'tMargin' => [
// Right margin
'name' => 'tMargin',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 12.7,
- ),
- 'SpaceX' => array(
+ ],
+ 'SpaceX' => [
// Horizontal space between two labels
'name' => 'SpaceX',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 3.96875,
- ),
- 'SpaceY' => array(
+ ],
+ 'SpaceY' => [
// Vertical space between two labels
'name' => 'SpaceY',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 0,
- ),
- 'width' => array(
+ ],
+ 'width' => [
// Width of label
'name' => 'width',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 65.875,
- ),
- 'height' => array(
+ ],
+ 'height' => [
// Height of label
'name' => 'height',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 25.4,
- ),
- 'lPadding' => array(
+ ],
+ 'lPadding' => [
// Space between text and left edge of label
'name' => 'lPadding',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 5.08,
- ),
- 'tPadding' => array(
+ ],
+ 'tPadding' => [
// Space between text and top edge of label
'name' => 'tPadding',
'type' => CRM_Utils_Type::T_FLOAT,
'metric' => TRUE,
'default' => 5.08,
- ),
- );
+ ],
+ ];
/**
* Get page orientations recognized by the DOMPDF package used to create PDF letters.
@@ -159,10 +161,10 @@ class CRM_Core_BAO_LabelFormat extends CRM_Core_DAO_OptionValue {
* array of page orientations
*/
public static function getPageOrientations() {
- return array(
+ return [
'portrait' => ts('Portrait'),
'landscape' => ts('Landscape'),
- );
+ ];
}
/**
@@ -186,9 +188,9 @@ public static function getFontNames($name = 'label_format') {
* array of font sizes
*/
public static function getFontSizes() {
- $fontSizes = array();
+ $fontSizes = [];
for ($i = 6; $i <= 60; $i++) {
- $fontSizes[$i] = ts('%1 pt', array(1 => $i));
+ $fontSizes[$i] = ts('%1 pt', [1 => $i]);
}
return $fontSizes;
@@ -201,12 +203,12 @@ public static function getFontSizes() {
* array of measurement units
*/
public static function getUnits() {
- return array(
+ return [
'in' => ts('Inches'),
'cm' => ts('Centimeters'),
'mm' => ts('Millimeters'),
'pt' => ts('Points'),
- );
+ ];
}
/**
@@ -216,11 +218,11 @@ public static function getUnits() {
* array of alignments
*/
public static function getTextAlignments() {
- return array(
+ return [
'R' => ts('Right'),
'L' => ts('Left'),
'C' => ts('Center'),
- );
+ ];
}
/**
@@ -230,11 +232,11 @@ public static function getTextAlignments() {
* array of alignments
*/
public static function getFontStyles() {
- return array(
+ return [
'' => ts('Normal'),
'B' => ts('Bold'),
'I' => ts('Italic'),
- );
+ ];
}
/**
@@ -258,7 +260,7 @@ private static function _getGid($name = 'label_format') {
/**
* Add ordering fields to Label Format list.
*
- * @param array (reference) $list List of Label Formats
+ * @param array $list List of Label Formats
* @param string $returnURL
* URL of page calling this function.
*
@@ -283,7 +285,7 @@ public static function addOrder(&$list, $returnURL) {
* (reference) label format list
*/
public static function &getList($namesOnly = FALSE, $groupName = 'label_format') {
- static $list = array();
+ static $list = [];
if (self::_getGid($groupName)) {
// get saved label formats from Option Value table
$dao = new CRM_Core_DAO_OptionValue();
@@ -313,13 +315,13 @@ public static function &getList($namesOnly = FALSE, $groupName = 'label_format')
* Name/value pairs containing the default Label Format values.
*/
public static function &getDefaultValues($groupName = 'label_format') {
- $params = array('is_active' => 1, 'is_default' => 1);
- $defaults = array();
+ $params = ['is_active' => 1, 'is_default' => 1];
+ $defaults = [];
if (!self::retrieve($params, $defaults, $groupName)) {
foreach (self::$optionValueFields as $name => $field) {
$defaults[$name] = $field['default'];
}
- $filter = array('option_group_id' => self::_getGid($groupName));
+ $filter = ['option_group_id' => self::_getGid($groupName)];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $filter);
}
return $defaults;
@@ -339,8 +341,8 @@ public static function &getDefaultValues($groupName = 'label_format') {
* (reference) associative array of name/value pairs
*/
public static function &getLabelFormat($field, $val, $groupName = 'label_format') {
- $params = array('is_active' => 1, $field => $val);
- $labelFormat = array();
+ $params = ['is_active' => 1, $field => $val];
+ $labelFormat = [];
if (self::retrieve($params, $labelFormat, $groupName)) {
return $labelFormat;
}
@@ -382,7 +384,7 @@ public static function &getById($id, $groupName = 'label_format') {
*
* @param string $field
* Name of a label format field.
- * @param array (reference) $values associative array of name/value pairs containing
+ * @param array $values associative array of name/value pairs containing
* label format field selections
*
* @param null $default
@@ -458,7 +460,7 @@ public static function customGroupName() {
/**
* Save the Label Format in the DB.
*
- * @param array (reference) $values associative array of name/value pairs
+ * @param array $values associative array of name/value pairs
* @param int $id
* Id of the database record (null = new record).
* @param string $groupName
@@ -519,7 +521,7 @@ public function saveLabelFormat(&$values, $id = NULL, $groupName = 'label_format
$this->save();
// fix duplicate weights
- $filter = array('option_group_id' => self::_getGid());
+ $filter = ['option_group_id' => self::_getGid()];
CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $filter);
}
@@ -537,7 +539,7 @@ public static function del($id, $groupName) {
$dao->id = $id;
if ($dao->find(TRUE)) {
if ($dao->option_group_id == self::_getGid($groupName)) {
- $filter = array('option_group_id' => self::_getGid($groupName));
+ $filter = ['option_group_id' => self::_getGid($groupName)];
CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $id, $filter);
$dao->delete();
return;
diff --git a/CRM/Core/BAO/Location.php b/CRM/Core/BAO/Location.php
index 56953d9b7d33..b0c68d1b8a93 100644
--- a/CRM/Core/BAO/Location.php
+++ b/CRM/Core/BAO/Location.php
@@ -1,9 +1,9 @@
$params['entity_table'],
'entity_id' => $params['entity_id'],
- );
+ ];
$location['id'] = self::createLocBlock($location, $entityElements);
}
@@ -102,18 +103,18 @@ public static function create(&$params, $fixAddress = TRUE, $entity = NULL) {
*/
public static function createLocBlock(&$location, &$entityElements) {
$locId = self::findExisting($entityElements);
- $locBlock = array();
+ $locBlock = [];
if ($locId) {
$locBlock['id'] = $locId;
}
- foreach (array(
- 'phone',
- 'email',
- 'im',
- 'address',
- ) as $loc) {
+ foreach ([
+ 'phone',
+ 'email',
+ 'im',
+ 'address',
+ ] as $loc) {
$locBlock["{$loc}_id"] = !empty($location["$loc"][0]) ? $location["$loc"][0]->id : NULL;
$locBlock["{$loc}_2_id"] = !empty($location["$loc"][1]) ? $location["$loc"][1]->id : NULL;
}
@@ -150,7 +151,7 @@ public static function findExisting($entityElements) {
FROM {$etable} e
WHERE e.id = %1";
- $params = array(1 => array($eid, 'Integer'));
+ $params = [1 => [$eid, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$locBlockId = $dao->locId;
@@ -192,7 +193,7 @@ public static function deleteLocBlock($locBlockId) {
$locBlock->find(TRUE);
//resolve conflict of having same ids for multiple blocks
- $store = array(
+ $store = [
'IM_1' => $locBlock->im_id,
'IM_2' => $locBlock->im_2_id,
'Email_1' => $locBlock->email_id,
@@ -201,7 +202,7 @@ public static function deleteLocBlock($locBlockId) {
'Phone_2' => $locBlock->phone_2_id,
'Address_1' => $locBlock->address_id,
'Address_2' => $locBlock->address_2_id,
- );
+ ];
$locBlock->delete();
foreach ($store as $daoName => $id) {
if ($id) {
@@ -210,7 +211,6 @@ public static function deleteLocBlock($locBlockId) {
$dao->id = $id;
$dao->find(TRUE);
$dao->delete();
- $dao->free();
}
}
}
@@ -249,12 +249,12 @@ public static function &getValues($entityBlock, $microformat = FALSE) {
if (empty($entityBlock)) {
return NULL;
}
- $blocks = array();
- $name_map = array(
+ $blocks = [];
+ $name_map = [
'im' => 'IM',
'openid' => 'OpenID',
- );
- $blocks = array();
+ ];
+ $blocks = [];
//get all the blocks for this contact
foreach (self::$blocks as $block) {
if (array_key_exists($block, $name_map)) {
@@ -293,9 +293,9 @@ public static function deleteLocationBlocks($contactId, $locationTypeId) {
$locationTypeId = 'null';
}
- static $blocks = array('Address', 'Phone', 'IM', 'OpenID', 'Email');
+ static $blocks = ['Address', 'Phone', 'IM', 'OpenID', 'Email'];
- $params = array('contact_id' => $contactId, 'location_type_id' => $locationTypeId);
+ $params = ['contact_id' => $contactId, 'location_type_id' => $locationTypeId];
foreach ($blocks as $name) {
CRM_Core_BAO_Block::blockDelete($name, $params);
}
@@ -313,14 +313,15 @@ public static function deleteLocationBlocks($contactId, $locationTypeId) {
* newly created/updated location block id.
*/
public static function copyLocBlock($locBlockId, $updateLocBlockId = NULL) {
+ CRM_Core_Error::deprecatedFunctionWarning('unused function which will be removed');
//get the location info.
- $defaults = $updateValues = array();
- $locBlock = array('id' => $locBlockId);
+ $defaults = $updateValues = [];
+ $locBlock = ['id' => $locBlockId];
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_LocBlock', $locBlock, $defaults);
if ($updateLocBlockId) {
//get the location info for update.
- $copyLocationParams = array('id' => $updateLocBlockId);
+ $copyLocationParams = ['id' => $updateLocBlockId];
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_LocBlock', $copyLocationParams, $updateValues);
foreach ($updateValues as $key => $value) {
if ($key != 'id') {
@@ -336,16 +337,16 @@ public static function copyLocBlock($locBlockId, $updateLocBlockId = NULL) {
$name = ucfirst($tbl[0]);
$updateParams = NULL;
if ($updateId = CRM_Utils_Array::value($key, $updateValues)) {
- $updateParams = array('id' => $updateId);
+ $updateParams = ['id' => $updateId];
}
- $copy = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_' . $name, array('id' => $value), $updateParams);
+ $copy = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_' . $name, ['id' => $value], $updateParams);
$copyLocationParams[$key] = $copy->id;
}
}
- $copyLocation = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_LocBlock',
- array('id' => $locBlock['id']),
+ $copyLocation = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_LocBlock',
+ ['id' => $locBlock['id']],
$copyLocationParams
);
return $copyLocation->id;
@@ -363,16 +364,16 @@ public static function checkPrimaryBlocks($contactId) {
}
// get the loc block ids.
- $primaryLocBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, array('is_primary' => 1));
- $nonPrimaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, array('is_primary' => 0));
-
- foreach (array(
- 'Email',
- 'IM',
- 'Phone',
- 'Address',
- 'OpenID',
- ) as $block) {
+ $primaryLocBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, ['is_primary' => 1]);
+ $nonPrimaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, ['is_primary' => 0]);
+
+ foreach ([
+ 'Email',
+ 'IM',
+ 'Phone',
+ 'Address',
+ 'OpenID',
+ ] as $block) {
$name = strtolower($block);
if (array_key_exists($name, $primaryLocBlockIds) &&
!CRM_Utils_System::isNull($primaryLocBlockIds[$name])
@@ -407,10 +408,10 @@ public static function checkPrimaryBlocks($contactId) {
*/
public static function getChainSelectValues($values, $valueType, $flatten = FALSE) {
if (!$values) {
- return array();
+ return [];
}
$values = array_filter((array) $values);
- $elements = array();
+ $elements = [];
$list = &$elements;
$method = $valueType == 'country' ? 'stateProvinceForCountry' : 'countyForState';
foreach ($values as $val) {
@@ -429,17 +430,17 @@ public static function getChainSelectValues($values, $valueType, $flatten = FALS
else {
// Option-groups for multiple categories
if ($result && count($values) > 1) {
- $elements[] = array(
+ $elements[] = [
'value' => CRM_Core_PseudoConstant::$valueType($val, FALSE),
- 'children' => array(),
- );
+ 'children' => [],
+ ];
$list = &$elements[count($elements) - 1]['children'];
}
foreach ($result as $id => $name) {
- $list[] = array(
+ $list[] = [
'value' => $name,
'key' => $id,
- );
+ ];
}
}
}
diff --git a/CRM/Core/BAO/LocationType.php b/CRM/Core/BAO/LocationType.php
index 9eead4bad16d..7f4cdab2df50 100644
--- a/CRM/Core/BAO/LocationType.php
+++ b/CRM/Core/BAO/LocationType.php
@@ -1,9 +1,9 @@
1);
- $defaults = array();
+ $params = ['is_default' => 1];
+ $defaults = [];
self::$_defaultLocationType = self::retrieve($params, $defaults);
}
return self::$_defaultLocationType;
@@ -107,7 +107,7 @@ public static function &getDefault() {
*/
public static function getBilling() {
if (self::$_billingLocationType == NULL) {
- $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
+ $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', [], 'validate');
self::$_billingLocationType = array_search('Billing', $locationTypes);
}
return self::$_billingLocationType;
@@ -148,7 +148,7 @@ public static function create(&$params) {
*
*/
public static function del($locationTypeId) {
- $entity = array('address', 'phone', 'email', 'im');
+ $entity = ['address', 'phone', 'email', 'im'];
//check dependencies
foreach ($entity as $key) {
if ($key == 'im') {
diff --git a/CRM/Core/BAO/Log.php b/CRM/Core/BAO/Log.php
index 9403c1b5bc4c..eb75c8370835 100644
--- a/CRM/Core/BAO/Log.php
+++ b/CRM/Core/BAO/Log.php
@@ -1,9 +1,9 @@
modified_id) {
list($displayName, $contactImage) = CRM_Contact_BAO_Contact::getDisplayAndImage($log->modified_id);
}
- $result = array(
+ $result = [
'id' => $log->modified_id,
'name' => $displayName,
'image' => $contactImage,
'date' => $log->modified_date,
- );
+ ];
}
return $result;
}
@@ -94,7 +94,7 @@ public static function register(
$userID = NULL
) {
if (!self::$_processed) {
- self::$_processed = array();
+ self::$_processed = [];
}
if (!$userID) {
@@ -128,7 +128,7 @@ public static function register(
self::$_processed[$contactID][$userID] = 1;
}
else {
- self::$_processed[$contactID] = array($userID => 1);
+ self::$_processed[$contactID] = [$userID => 1];
}
$logData = "$tableName,$tableID";
@@ -183,8 +183,8 @@ public static function useLoggingReport() {
$loggingSchema = new CRM_Logging_Schema();
if ($loggingSchema->isEnabled()) {
- $params = array('report_id' => 'logging/contact/summary');
- $instance = array();
+ $params = ['report_id' => 'logging/contact/summary'];
+ $instance = [];
CRM_Report_BAO_ReportInstance::retrieve($params, $instance);
if (!empty($instance) &&
diff --git a/CRM/Core/BAO/MailSettings.php b/CRM/Core/BAO/MailSettings.php
index ef806d5ea9d6..05168c3e3ac0 100644
--- a/CRM/Core/BAO/MailSettings.php
+++ b/CRM/Core/BAO/MailSettings.php
@@ -1,9 +1,9 @@
array(CRM_Core_Config::domainID(), 'Integer'));
+ $queryParams = [1 => [CRM_Core_Config::domainID(), 'Integer']];
CRM_Core_DAO::executeQuery($query, $queryParams);
}
diff --git a/CRM/Core/BAO/Mapping.php b/CRM/Core/BAO/Mapping.php
index 34934ab123ee..3a9e29f5e739 100644
--- a/CRM/Core/BAO/Mapping.php
+++ b/CRM/Core/BAO/Mapping.php
@@ -1,9 +1,9 @@
$mappingType,
- 'options' => array(
+ 'options' => [
'sort' => 'name',
'limit' => 0,
- ),
- ));
- $mapping = array();
+ ],
+ ]);
+ $mapping = [];
foreach ($result['values'] as $key => $value) {
$mapping[$key] = $value['name'];
@@ -151,13 +151,13 @@ public static function getCreateMappingValues($mappingType) {
// it feels like there could be other instances so this is safer.
$errorParams = $e->getExtraParams();
if ($errorParams['error_field'] === 'mapping_type_id') {
- $mappingValues = civicrm_api3('Mapping', 'getoptions', array('field' => 'mapping_type_id'));
- civicrm_api3('OptionValue', 'create', array(
+ $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
+ civicrm_api3('OptionValue', 'create', [
'option_group_id' => 'mapping_type',
'label' => $mappingType,
'value' => max(array_keys($mappingValues['values'])) + 1,
'is_reserved' => 1,
- ));
+ ]);
return CRM_Core_BAO_Mapping::getMappings($mappingType);
}
throw $e;
@@ -184,8 +184,8 @@ public static function getMappingFields($mappingId, $addPrimary = FALSE) {
$mapping->orderBy('column_number');
$mapping->find();
- $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = array();
- $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = array();
+ $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
+ $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
while ($mapping->fetch()) {
$mappingName[$mapping->grouping][$mapping->column_number] = $mapping->name;
$mappingContactType[$mapping->grouping][$mapping->column_number] = $mapping->contact_type;
@@ -228,7 +228,7 @@ public static function getMappingFields($mappingId, $addPrimary = FALSE) {
}
}
- return array(
+ return [
$mappingName,
$mappingContactType,
$mappingLocation,
@@ -238,7 +238,7 @@ public static function getMappingFields($mappingId, $addPrimary = FALSE) {
$mappingOperator,
$mappingValue,
$mappingWebsiteType,
- );
+ ];
}
/**
@@ -268,7 +268,7 @@ public static function checkMapping($nameField, $mapTypeId) {
* associated array of elements
*/
public static function getFormattedFields($smartGroupId) {
- $returnFields = array();
+ $returnFields = [];
//get the fields from mapping table
$dao = new CRM_Core_DAO_MappingField();
@@ -303,14 +303,14 @@ public static function getFormattedFields($smartGroupId) {
*/
public static function buildMappingForm(&$form, $mappingType, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
- $hasLocationTypes = array();
- $hasRelationTypes = array();
- $fields = array();
+ $hasLocationTypes = [];
+ $hasRelationTypes = [];
+ $fields = [];
//get the saved mapping details
if ($mappingType == 'Export') {
- $columnCount = array('1' => $columnNo);
+ $columnCount = ['1' => $columnNo];
$form->applyFilter('saveMappingName', 'trim');
//to save the current mappings
@@ -322,8 +322,8 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
else {
$form->assign('loadedMapping', $mappingId);
- $params = array('id' => $mappingId);
- $temp = array();
+ $params = ['id' => $mappingId];
+ $temp = [];
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$form->assign('savedName', $mappingDetails->name);
@@ -336,17 +336,17 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$form->add('text', 'saveMappingDesc', ts('Description'));
}
- $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
- $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId'));
+ $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
+ $form->addFormRule(['CRM_Export_Form_Map', 'formRule'], $form->get('mappingTypeId'));
}
elseif ($mappingType == 'Search Builder') {
$columnCount = $columnNo;
$form->addElement('submit', 'addBlock', ts('Also include contacts where'),
- array('class' => 'submit-link')
+ ['class' => 'submit-link']
);
}
- $contactType = array('Individual', 'Household', 'Organization');
+ $contactType = ['Individual', 'Household', 'Organization'];
foreach ($contactType as $value) {
if ($mappingType == 'Search Builder') {
// get multiple custom group fields in this context
@@ -361,7 +361,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
ksort($fields[$value]);
if ($mappingType == 'Export') {
- $relationships = array();
+ $relationships = [];
$relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value, TRUE);
asort($relationshipTypes);
@@ -378,7 +378,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (!empty($relationships)) {
$fields[$value] = array_merge($fields[$value],
- array('related' => array('title' => ts('- related contact info -'))),
+ ['related' => ['title' => ts('- related contact info -')]],
$relationships
);
}
@@ -391,15 +391,15 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
}
// add component fields
- $compArray = array();
+ $compArray = [];
//we need to unset groups, tags, notes for component export
if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
- foreach (array(
- 'groups',
- 'tags',
- 'notes',
- ) as $value) {
+ foreach ([
+ 'groups',
+ 'tags',
+ 'notes',
+ ] as $value) {
unset($fields['Individual'][$value]);
unset($fields['Household'][$value]);
unset($fields['Organization'][$value]);
@@ -408,7 +408,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if ($mappingType == 'Search Builder') {
//build the common contact fields array.
- $fields['Contact'] = array();
+ $fields['Contact'] = [];
foreach ($fields['Individual'] as $key => $value) {
if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) {
$fields['Contact'][$key] = $value;
@@ -420,17 +420,17 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (array_key_exists('note', $fields['Contact'])) {
$noteTitle = $fields['Contact']['note']['title'];
$fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
- $fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body');
- $fields['Contact']['note_subject'] = array(
+ $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
+ $fields['Contact']['note_subject'] = [
'title' => $noteTitle . ': ' . ts('Subject Only'),
'name' => 'note_subject',
- );
+ ];
}
}
if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
if (CRM_Core_Permission::access('CiviContribute')) {
- $fields['Contribution'] = CRM_Contribute_BAO_Contribution::getExportableFieldsWithPseudoConstants();
+ $fields['Contribution'] = CRM_Core_DAO::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
unset($fields['Contribution']['contribution_contact_id']);
$compArray['Contribution'] = ts('Contribution');
}
@@ -440,10 +440,11 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (CRM_Core_Permission::access('CiviEvent')) {
$fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
//get the component payment fields
+ // @todo - review this - inconsistent with other entities & hacky.
if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
- $componentPaymentFields = array();
+ $componentPaymentFields = [];
foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) {
- $componentPaymentFields[$payField] = array('title' => $payTitle);
+ $componentPaymentFields[$payField] = ['title' => $payTitle];
}
$fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
}
@@ -496,12 +497,12 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
}
//Contact Sub Type For export
- $contactSubTypes = array();
+ $contactSubTypes = [];
$subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
foreach ($subTypes as $subType => $val) {
//adding subtype specific relationships CRM-5256
- $csRelationships = array();
+ $csRelationships = [];
if ($mappingType == 'Export') {
$subTypeRelationshipTypes
@@ -570,19 +571,19 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if ($defaultLocationType) {
$defaultLocation = $locationTypes[$defaultLocationType->id];
unset($locationTypes[$defaultLocationType->id]);
- $locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes;
+ $locationTypes = [$defaultLocationType->id => $defaultLocation] + $locationTypes;
}
- $locationTypes = array(' ' => ts('Primary')) + $locationTypes;
+ $locationTypes = [' ' => ts('Primary')] + $locationTypes;
// since we need a hierarchical list to display contact types & subtypes,
// this is what we going to display in first selector
$contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
if ($mappingType == 'Search Builder') {
- $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes;
+ $contactTypes = ['Contact' => ts('Contacts')] + $contactTypes;
}
- $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray;
+ $sel1 = ['' => ts('- select record type -')] + $contactTypes + $compArray;
foreach ($sel1 as $key => $sel) {
if ($key) {
@@ -591,7 +592,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (!in_array($key, $contactType)) {
asort($mapperFields[$key]);
}
- $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key];
+ $sel2[$key] = ['' => ts('- select field -')] + $mapperFields[$key];
}
}
@@ -635,11 +636,11 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (isset($hasRelationTypes[$k][$field])) {
list($id, $first, $second) = explode('_', $field);
// FIX ME: For now let's not expose custom data related to relationship
- $relationshipCustomFields = array();
+ $relationshipCustomFields = [];
//$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
//asort($relationshipCustomFields);
- $relatedFields = array();
+ $relatedFields = [];
$relationshipType = new CRM_Contact_BAO_RelationshipType();
$relationshipType->id = $id;
if ($relationshipType->find(TRUE)) {
@@ -698,7 +699,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
}
//special fields that have location, hack for primary location
- $specialFields = array(
+ $specialFields = [
'street_address',
'supplemental_address_1',
'supplemental_address_2',
@@ -713,7 +714,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
'phone',
'email',
'im',
- );
+ ];
if (isset($mappingId)) {
list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
@@ -740,13 +741,13 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$form->set('blockCount', $form->_blockCount);
$form->set('columnCount', $form->_columnCount);
- $defaults = $noneArray = $nullArray = array();
+ $defaults = $noneArray = $nullArray = [];
for ($x = 1; $x < $blockCount; $x++) {
for ($i = 0; $i < $columnCount[$x]; $i++) {
- $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
+ $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
$jsSet = FALSE;
if (isset($mappingId)) {
@@ -762,7 +763,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
- $defaults["mapper[$x][$i]"] = array(
+ $defaults["mapper[$x][$i]"] = [
$mappingContactType[$x][$i],
$mappingRelation[$x][$i],
$locationId,
@@ -770,24 +771,24 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$mappingName[$x][$i],
$relLocationId,
$relPhoneType,
- );
+ ];
if (!$locationId) {
- $noneArray[] = array($x, $i, 2);
+ $noneArray[] = [$x, $i, 2];
}
if (!$phoneType && !$imProvider) {
- $noneArray[] = array($x, $i, 3);
+ $noneArray[] = [$x, $i, 3];
}
if (!$mappingName[$x][$i]) {
- $noneArray[] = array($x, $i, 4);
+ $noneArray[] = [$x, $i, 4];
}
if (!$relLocationId) {
- $noneArray[] = array($x, $i, 5);
+ $noneArray[] = [$x, $i, 5];
}
if (!$relPhoneType) {
- $noneArray[] = array($x, $i, 6);
+ $noneArray[] = [$x, $i, 6];
}
- $noneArray[] = array($x, $i, 2);
+ $noneArray[] = [$x, $i, 2];
}
else {
$phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
@@ -796,25 +797,25 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$locationId = " ";
}
- $defaults["mapper[$x][$i]"] = array(
+ $defaults["mapper[$x][$i]"] = [
$mappingContactType[$x][$i],
$mappingName[$x][$i],
$locationId,
$phoneType,
- );
+ ];
if (!$mappingName[$x][$i]) {
- $noneArray[] = array($x, $i, 1);
+ $noneArray[] = [$x, $i, 1];
}
if (!$locationId) {
- $noneArray[] = array($x, $i, 2);
+ $noneArray[] = [$x, $i, 2];
}
if (!$phoneType && !$imProvider) {
- $noneArray[] = array($x, $i, 3);
+ $noneArray[] = [$x, $i, 3];
}
- $noneArray[] = array($x, $i, 4);
- $noneArray[] = array($x, $i, 5);
- $noneArray[] = array($x, $i, 6);
+ $noneArray[] = [$x, $i, 4];
+ $noneArray[] = [$x, $i, 5];
+ $noneArray[] = [$x, $i, 6];
}
$jsSet = TRUE;
@@ -842,7 +843,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (empty($formValues)) {
// Incremented length for third select box(relationship type)
for ($k = 1; $k < $j; $k++) {
- $noneArray[] = array($x, $i, $k);
+ $noneArray[] = [$x, $i, $k];
}
}
else {
@@ -852,17 +853,17 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
if (!isset($formValues['mapper'][$x][$i][$k]) ||
(!$formValues['mapper'][$x][$i][$k])
) {
- $noneArray[] = array($x, $i, $k);
+ $noneArray[] = [$x, $i, $k];
}
else {
- $nullArray[] = array($x, $i, $k);
+ $nullArray[] = [$x, $i, $k];
}
}
}
}
else {
for ($k = 1; $k < $j; $k++) {
- $noneArray[] = array($x, $i, $k);
+ $noneArray[] = [$x, $i, $k];
}
}
}
@@ -874,23 +875,23 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
isset($formValues['mapper'][$x][$i][1]) &&
array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
) {
- $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
+ $sel->setOptions([$sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4]);
}
else {
- $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
+ $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
}
}
else {
- $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
+ $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
}
}
else {
- $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
+ $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
}
if ($mappingType == 'Search Builder') {
//CRM -2292, restricted array set
- $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators();
+ $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues::getSearchBuilderOperators();
$form->add('select', "operator[$x][$i]", '', $operatorArray);
$form->add('text', "value[$x][$i]", '');
@@ -904,7 +905,7 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$title = ts('Select more fields');
}
- $form->addElement('submit', "addMore[$x]", $title, array('class' => 'submit-link'));
+ $form->addElement('submit', "addMore[$x]", $title, ['class' => 'submit-link']);
}
//end of block for
@@ -912,8 +913,8 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
$formName = "document." . (($mappingType == 'Export') ? 'Map' : 'Builder');
if (!empty($nullArray)) {
$js .= "var nullArray = [";
- $elements = array();
- $seen = array();
+ $elements = [];
+ $seen = [];
foreach ($nullArray as $element) {
$key = "{$element[0]}, {$element[1]}, {$element[2]}";
if (!isset($seen[$key])) {
@@ -933,8 +934,8 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
}
if (!empty($noneArray)) {
$js .= "var noneArray = [";
- $elements = array();
- $seen = array();
+ $elements = [];
+ $seen = [];
foreach ($noneArray as $element) {
$key = "{$element[0]}, {$element[1]}, {$element[2]}";
if (!isset($seen[$key])) {
@@ -975,14 +976,13 @@ public static function buildMappingForm(&$form, $mappingType, $mappingId, $colum
public function getRelationTypeCustomGroupData($relationshipTypeId) {
$customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
- $groupTitle = array();
+ $groupTitle = [];
foreach ($customFields as $krelation => $vrelation) {
$groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
}
return $groupTitle;
}
-
/**
* Function returns all Custom group Names.
*
@@ -997,9 +997,7 @@ public static function getCustomGroupName($customfieldId) {
$customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
$customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
- if (strlen($customGroupName) > 13) {
- $customGroupName = substr($customGroupName, 0, 10) . '...';
- }
+ $customGroupName = CRM_Utils_String::ellipsify($customGroupName, 13);
return $customGroupName;
}
@@ -1018,20 +1016,20 @@ public static function getCustomGroupName($customfieldId) {
* formatted associated array of elements
*/
public static function formattedFields(&$params, $row = FALSE) {
- $fields = array();
+ $fields = [];
if (empty($params) || !isset($params['mapper'])) {
return $fields;
}
- $types = array('Individual', 'Organization', 'Household');
+ $types = ['Individual', 'Organization', 'Household'];
foreach ($params['mapper'] as $key => $value) {
$contactType = NULL;
foreach ($value as $k => $v) {
if (in_array($v[0], $types)) {
if ($contactType && $contactType != $v[0]) {
CRM_Core_Error::fatal(ts("Cannot have two clauses with different types: %1, %2",
- array(1 => $contactType, 2 => $v[0])
+ [1 => $contactType, 2 => $v[0]]
));
}
$contactType = $v[0];
@@ -1061,7 +1059,7 @@ public static function formattedFields(&$params, $row = FALSE) {
// CRM-14983: verify if values are comma separated convert to array
if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
$value = explode(',', $value);
- $value = array($params['operator'][$key][$k] => $value);
+ $value = [$params['operator'][$key][$k] => $value];
}
// CRM-19081 Fix legacy StateProvince Field Values.
// These derive from smart groups created using search builder under older
@@ -1071,45 +1069,45 @@ public static function formattedFields(&$params, $row = FALSE) {
}
if ($row) {
- $fields[] = array(
+ $fields[] = [
$fldName,
$params['operator'][$key][$k],
$value,
$key,
$k,
- );
+ ];
}
else {
- $fields[] = array(
+ $fields[] = [
$fldName,
$params['operator'][$key][$k],
$value,
$key,
0,
- );
+ ];
}
}
}
if ($contactType) {
- $fields[] = array(
+ $fields[] = [
'contact_type',
'=',
$contactType,
$key,
0,
- );
+ ];
}
}
//add sortByCharacter values
if (isset($params['sortByCharacter'])) {
- $fields[] = array(
+ $fields[] = [
'sortByCharacter',
'=',
$params['sortByCharacter'],
0,
0,
- );
+ ];
}
return $fields;
}
@@ -1120,17 +1118,17 @@ public static function formattedFields(&$params, $row = FALSE) {
* @return array
*/
public static function &returnProperties(&$params) {
- $fields = array(
+ $fields = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
- );
+ ];
if (empty($params) || empty($params['mapper'])) {
return $fields;
}
- $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
+ $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
foreach ($params['mapper'] as $key => $value) {
foreach ($value as $k => $v) {
if (isset($v[1])) {
@@ -1140,13 +1138,13 @@ public static function &returnProperties(&$params) {
if (isset($v[2]) && is_numeric($v[2])) {
if (!array_key_exists('location', $fields)) {
- $fields['location'] = array();
+ $fields['location'] = [];
}
// make sure that we have a location fields and a location type for this
$locationName = $locationTypes[$v[2]];
if (!array_key_exists($locationName, $fields['location'])) {
- $fields['location'][$locationName] = array();
+ $fields['location'][$locationName] = [];
$fields['location'][$locationName]['location_type'] = $v[2];
}
diff --git a/CRM/Core/BAO/MessageTemplate.php b/CRM/Core/BAO/MessageTemplate.php
index 2b87046c0eb8..6687dd0ee4c1 100644
--- a/CRM/Core/BAO/MessageTemplate.php
+++ b/CRM/Core/BAO/MessageTemplate.php
@@ -1,9 +1,9 @@
$params['id']]);
+ if (!empty($details['workflow_id'])) {
+ if (!CRM_Core_Permission::check('edit system workflow message templates')) {
+ throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
+ }
+ }
+ elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
+ throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
+ }
+ }
+ else {
+ if (!empty($params['workflow_id']) && !CRM_Core_Permission::check('edit system workflow message templates')) {
+ throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $systemWorkflowPermissionDeniedMessage]));
+ }
+ elseif (!CRM_Core_Permission::check('edit user-driven message templates')) {
+ throw new \Civi\API\Exception\UnauthorizedException(ts('%1', [1 => $userWorkflowPermissionDeniedMessage]));
+ }
+ }
+ }
+ }
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
@@ -130,7 +157,7 @@ public static function del($messageTemplatesID) {
SET msg_template_id = NULL
WHERE msg_template_id = %1";
- $params = array(1 => array($messageTemplatesID, 'Integer'));
+ $params = [1 => [$messageTemplatesID, 'Integer']];
CRM_Core_DAO::executeQuery($query, $params);
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
@@ -150,7 +177,7 @@ public static function del($messageTemplatesID) {
* @return object
*/
public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
- $msgTpls = array();
+ $msgTpls = [];
$messageTemplates = new CRM_Core_DAO_MessageTemplate();
$messageTemplates->is_active = 1;
@@ -182,7 +209,7 @@ public static function sendReminder($contactId, $email, $messageTemplateID, $fro
$domain = CRM_Core_BAO_Domain::getDomain();
$result = NULL;
- $hookTokens = array();
+ $hookTokens = [];
if ($messageTemplates->find(TRUE)) {
$body_text = $messageTemplates->msg_text;
@@ -192,7 +219,7 @@ public static function sendReminder($contactId, $email, $messageTemplateID, $fro
$body_text = CRM_Utils_String::htmlToText($body_html);
}
- $params = array(array('contact_id', '=', $contactId, 0, 0));
+ $params = [['contact_id', '=', $contactId, 0, 0]];
list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
//CRM-4524
@@ -210,13 +237,13 @@ public static function sendReminder($contactId, $email, $messageTemplateID, $fro
CRM_Utils_Token::getTokens($body_subject));
// get replacement text for these tokens
- $returnProperties = array("preferred_mail_format" => 1);
+ $returnProperties = ["preferred_mail_format" => 1];
if (isset($tokens['contact'])) {
foreach ($tokens['contact'] as $key => $value) {
$returnProperties[$value] = 1;
}
}
- list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
+ list($details) = CRM_Utils_Token::getTokenDetails([$contactId],
$returnProperties,
NULL, NULL, FALSE,
$tokens,
@@ -224,12 +251,12 @@ public static function sendReminder($contactId, $email, $messageTemplateID, $fro
$contact = reset($details);
// call token hook
- $hookTokens = array();
+ $hookTokens = [];
CRM_Utils_Hook::tokens($hookTokens);
$categories = array_keys($hookTokens);
// do replacements in text and html body
- $type = array('html', 'text');
+ $type = ['html', 'text'];
foreach ($type as $key => $value) {
$bodyType = "body_{$value}";
if ($$bodyType) {
@@ -244,10 +271,10 @@ public static function sendReminder($contactId, $email, $messageTemplateID, $fro
$text = $body_text;
$smarty = CRM_Core_Smarty::singleton();
- foreach (array(
- 'text',
- 'html',
- ) as $elem) {
+ foreach ([
+ 'text',
+ 'html',
+ ] as $elem) {
$$elem = $smarty->fetch("string:{$$elem}");
}
@@ -260,13 +287,13 @@ public static function sendReminder($contactId, $email, $messageTemplateID, $fro
$messageSubject = $smarty->fetch("string:{$messageSubject}");
// set up the parameters for CRM_Utils_Mail::send
- $mailParams = array(
+ $mailParams = [
'groupName' => 'Scheduled Reminder Sender',
'from' => $from,
'toName' => $contact['display_name'],
'toEmail' => $email,
'subject' => $messageSubject,
- );
+ ];
if (!$html || $contact['preferred_mail_format'] == 'Text' ||
$contact['preferred_mail_format'] == 'Both'
) {
@@ -299,7 +326,7 @@ public static function revert($id) {
$diverted->find(1);
if ($diverted->N != 1) {
- CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
+ CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', [1 => $id]));
}
$orig = new CRM_Core_BAO_MessageTemplate();
@@ -308,7 +335,7 @@ public static function revert($id) {
$orig->find(1);
if ($orig->N != 1) {
- CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
+ CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', [1 => $id]));
}
$diverted->msg_subject = $orig->msg_subject;
@@ -328,7 +355,7 @@ public static function revert($id) {
* Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
*/
public static function sendTemplate($params) {
- $defaults = array(
+ $defaults = [
// option group name of the template
'groupName' => NULL,
// option value name of the template
@@ -338,7 +365,7 @@ public static function sendTemplate($params) {
// contact id if contact tokens are to be replaced
'contactId' => NULL,
// additional template params (other than the ones already set in the template singleton)
- 'tplParams' => array(),
+ 'tplParams' => [],
// the From: header
'from' => NULL,
// the recipient’s name
@@ -357,9 +384,14 @@ public static function sendTemplate($params) {
'isTest' => FALSE,
// filename of optional PDF version to add as attachment (do not include path)
'PDFFilename' => NULL,
- );
+ ];
$params = array_merge($defaults, $params);
+ // Core#644 - handle contact ID passed as "From".
+ if (isset($params['from'])) {
+ $params['from'] = CRM_Utils_Mail::formatFromAddress($params['from']);
+ }
+
CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
if ((!$params['groupName'] ||
@@ -375,7 +407,7 @@ public static function sendTemplate($params) {
$query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
FROM civicrm_msg_template mt
WHERE mt.id = %1 AND mt.is_default = 1';
- $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
+ $sqlParams = [1 => [$params['messageTemplateID'], 'String']];
}
else {
// fetch the three elements from the db based on option_group and option_value names
@@ -384,29 +416,32 @@ public static function sendTemplate($params) {
JOIN civicrm_option_value ov ON workflow_id = ov.id
JOIN civicrm_option_group og ON ov.option_group_id = og.id
WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
- $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
+ $sqlParams = [1 => [$params['groupName'], 'String'], 2 => [$params['valueName'], 'String']];
}
$dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
$dao->fetch();
if (!$dao->N) {
if ($params['messageTemplateID']) {
- CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
+ CRM_Core_Error::fatal(ts('No such message template: id=%1.', [1 => $params['messageTemplateID']]));
}
else {
- CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(
- 1 => $params['groupName'],
- 2 => $params['valueName'],
- )));
+ CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', [
+ 1 => $params['groupName'],
+ 2 => $params['valueName'],
+ ]));
}
}
- $mailContent = array(
+ $mailContent = [
'subject' => $dao->subject,
'text' => $dao->text,
'html' => $dao->html,
'format' => $dao->format,
- );
+ 'groupName' => $params['groupName'],
+ 'valueName' => $params['valueName'],
+ 'messageTemplateID' => $params['messageTemplateID'],
+ ];
$dao->free();
CRM_Utils_Hook::alterMailContent($mailContent);
@@ -429,7 +464,7 @@ public static function sendTemplate($params) {
// replace tokens in the three elements (in subject as if it was the text body)
$domain = CRM_Core_BAO_Domain::getDomain();
- $hookTokens = array();
+ $hookTokens = [];
$mailing = new CRM_Mailing_BAO_Mailing();
$mailing->subject = $mailContent['subject'];
$mailing->body_text = $mailContent['text'];
@@ -441,8 +476,8 @@ public static function sendTemplate($params) {
$contactID = CRM_Utils_Array::value('contactId', $params);
if ($contactID) {
- $contactParams = array('contact_id' => $contactID);
- $returnProperties = array();
+ $contactParams = ['contact_id' => $contactID];
+ $returnProperties = [];
if (isset($tokens['subject']['contact'])) {
foreach ($tokens['subject']['contact'] as $name) {
@@ -485,9 +520,9 @@ public static function sendTemplate($params) {
$mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
$mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
- $contactArray = array($contactID => $contact);
+ $contactArray = [$contactID => $contact];
CRM_Utils_Hook::tokenValues($contactArray,
- array($contactID),
+ [$contactID],
NULL,
CRM_Utils_Token::flattenTokens($tokens),
// we should consider adding groupName and valueName here
@@ -508,11 +543,11 @@ public static function sendTemplate($params) {
foreach ($params['tplParams'] as $name => $value) {
$smarty->assign($name, $value);
}
- foreach (array(
+ foreach ([
'subject',
'text',
'html',
- ) as $elem) {
+ ] as $elem) {
$mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
}
@@ -525,7 +560,7 @@ public static function sendTemplate($params) {
$params['html'] = $mailContent['html'];
if ($params['toEmail']) {
- $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
+ $contactParams = [['email', 'LIKE', $params['toEmail'], 0, 1]];
list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
$prefs = array_pop($contact);
@@ -542,7 +577,7 @@ public static function sendTemplate($params) {
if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
$pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
if (empty($params['attachments'])) {
- $params['attachments'] = array();
+ $params['attachments'] = [];
}
$params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
}
@@ -552,7 +587,7 @@ public static function sendTemplate($params) {
$params['html']
) {
if (empty($params['attachments'])) {
- $params['attachments'] = array();
+ $params['attachments'] = [];
}
$params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
if (isset($params['tplParams']['email_comment'])) {
@@ -568,7 +603,7 @@ public static function sendTemplate($params) {
}
}
- return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']);
+ return [$sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']];
}
}
diff --git a/CRM/Core/BAO/Navigation.php b/CRM/Core/BAO/Navigation.php
index b499f0ceb70a..90cc56fb1cf3 100644
--- a/CRM/Core/BAO/Navigation.php
+++ b/CRM/Core/BAO/Navigation.php
@@ -1,9 +1,9 @@
copyValues($params);
- $navigation->domain_id = CRM_Core_Config::domainID();
-
$navigation->save();
return $navigation;
}
@@ -172,10 +171,10 @@ public static function getNavigationList() {
$domainID = CRM_Core_Config::domainID();
$query = "
SELECT id, label, parent_id, weight, is_active, name
-FROM civicrm_navigation WHERE domain_id = $domainID {$whereClause} ORDER BY parent_id, weight ASC";
+FROM civicrm_navigation WHERE domain_id = $domainID";
$result = CRM_Core_DAO::executeQuery($query);
- $pidGroups = array();
+ $pidGroups = [];
while ($result->fetch()) {
$pidGroups[$result->parent_id][$result->label] = $result->id;
}
@@ -184,7 +183,7 @@ public static function getNavigationList() {
$pidGroups[''][$label] = self::_getNavigationValue($val, $pidGroups);
}
- $navigations = array();
+ $navigations = [];
self::_getNavigationLabel($pidGroups[''], $navigations);
CRM_Core_BAO_Cache::setItem($navigations, 'navigation', $cacheKeyString);
@@ -208,7 +207,7 @@ public static function _getNavigationLabel($list, &$navigations, $separator = ''
if ($label == 'navigation_id') {
continue;
}
- $translatedLabel = $i18n->crm_translate($label, array('context' => 'menu'));
+ $translatedLabel = $i18n->crm_translate($label, ['context' => 'menu']);
$navigations[is_array($val) ? $val['navigation_id'] : $val] = "{$separator}{$translatedLabel}";
if (is_array($val)) {
self::_getNavigationLabel($val, $navigations, $separator . ' ');
@@ -228,7 +227,7 @@ public static function _getNavigationLabel($list, &$navigations, $separator = ''
*/
public static function _getNavigationValue($val, &$pidGroups) {
if (array_key_exists($val, $pidGroups)) {
- $list = array('navigation_id' => $val);
+ $list = ['navigation_id' => $val];
foreach ($pidGroups[$val] as $label => $id) {
$list[$label] = self::_getNavigationValue($id, $pidGroups);
}
@@ -248,7 +247,7 @@ public static function _getNavigationValue($val, &$pidGroups) {
*/
public static function buildNavigationTree() {
$domainID = CRM_Core_Config::domainID();
- $navigationTree = array();
+ $navigationTree = [];
$navigationMenu = new self();
$navigationMenu->domain_id = $domainID;
@@ -256,20 +255,21 @@ public static function buildNavigationTree() {
$navigationMenu->find();
while ($navigationMenu->fetch()) {
- $navigationTree[$navigationMenu->id] = array(
- 'attributes' => array(
+ $navigationTree[$navigationMenu->id] = [
+ 'attributes' => [
'label' => $navigationMenu->label,
'name' => $navigationMenu->name,
'url' => $navigationMenu->url,
'icon' => $navigationMenu->icon,
+ 'weight' => $navigationMenu->weight,
'permission' => $navigationMenu->permission,
'operator' => $navigationMenu->permission_operator,
'separator' => $navigationMenu->has_separator,
'parentID' => $navigationMenu->parent_id,
'navID' => $navigationMenu->id,
'active' => $navigationMenu->is_active,
- ),
- );
+ ],
+ ];
}
return self::buildTree($navigationTree);
@@ -284,7 +284,7 @@ public static function buildNavigationTree() {
* @return array
*/
private static function buildTree($elements, $parentId = NULL) {
- $branch = array();
+ $branch = [];
foreach ($elements as $id => $element) {
if ($element['attributes']['parentID'] == $parentId) {
@@ -300,41 +300,29 @@ private static function buildTree($elements, $parentId = NULL) {
}
/**
- * Build menu.
- *
- * @return string
+ * buildNavigationTree retreives items in order. We call this function to
+ * ensure that any items added by the hook are also in the correct order.
*/
- public static function buildNavigation() {
- $navigations = self::buildNavigationTree();
- $navigationString = '';
+ public static function orderByWeight(&$navigations) {
+ // sort each item in navigations by weight
+ usort($navigations, function($a, $b) {
- // run the Navigation through a hook so users can modify it
- CRM_Utils_Hook::navigationMenu($navigations);
- self::fixNavigationMenu($navigations);
+ // If no weight have been defined for an item put it at the end of the list
+ if (!isset($a['attributes']['weight'])) {
+ $a['attributes']['weight'] = 1000;
+ }
+ if (!isset($b['attributes']['weight'])) {
+ $b['attributes']['weight'] = 1000;
+ }
+ return $a['attributes']['weight'] - $b['attributes']['weight'];
+ });
- //skip children menu item if user don't have access to parent menu item
- $skipMenuItems = array();
- foreach ($navigations as $key => $value) {
- // Home is a special case
- if ($value['attributes']['name'] != 'Home') {
- $name = self::getMenuName($value, $skipMenuItems);
- if ($name) {
- //separator before
- if (isset($value['attributes']['separator']) && $value['attributes']['separator'] == 2) {
- $navigationString .= '';
- }
- $removeCharacters = array('/', '!', '&', '*', ' ', '(', ')', '.');
- $navigationString .= '
' . $name;
- }
+ // If any of the $navigations have children, recurse
+ foreach ($navigations as $navigation) {
+ if (isset($navigation['child'])) {
+ self::orderByWeight($navigation['child']);
}
- self::recurseNavigation($value, $navigationString, $skipMenuItems);
}
-
- // clean up - Need to remove empty
's, this happens when user don't have
- // permission to access parent
- $navigationString = str_replace('
';
@@ -417,13 +424,13 @@ public static function handleUnhandledException($exception) {
CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other));
}
$config = CRM_Core_Config::singleton();
- $vars = array(
+ $vars = [
'message' => $exception->getMessage(),
'code' => NULL,
'exception' => $exception,
- );
+ ];
if (!$vars['message']) {
- $vars['message'] = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', array(1 => 'https://civicrm.org/bug-reporting'));
+ $vars['message'] = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', [1 => 'https://civicrm.org/bug-reporting']);
}
// Case A: CLI
@@ -610,7 +617,7 @@ public static function debug_log_message($message, $out = FALSE, $prefix = '', $
if (!empty(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) {
// should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
if ($config->userSystem->is_drupal and function_exists('watchdog')) {
- watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG);
+ watchdog('civicrm', '%message', ['%message' => $message], isset($priority) ? $priority : WATCHDOG_DEBUG);
}
}
@@ -640,7 +647,7 @@ public static function debug_query($string) {
*/
public static function debug_query_result($query) {
$results = CRM_Core_DAO::executeQuery($query)->fetchAll();
- CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results));
+ CRM_Core_Error::debug_var('dao result', ['query' => $query, 'results' => $results]);
}
/**
@@ -666,12 +673,12 @@ public static function createDebugLogger($prefix = '') {
*/
public static function generateLogFileHash($config) {
// Use multiple (but stable) inputs for hash information.
- $md5inputs = array(
+ $md5inputs = [
defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY',
$config->userFrameworkBaseURL,
md5($config->dsn),
$config->dsn,
- );
+ ];
// Trim 8 chars off the string, make it slightly easier to find
// but reveals less information from the hash.
return substr(md5(var_export($md5inputs, 1)), 8);
@@ -763,9 +770,9 @@ public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen
* @see Exception::getTrace()
*/
public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
- $ret = array();
+ $ret = [];
foreach ($backTrace as $trace) {
- $args = array();
+ $args = [];
$fnName = CRM_Utils_Array::value('function', $trace);
$className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
@@ -842,13 +849,13 @@ public static function formatHtmlException(Exception $e) {
// Exception backtrace
if ($e instanceof PEAR_Exception) {
$ei = $e;
- while (is_callable(array($ei, 'getCause'))) {
+ while (is_callable([$ei, 'getCause'])) {
if ($ei->getCause() instanceof PEAR_Error) {
$msg .= '
";
- return FALSE;
- }
-
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$transaction = new CRM_Core_Transaction();
@@ -133,7 +135,7 @@ public function recur(&$input, &$ids, &$objects, $first) {
$now = date('YmdHis');
// fix dates that already exist
- $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
+ $dates = ['create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date'];
foreach ($dates as $name) {
if ($recur->$name) {
$recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
@@ -154,6 +156,7 @@ public function recur(&$input, &$ids, &$objects, $first) {
$contribution->amount_level = $objects['contribution']->amount_level;
$contribution->address_id = $objects['contribution']->address_id;
$contribution->campaign_id = $objects['contribution']->campaign_id;
+ $contribution->_relatedObjects = $objects['contribution']->_relatedObjects;
$objects['contribution'] = &$contribution;
}
@@ -161,8 +164,6 @@ public function recur(&$input, &$ids, &$objects, $first) {
$objects['contribution']->total_amount = $input['amount'];
$objects['contribution']->trxn_id = $input['trxn_id'];
- $this->checkMD5($paymentProcessorObject, $input);
-
$isFirstOrLastRecurringPayment = FALSE;
if ($input['response_code'] == 1) {
// Approved
@@ -191,7 +192,7 @@ public function recur(&$input, &$ids, &$objects, $first) {
$recur->cancel_date = $now;
$recur->save();
- $message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text'])));
+ $message = ts("Subscription payment failed - %1", [1 => htmlspecialchars($input['response_reason_text'])]);
CRM_Core_Error::debug_log_message($message);
// the recurring contribution has declined a payment or has failed
@@ -256,7 +257,7 @@ public function getInput(&$input, &$ids) {
return FALSE;
}
$billingID = $ids['billing'];
- $params = array(
+ $params = [
'first_name' => 'x_first_name',
'last_name' => 'x_last_name',
"street_address-{$billingID}" => 'x_address',
@@ -265,7 +266,7 @@ public function getInput(&$input, &$ids) {
"postal_code-{$billingID}" => 'x_zip',
"country-{$billingID}" => 'x_country',
"email-{$billingID}" => 'x_email',
- );
+ ];
foreach ($params as $civiName => $resName) {
$input[$civiName] = $this->retrieve($resName, 'String', FALSE);
}
@@ -295,14 +296,14 @@ public function getIDs(&$ids, &$input) {
$contRecur->fetch();
$ids['contributionRecur'] = $contRecur->id;
if ($ids['contact'] != $contRecur->contact_id) {
- $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", array(1 => $ids['contact'], 2 => $contRecur->contact_id));
+ $message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", [1 => $ids['contact'], 2 => $contRecur->contact_id]);
CRM_Core_Error::debug_log_message($message);
$ids['contact'] = $contRecur->contact_id;
}
if (!$ids['contributionRecur']) {
$message = ts("Could not find contributionRecur id");
$log = new CRM_Utils_SystemLogger();
- $log->error('payment_notification', array('message' => $message, 'ids' => $ids, 'input' => $input));
+ $log->error('payment_notification', ['message' => $message, 'ids' => $ids, 'input' => $input]);
throw new CRM_Core_Exception($message);
}
@@ -356,25 +357,4 @@ public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
return $value;
}
- /**
- * Check and validate gateway MD5 response if present.
- *
- * @param CRM_Core_Payment_AuthorizeNet $paymentObject
- * @param array $input
- *
- * @throws CRM_Core_Exception
- */
- public function checkMD5($paymentObject, $input) {
- if (empty($input['trxn_id'])) {
- // For decline we have nothing to check against.
- return;
- }
- if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
- $message = "Failure: Security verification failed";
- $log = new CRM_Utils_SystemLogger();
- $log->error('payment_notification', array('message' => $message, 'input' => $input));
- throw new CRM_Core_Exception($message);
- }
- }
-
}
diff --git a/CRM/Core/Payment/BaseIPN.php b/CRM/Core/Payment/BaseIPN.php
index 822d74823807..35af834bd575 100644
--- a/CRM/Core/Payment/BaseIPN.php
+++ b/CRM/Core/Payment/BaseIPN.php
@@ -1,9 +1,9 @@
1,
'echo_error' => 1,
- );
+ ];
}
$ids['paymentProcessor'] = $paymentProcessorID;
if (is_a($objects['contribution'], 'CRM_Contribute_BAO_Contribution')) {
@@ -195,10 +195,10 @@ public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProces
echo $e->getMessage();
}
if (!empty($error_handling['return_error'])) {
- return array(
+ return [
'is_error' => 1,
'error_message' => ($e->getMessage()),
- );
+ ];
}
}
$objects = array_merge($objects, $contribution->_relatedObjects);
@@ -214,13 +214,13 @@ public function loadObjects(&$input, &$ids, &$objects, $required, $paymentProces
*
* @return bool
*/
- public function failed(&$objects, &$transaction, $input = array()) {
+ public function failed(&$objects, &$transaction, $input = []) {
$contribution = &$objects['contribution'];
- $memberships = array();
+ $memberships = [];
if (!empty($objects['membership'])) {
$memberships = &$objects['membership'];
if (is_numeric($memberships)) {
- $memberships = array($objects['membership']);
+ $memberships = [$objects['membership']];
}
}
@@ -231,10 +231,10 @@ public function failed(&$objects, &$transaction, $input = array()) {
$participant = &$objects['participant'];
// CRM-15546
- $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
- 'labelColumn' => 'name',
- 'flip' => 1,
- ));
+ $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
+ 'labelColumn' => 'name',
+ 'flip' => 1,
+ ]);
$contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
$contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
$contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
@@ -256,29 +256,26 @@ public function failed(&$objects, &$transaction, $input = array()) {
if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
if (!empty($memberships)) {
// if transaction is failed then set "Cancelled" as membership status
- $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
- 'labelColumn' => 'name',
- 'flip' => 1,
- ));
+ $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', [
+ 'labelColumn' => 'name',
+ 'flip' => 1,
+ ]);
foreach ($memberships as $membership) {
if ($membership) {
$membership->status_id = $membershipStatuses['Cancelled'];
$membership->save();
//update related Memberships.
- $params = array('status_id' => $membershipStatuses['Cancelled']);
+ $params = ['status_id' => $membershipStatuses['Cancelled']];
CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
}
}
}
if ($participant) {
- $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
- 'labelColumn' => 'name',
- 'flip' => 1,
- ));
- $participant->status_id = $participantStatuses['Cancelled'];
- $participant->save();
+ $participantParams['id'] = $participant->id;
+ $participantParams['status_id'] = 'Cancelled';
+ civicrm_api3('Participant', 'create', $participantParams);
}
}
@@ -312,11 +309,11 @@ public function pending(&$objects, &$transaction) {
*
* @return bool
*/
- public function cancelled(&$objects, &$transaction, $input = array()) {
+ public function cancelled(&$objects, &$transaction, $input = []) {
$contribution = &$objects['contribution'];
$memberships = &$objects['membership'];
if (is_numeric($memberships)) {
- $memberships = array($objects['membership']);
+ $memberships = [$objects['membership']];
}
$participant = &$objects['participant'];
@@ -324,10 +321,10 @@ public function cancelled(&$objects, &$transaction, $input = array()) {
if (empty($contribution->id)) {
$addLineItems = TRUE;
}
- $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
- 'labelColumn' => 'name',
- 'flip' => 1,
- ));
+ $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
+ 'labelColumn' => 'name',
+ 'flip' => 1,
+ ]);
$contribution->contribution_status_id = $contributionStatuses['Cancelled'];
$contribution->cancel_date = self::$_now;
$contribution->cancel_reason = CRM_Utils_Array::value('reasonCode', $input);
@@ -350,10 +347,10 @@ public function cancelled(&$objects, &$transaction, $input = array()) {
if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
if (!empty($memberships)) {
- $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', array(
- 'labelColumn' => 'name',
- 'flip' => 1,
- ));
+ $membershipStatuses = CRM_Core_PseudoConstant::get('CRM_Member_DAO_Membership', 'status_id', [
+ 'labelColumn' => 'name',
+ 'flip' => 1,
+ ]);
// Cancel only Pending memberships
// CRM-18688
$pendingStatusId = $membershipStatuses['Pending'];
@@ -363,19 +360,16 @@ public function cancelled(&$objects, &$transaction, $input = array()) {
$membership->save();
//update related Memberships.
- $params = array('status_id' => $membershipStatuses['Cancelled']);
+ $params = ['status_id' => $membershipStatuses['Cancelled']];
CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $params);
}
}
}
if ($participant) {
- $participantStatuses = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'status_id', array(
- 'labelColumn' => 'name',
- 'flip' => 1,
- ));
- $participant->status_id = $participantStatuses['Cancelled'];
- $participant->save();
+ $participantParams['id'] = $participant->id;
+ $participantParams['status_id'] = 'Cancelled';
+ civicrm_api3('Participant', 'create', $participantParams);
}
}
$transaction->commit();
@@ -470,7 +464,7 @@ public function completeTransaction(&$input, &$ids, &$objects, &$transaction, $r
public function getBillingID(&$ids) {
$ids['billing'] = CRM_Core_BAO_LocationType::getBilling();
if (!$ids['billing']) {
- CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
+ CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
echo "Failure: Could not find billing location type
";
return FALSE;
}
diff --git a/CRM/Core/Payment/Dummy.php b/CRM/Core/Payment/Dummy.php
index 1d68efe86812..d2f8c5c00d44 100644
--- a/CRM/Core/Payment/Dummy.php
+++ b/CRM/Core/Payment/Dummy.php
@@ -22,8 +22,8 @@ class CRM_Core_Payment_Dummy extends CRM_Core_Payment {
protected $_mode = NULL;
- protected $_params = array();
- protected $_doDirectPaymentResult = array();
+ protected $_params = [];
+ protected $_doDirectPaymentResult = [];
/**
* Set result from do Direct Payment for test purposes.
@@ -34,7 +34,7 @@ class CRM_Core_Payment_Dummy extends CRM_Core_Payment {
public function setDoDirectPaymentResult($doDirectPaymentResult) {
$this->_doDirectPaymentResult = $doDirectPaymentResult;
if (empty($this->_doDirectPaymentResult['trxn_id'])) {
- $this->_doDirectPaymentResult['trxn_id'] = array();
+ $this->_doDirectPaymentResult['trxn_id'] = [];
}
else {
$this->_doDirectPaymentResult['trxn_id'] = (array) $doDirectPaymentResult['trxn_id'];
@@ -104,7 +104,7 @@ public function doDirectPayment(&$params) {
}
if ($this->_mode == 'test') {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test\\_%'";
- $p = array();
+ $p = [];
$trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
$trxn_id = str_replace('test_', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -112,7 +112,7 @@ public function doDirectPayment(&$params) {
}
else {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'live_%'";
- $p = array();
+ $p = [];
$trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
$trxn_id = str_replace('live_', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -137,6 +137,33 @@ protected function supportsLiveMode() {
return TRUE;
}
+ /**
+ * Does this payment processor support refund?
+ *
+ * @return bool
+ */
+ public function supportsRefund() {
+ return TRUE;
+ }
+
+ /**
+ * Supports altering future start dates
+ * @return bool
+ */
+ public function supportsFutureRecurStartDate() {
+ return TRUE;
+ }
+
+ /**
+ * Submit a refund payment
+ *
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
+ *
+ * @param array $params
+ * Assoc array of input parameters for this transaction.
+ */
+ public function doRefund(&$params) {}
+
/**
* Generate error object.
*
@@ -195,7 +222,17 @@ public function checkConfig() {
* @return array
*/
public function getEditableRecurringScheduleFields() {
- return array('amount', 'next_sched_contribution_date');
+ return ['amount', 'next_sched_contribution_date'];
+ }
+
+ /**
+ * @param string $message
+ * @param array $params
+ *
+ * @return bool|object
+ */
+ public function cancelSubscription(&$message = '', $params = []) {
+ return TRUE;
}
}
diff --git a/CRM/Core/Payment/Elavon.php b/CRM/Core/Payment/Elavon.php
index b322859fe877..7b91ac425198 100644
--- a/CRM/Core/Payment/Elavon.php
+++ b/CRM/Core/Payment/Elavon.php
@@ -1,7 +1,7 @@
_mode == 'test') {
$query = "SELECT MAX(trxn_id) FROM civicrm_contribution WHERE trxn_id LIKE 'test%'";
- $p = array();
+ $p = [];
$trxn_id = strval(CRM_Core_Dao::singleValueQuery($query, $p));
$trxn_id = str_replace('test', '', $trxn_id);
$trxn_id = intval($trxn_id) + 1;
@@ -287,7 +287,7 @@ public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
*
*/
public function checkConfig() {
- $errorMsg = array();
+ $errorMsg = [];
if (empty($this->_paymentProcessor['user_name'])) {
$errorMsg[] = ' ' . ts('ssl_merchant_id is not set for this payment processor');
@@ -405,7 +405,7 @@ public function GetNodeValue($NodeName, &$strXML) {
* @return mixed
*/
public function decodeXMLresponse($Xml) {
- $processorResponse = array();
+ $processorResponse = [];
$processorResponse['ssl_result'] = self::GetNodeValue("ssl_result", $Xml);
$processorResponse['ssl_result_message'] = self::GetNodeValue("ssl_result_message", $Xml);
diff --git a/CRM/Core/Payment/FirstData.php b/CRM/Core/Payment/FirstData.php
index 116d2322ba53..a123e8f85dea 100644
--- a/CRM/Core/Payment/FirstData.php
+++ b/CRM/Core/Payment/FirstData.php
@@ -1,7 +1,7 @@
$paymentProcessor)));
+ CRM_Core_Error::fatal(ts('%1 - Gateway requires curl with SSL support', [1 => $paymentProcessor]));
}
/**********************************************************
@@ -309,6 +309,7 @@ public function doDirectPayment(&$params) {
return $params;
}
}
+
// end function doDirectPayment
/**
@@ -346,7 +347,7 @@ public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
* CiviCRM V2.0 Declaration
*/
public function checkConfig() {
- $errorMsg = array();
+ $errorMsg = [];
if (empty($this->_paymentProcessor['user_name'])) {
$errorMsg[] = ts(' Store Name is not set for this payment processor');
diff --git a/CRM/Core/Payment/Form.php b/CRM/Core/Payment/Form.php
index 4988ee531c79..027904845b36 100644
--- a/CRM/Core/Payment/Form.php
+++ b/CRM/Core/Payment/Form.php
@@ -1,9 +1,9 @@
billingFieldSets = array();
+ public static function setPaymentFieldsByProcessor(&$form, $processor, $billing_profile_id = NULL, $isBackOffice = FALSE, $paymentInstrumentID = NULL) {
+ $form->billingFieldSets = [];
// Load the pay-later processor
// @todo load this right up where the other processors are loaded initially.
if (empty($processor)) {
@@ -68,15 +67,14 @@ static public function setPaymentFieldsByProcessor(&$form, $processor, $billing_
$processor['object']->setPaymentInstrumentID($paymentInstrumentID);
$paymentTypeName = self::getPaymentTypeName($processor);
$form->assign('paymentTypeName', $paymentTypeName);
- $paymentTypeLabel = self::getPaymentTypeLabel($processor);
- $form->assign('paymentTypeLabel', $paymentTypeLabel);
+ $form->assign('paymentTypeLabel', self::getPaymentLabel($processor['object']));
$form->assign('isBackOffice', $isBackOffice);
$form->_paymentFields = $form->billingFieldSets[$paymentTypeName]['fields'] = self::getPaymentFieldMetadata($processor);
$form->_paymentFields = array_merge($form->_paymentFields, self::getBillingAddressMetadata($processor, $form->_bltID));
$form->assign('paymentFields', self::getPaymentFields($processor));
self::setBillingAddressFields($form, $processor);
// @todo - this may be obsolete - although potentially it could be used to re-order things in the form.
- $form->billingFieldSets['billing_name_address-group']['fields'] = array();
+ $form->billingFieldSets['billing_name_address-group']['fields'] = [];
}
/**
@@ -85,7 +83,7 @@ static public function setPaymentFieldsByProcessor(&$form, $processor, $billing_
* @param CRM_Core_Form $form
* @param CRM_Core_Payment $processor
*/
- static protected function setBillingAddressFields(&$form, $processor) {
+ protected static function setBillingAddressFields(&$form, $processor) {
$billingID = $form->_bltID;
$smarty = CRM_Core_Smarty::singleton();
$smarty->assign('billingDetailsFields', self::getBillingAddressFields($processor, $billingID));
@@ -114,26 +112,28 @@ static protected function setBillingAddressFields(&$form, $processor) {
* Fields that are to be shown on the payment form.
*/
protected static function addCommonFields(&$form, $paymentFields) {
- $requiredPaymentFields = array();
+ $requiredPaymentFields = $paymentFieldsMetadata = [];
foreach ($paymentFields as $name => $field) {
- // @todo - remove the cc_field check - no longer useful.
- if (!empty($field['cc_field'])) {
- if ($field['htmlType'] == 'chainSelect') {
- $form->addChainSelect($field['name'], array('required' => FALSE));
- }
- else {
- $form->add($field['htmlType'],
- $field['name'],
- $field['title'],
- $field['attributes'],
- FALSE
- );
- }
+ $field['extra'] = isset($field['extra']) ? $field['extra'] : NULL;
+ if ($field['htmlType'] == 'chainSelect') {
+ $form->addChainSelect($field['name'], ['required' => FALSE]);
+ }
+ else {
+ $form->add($field['htmlType'],
+ $field['name'],
+ $field['title'],
+ $field['attributes'],
+ FALSE,
+ $field['extra']
+ );
}
// This will cause the fields to be marked as required - but it is up to the payment processor to
// validate it.
$requiredPaymentFields[$field['name']] = $field['is_required'];
+ $paymentFieldsMetadata[$field['name']] = $field;
}
+
+ $form->assign('paymentFieldsMetadata', $paymentFieldsMetadata);
$form->assign('requiredPaymentFields', $requiredPaymentFields);
}
@@ -207,7 +207,7 @@ public static function getPaymentTypeName($paymentProcessor) {
* @return string
*/
public static function getPaymentTypeLabel($paymentProcessor) {
- return ts(($paymentProcessor['object']->getPaymentTypeLabel()) . ' Information');
+ return ts('%1 Information', [$paymentProcessor->getPaymentTypeLabel()]);
}
/**
@@ -282,27 +282,6 @@ public static function validatePaymentInstrument($payment_processor_id, $values,
$payment->validatePaymentInstrument($values, $errors);
}
- /**
- * The credit card pseudo constant results only the CC label, not the key ID
- * So we normalize the name to use it as a CSS class.
- */
- public static function getCreditCardCSSNames($creditCards = array()) {
- $creditCardTypes = array();
- if (empty($creditCards)) {
- $creditCards = CRM_Contribute_PseudoConstant::creditCard();
- }
- foreach ($creditCards as $key => $name) {
- // Replace anything not css-friendly by an underscore
- // Non-latin names will not like this, but so many things are wrong with
- // the credit-card type configurations already.
- $key = str_replace(' ', '', $key);
- $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
- $key = strtolower($key);
- $creditCardTypes[$key] = $name;
- }
- return $creditCardTypes;
- }
-
/**
* Set default values for the form.
*
@@ -365,7 +344,7 @@ public static function validateCreditCard($values, &$errors, $processorID = NULL
* @param bool $reverse
*/
public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
- $map = array(
+ $map = [
'first_name' => 'billing_first_name',
'middle_name' => 'billing_middle_name',
'last_name' => 'billing_last_name',
@@ -377,7 +356,7 @@ public static function mapParams($id, $src, &$dst, $reverse = FALSE) {
'postal_code' => "billing_postal_code-$id",
'country' => "billing_country-$id",
'contactID' => 'contact_id',
- );
+ ];
foreach ($map as $n => $v) {
if (!$reverse) {
@@ -426,4 +405,25 @@ public static function getCreditCardExpirationYear($src) {
return CRM_Utils_Array::value('Y', $src['credit_card_exp_date']);
}
+ /**
+ * Get the label for the processor.
+ *
+ * We do not use a label if there are no enterable fields.
+ *
+ * @param \CRM_Core_Payment $processor
+ *
+ * @return string
+ */
+ public static function getPaymentLabel($processor) {
+ $isVisible = FALSE;
+ $paymentTypeLabel = self::getPaymentTypeLabel($processor);
+ foreach (self::getPaymentFieldMetadata(['object' => $processor]) as $paymentField) {
+ if ($paymentField['htmlType'] !== 'hidden') {
+ $isVisible = TRUE;
+ }
+ }
+ return $isVisible ? $paymentTypeLabel : '';
+
+ }
+
}
diff --git a/CRM/Core/Payment/Manual.php b/CRM/Core/Payment/Manual.php
index 833609ad53e7..5621d712800c 100644
--- a/CRM/Core/Payment/Manual.php
+++ b/CRM/Core/Payment/Manual.php
@@ -1,9 +1,9 @@
'billing_first_name',
'middle_name' => 'billing_middle_name',
'last_name' => 'billing_last_name',
@@ -71,10 +71,10 @@ public function getBillingAddressFields($billingLocationID = NULL) {
'country' => "billing_country_id-{$billingLocationID}",
'state_province' => "billing_state_province_id-{$billingLocationID}",
'postal_code' => "billing_postal_code-{$billingLocationID}",
- );
+ ];
}
else {
- return array();
+ return [];
}
}
@@ -85,17 +85,17 @@ public function getBillingAddressFields($billingLocationID = NULL) {
*/
public function getPaymentFormFields() {
if (!$this->isBackOffice()) {
- return array();
+ return [];
}
$paymentInstrument = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $this->getPaymentInstrumentID());
if ($paymentInstrument === 'Credit Card') {
- return array('credit_card_type', 'pan_truncation');
+ return ['credit_card_type', 'pan_truncation'];
}
elseif ($paymentInstrument === 'Check') {
- return array('check_number');
+ return ['check_number'];
}
- return array();
+ return [];
}
/**
@@ -231,4 +231,30 @@ public function isSendReceiptForPending() {
return TRUE;
}
+ /**
+ * Get help text information (help, description, etc.) about this payment,
+ * to display to the user.
+ *
+ * @param string $context
+ * Context of the text.
+ * Only explicitly supported contexts are handled without error.
+ * Currently supported:
+ * - contributionPageRecurringHelp (params: is_recur_installments, is_email_receipt)
+ *
+ * @param array $params
+ * Parameters for the field, context specific.
+ *
+ * @return string
+ */
+ public function getText($context, $params) {
+ switch ($context) {
+ case 'contributionPageContinueText':
+ if ($params['amount'] <= 0) {
+ return ts('To complete this transaction, click the Continue button below.');
+ }
+ return ts('To complete your contribution, click the Continue button below.');
+
+ }
+ }
+
}
diff --git a/CRM/Core/Payment/PayJunction.php b/CRM/Core/Payment/PayJunction.php
index 3b70daea0650..42eeb94d4acb 100644
--- a/CRM/Core/Payment/PayJunction.php
+++ b/CRM/Core/Payment/PayJunction.php
@@ -66,7 +66,7 @@ public function doDirectPayment(&$params) {
$pjpgCustInfo->setEmail($params['email']);
- $billing = array(
+ $billing = [
"logon" => $logon,
"password" => $password,
"url_site" => $url_site,
@@ -77,7 +77,7 @@ public function doDirectPayment(&$params) {
"province" => $params['state_province'],
"postal_code" => $params['postal_code'],
"country" => $params['country'],
- );
+ ];
$pjpgCustInfo->setBilling($billing);
// create pjpgTransaction object
@@ -85,7 +85,7 @@ public function doDirectPayment(&$params) {
$expiry_string = sprintf('%04d%02d', $params['year'], $params['month']);
- $txnArray = array(
+ $txnArray = [
'type' => 'purchase',
'order_id' => $my_orderid,
'amount' => sprintf('%01.2f', $params['amount']),
@@ -94,7 +94,7 @@ public function doDirectPayment(&$params) {
'crypt_type' => '7',
'cavv' => $params['cvv2'],
'cust_id' => $params['contact_id'],
- );
+ ];
// Allow further manipulation of params via custom hooks
CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $txnArray);
@@ -126,7 +126,7 @@ public function doDirectPayment(&$params) {
$numRecurs = $params['installments'];
- $recurArray = array(
+ $recurArray = [
'dc_schedule_create' => $dc_schedule_create,
// (day | week | month)
'recur_unit' => $recurUnit,
@@ -137,7 +137,7 @@ public function doDirectPayment(&$params) {
'period' => $recurInterval,
'dc_schedule_start' => $dc_schedule_start,
'amount' => sprintf('%01.2f', $params['amount']),
- );
+ ];
$pjpgRecur = new pjpgRecur($recurArray);
@@ -170,6 +170,7 @@ public function doDirectPayment(&$params) {
return $params;
}
+
// end function doDirectPayment
/**
@@ -190,7 +191,6 @@ public function isError(&$response) {
}
}
-
/**
* ignore for now, more elaborate error handling later.
* @param $response
@@ -265,7 +265,7 @@ public function _setParam($field, $value) {
* the error message if any
*/
public function checkConfig() {
- $error = array();
+ $error = [];
if (empty($this->_paymentProcessor['user_name'])) {
$error[] = ts('Username is not set for this payment processor');
}
diff --git a/CRM/Core/Payment/PayPalIPN.php b/CRM/Core/Payment/PayPalIPN.php
index 9aa58748696e..cb68eff20150 100644
--- a/CRM/Core/Payment/PayPalIPN.php
+++ b/CRM/Core/Payment/PayPalIPN.php
@@ -1,9 +1,9 @@
_inputParameters),
- $type,
- FALSE
- );
+ $value = CRM_Utils_Type::validate(CRM_Utils_Array::value($name, $this->_inputParameters), $type, FALSE);
if ($abort && $value === NULL) {
- CRM_Core_Error::debug_log_message("Could not find an entry for $name");
+ Civi::log()->debug("PayPalIPN: Could not find an entry for $name");
echo "Failure: Missing Parameter
" . CRM_Utils_Type::escape($name, 'String');
- exit();
+ throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
}
return $value;
}
/**
- * @param $input
- * @param $ids
- * @param $objects
- * @param $first
+ * @param array $input
+ * @param array $ids
+ * @param array $objects
+ * @param bool $first
+ *
+ * @return void
*
- * @return bool
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function recur(&$input, &$ids, &$objects, $first) {
if (!isset($input['txnType'])) {
- CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
+ Civi::log()->debug('PayPalIPN: Could not find txn_type in input request');
echo "Failure: Invalid parameters
";
- return FALSE;
+ return;
}
if ($input['txnType'] == 'subscr_payment' &&
$input['paymentStatus'] != 'Completed'
) {
- CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
+ Civi::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
echo "Failure: Invalid parameters
";
- return FALSE;
+ return;
}
$recur = &$objects['contributionRecur'];
@@ -110,15 +108,15 @@ public function recur(&$input, &$ids, &$objects, $first) {
// make sure the invoice ids match
// make sure the invoice is valid and matches what we have in the contribution record
if ($recur->invoice_id != $input['invoice']) {
- CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
+ Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id . ').');
echo "Failure: Invoice values dont match between database and IPN request
";
- return FALSE;
+ return;
}
$now = date('YmdHis');
// fix dates that already exist
- $dates = array('create', 'start', 'end', 'cancel', 'modified');
+ $dates = ['create', 'start', 'end', 'cancel', 'modified'];
foreach ($dates as $date) {
$name = "{$date}_date";
if ($recur->$name) {
@@ -127,18 +125,19 @@ public function recur(&$input, &$ids, &$objects, $first) {
}
$sendNotification = FALSE;
$subscriptionPaymentStatus = NULL;
- //set transaction type
+ // set transaction type
$txnType = $this->retrieve('txn_type', 'String');
+ $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
switch ($txnType) {
case 'subscr_signup':
$recur->create_date = $now;
- //some times subscr_signup response come after the
- //subscr_payment and set to pending mode.
+ // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
+
$statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
$recur->id, 'contribution_status_id'
);
- if ($statusID != 5) {
- $recur->contribution_status_id = 2;
+ if ($statusID != $contributionStatuses['In Progress']) {
+ $recur->contribution_status_id = $contributionStatuses['Pending'];
}
$recur->processor_id = $this->retrieve('subscr_id', 'String');
$recur->trxn_id = $recur->processor_id;
@@ -147,8 +146,8 @@ public function recur(&$input, &$ids, &$objects, $first) {
break;
case 'subscr_eot':
- if ($recur->contribution_status_id != 3) {
- $recur->contribution_status_id = 1;
+ if ($recur->contribution_status_id != $contributionStatuses['Cancelled']) {
+ $recur->contribution_status_id = $contributionStatuses['Completed'];
}
$recur->end_date = $now;
$sendNotification = TRUE;
@@ -156,19 +155,19 @@ public function recur(&$input, &$ids, &$objects, $first) {
break;
case 'subscr_cancel':
- $recur->contribution_status_id = 3;
+ $recur->contribution_status_id = $contributionStatuses['Cancelled'];
$recur->cancel_date = $now;
break;
case 'subscr_failed':
- $recur->contribution_status_id = 4;
+ $recur->contribution_status_id = $contributionStatuses['Failed'];
$recur->modified_date = $now;
break;
case 'subscr_modify':
- CRM_Core_Error::debug_log_message("We do not handle modifications to subscriptions right now");
+ Civi::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id . ').');
echo "Failure: We do not handle modifications to subscriptions right now
";
- return FALSE;
+ return;
case 'subscr_payment':
if ($first) {
@@ -180,8 +179,8 @@ public function recur(&$input, &$ids, &$objects, $first) {
// make sure the contribution status is not done
// since order of ipn's is unknown
- if ($recur->contribution_status_id != 1) {
- $recur->contribution_status_id = 5;
+ if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
+ $recur->contribution_status_id = $contributionStatuses['In Progress'];
}
break;
}
@@ -189,7 +188,6 @@ public function recur(&$input, &$ids, &$objects, $first) {
$recur->save();
if ($sendNotification) {
-
$autoRenewMembership = FALSE;
if ($recur->id &&
isset($ids['membership']) && $ids['membership']
@@ -211,27 +209,28 @@ public function recur(&$input, &$ids, &$objects, $first) {
}
if (!$first) {
- //check if this contribution transaction is already processed
- //if not create a contribution and then get it processed
+ // check if this contribution transaction is already processed
+ // if not create a contribution and then get it processed
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->trxn_id = $input['trxn_id'];
if ($contribution->trxn_id && $contribution->find()) {
- CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
+ Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id . ')');
echo "Success: Contribution has already been handled
";
- return TRUE;
+ return;
}
- $contribution->contact_id = $ids['contact'];
- $contribution->financial_type_id = $objects['contributionType']->id;
- $contribution->contribution_page_id = $ids['contributionPage'];
- $contribution->contribution_recur_id = $ids['contributionRecur'];
- $contribution->receive_date = $now;
- $contribution->currency = $objects['contribution']->currency;
- $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
- $contribution->amount_level = $objects['contribution']->amount_level;
- $contribution->campaign_id = $objects['contribution']->campaign_id;
-
- $objects['contribution'] = &$contribution;
+ if ($input['paymentStatus'] != 'Completed') {
+ throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
+ }
+
+ // In future moving to create pending & then complete, but this OK for now.
+ // Also consider accepting 'Failed' like other processors.
+ $input['contribution_status_id'] = $contributionStatuses['Completed'];
+ $input['original_contribution_id'] = $ids['contribution'];
+ $input['contribution_recur_id'] = $ids['contributionRecur'];
+
+ civicrm_api3('Contribution', 'repeattransaction', $input);
+ return;
}
$this->single($input, $ids, $objects,
@@ -240,27 +239,23 @@ public function recur(&$input, &$ids, &$objects, $first) {
}
/**
- * @param $input
- * @param $ids
- * @param $objects
+ * @param array $input
+ * @param array $ids
+ * @param array $objects
* @param bool $recur
* @param bool $first
*
- * @return bool
+ * @return void
*/
- public function single(
- &$input, &$ids, &$objects,
- $recur = FALSE,
- $first = FALSE
- ) {
+ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
$contribution = &$objects['contribution'];
// make sure the invoice is valid and matches what we have in the contribution record
if ((!$recur) || ($recur && $first)) {
if ($contribution->invoice_id != $input['invoice']) {
- CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
+ Civi::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
echo "Failure: Invoice values dont match between database and IPN request
";
- return FALSE;
+ return;
}
}
else {
@@ -269,9 +264,9 @@ public function single(
if (!$recur) {
if ($contribution->total_amount != $input['amount']) {
- CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
+ Civi::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id . ').');
echo "Failure: Amount values dont match between database and IPN request
";
- return FALSE;
+ return;
}
}
else {
@@ -280,9 +275,6 @@ public function single(
$transaction = new CRM_Core_Transaction();
- $participant = &$objects['participant'];
- $membership = &$objects['membership'];
-
$status = $input['paymentStatus'];
if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
return $this->failed($objects, $transaction);
@@ -298,11 +290,12 @@ public function single(
}
// check if contribution is already completed, if so we ignore this ipn
- if ($contribution->contribution_status_id == 1) {
+ $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+ if ($contribution->contribution_status_id == $completedStatusId) {
$transaction->commit();
- CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
+ Civi::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id . ').');
echo "Success: Contribution has already been handled
";
- return TRUE;
+ return;
}
$this->completeTransaction($input, $ids, $objects, $transaction, $recur);
@@ -311,11 +304,11 @@ public function single(
/**
* Main function.
*
- * @return bool
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function main() {
-
- $objects = $ids = $input = array();
+ $objects = $ids = $input = [];
$component = $this->retrieve('module', 'String');
$input['component'] = $component;
@@ -337,23 +330,12 @@ public function main() {
$ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
}
- $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
- if (empty($paymentProcessorID)) {
- $processorParams = array(
- 'user_name' => $this->retrieve('business', 'String', FALSE),
- 'payment_processor_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name'),
- 'is_test' => empty($input['is_test']) ? 0 : 1,
- );
+ $paymentProcessorID = self::getPayPalPaymentProcessorID($input, $ids);
- $processorInfo = array();
- if (!CRM_Financial_BAO_PaymentProcessor::retrieve($processorParams, $processorInfo)) {
- return FALSE;
- }
- $paymentProcessorID = $processorInfo['id'];
- }
+ Civi::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
- return FALSE;
+ return;
}
self::$_paymentProcessor = &$objects['paymentProcessor'];
@@ -361,29 +343,26 @@ public function main() {
if ($ids['contributionRecur']) {
// check if first contribution is completed, else complete first contribution
$first = TRUE;
- if ($objects['contribution']->contribution_status_id == 1) {
+ $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+ if ($objects['contribution']->contribution_status_id == $completedStatusId) {
$first = FALSE;
}
- return $this->recur($input, $ids, $objects, $first);
+ $this->recur($input, $ids, $objects, $first);
+ return;
}
- else {
- return $this->single($input, $ids, $objects, FALSE, FALSE);
- }
- }
- else {
- return $this->single($input, $ids, $objects, FALSE, FALSE);
}
+ $this->single($input, $ids, $objects, FALSE, FALSE);
}
/**
- * @param $input
- * @param $ids
+ * @param array $input
+ * @param array $ids
*
- * @return bool
+ * @throws \CRM_Core_Exception
*/
public function getInput(&$input, &$ids) {
if (!$this->getBillingID($ids)) {
- return FALSE;
+ return;
}
$input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
@@ -393,7 +372,7 @@ public function getInput(&$input, &$ids) {
$input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
$billingID = $ids['billing'];
- $lookup = array(
+ $lookup = [
"first_name" => 'first_name',
"last_name" => 'last_name',
"street_address-{$billingID}" => 'address_street',
@@ -401,7 +380,7 @@ public function getInput(&$input, &$ids) {
"state-{$billingID}" => 'address_state',
"postal_code-{$billingID}" => 'address_zip',
"country-{$billingID}" => 'address_country_code',
- );
+ ];
foreach ($lookup as $name => $paypalName) {
$value = $this->retrieve($paypalName, 'String', FALSE);
$input[$name] = $value ? $value : NULL;
@@ -411,6 +390,69 @@ public function getInput(&$input, &$ids) {
$input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
$input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
$input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
+
+ $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
+ if (!empty($paymentDate)) {
+ $receiveDateTime = new DateTime($paymentDate);
+ /**
+ * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
+ * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
+ */
+ $systemTimeZone = new DateTimeZone(CRM_Core_Config::singleton()->userSystem->getTimeZoneString());
+ $receiveDateTime->setTimezone($systemTimeZone);
+ $input['receive_date'] = $receiveDateTime->format('YmdHis');
+ }
+ }
+
+ /**
+ * Gets PaymentProcessorID for PayPal
+ *
+ * @param array $input
+ * @param array $ids
+ *
+ * @return int
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
+ */
+ public function getPayPalPaymentProcessorID($input, $ids) {
+ // First we try and retrieve from POST params
+ $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
+ if (!empty($paymentProcessorID)) {
+ return $paymentProcessorID;
+ }
+
+ // Then we try and get it from recurring contribution ID
+ if (!empty($ids['contributionRecur'])) {
+ $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
+ 'id' => $ids['contributionRecur'],
+ 'return' => ['payment_processor_id'],
+ ]);
+ if (!empty($contributionRecur['payment_processor_id'])) {
+ return $contributionRecur['payment_processor_id'];
+ }
+ }
+
+ // This is an unreliable method as there could be more than one instance.
+ // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
+ // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
+ // entirely). The only thing the IPN class should really do is extract data from the request, validate it
+ // & call completetransaction or call fail? (which may not exist yet).
+
+ Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal IPN - this will cause problems if you have more than one instance');
+ // Then we try and retrieve based on business email ID
+ $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
+ $processorParams = [
+ 'user_name' => $this->retrieve('business', 'String', FALSE),
+ 'payment_processor_type_id' => $paymentProcessorTypeID,
+ 'is_test' => empty($input['is_test']) ? 0 : 1,
+ 'options' => ['limit' => 1],
+ 'return' => ['id'],
+ ];
+ $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
+ if (empty($paymentProcessorID)) {
+ throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
+ }
+ return $paymentProcessorID;
}
}
diff --git a/CRM/Core/Payment/PayPalImpl.php b/CRM/Core/Payment/PayPalImpl.php
index e2b64a60afef..5b4a109802e0 100644
--- a/CRM/Core/Payment/PayPalImpl.php
+++ b/CRM/Core/Payment/PayPalImpl.php
@@ -1,9 +1,9 @@
_mode = $mode;
$this->_paymentProcessor = $paymentProcessor;
- $this->_processorName = ts('PayPal Pro');
- $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
- if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
+ if ($this->isPayPalType($this::PAYPAL_STANDARD)) {
$this->_processorName = ts('PayPal Standard');
- return;
}
- elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) {
+ elseif ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
$this->_processorName = ts('PayPal Express');
}
+ elseif ($this->isPayPalType($this::PAYPAL_PRO)) {
+ $this->_processorName = ts('PayPal Pro');
+ }
+ else {
+ throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
+ }
+ }
+ /**
+ * Helper function to check which payment processor type is being used.
+ *
+ * @param $typeName
+ *
+ * @return bool
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
+ */
+ public function isPayPalType($typeName) {
+ // Historically payment_processor_type may have been set to the name of the processor but newer versions of CiviCRM use the id set in payment_processor_type_id
+ if (empty($this->_paymentProcessor['payment_processor_type_id']) && empty($this->_paymentProcessor['payment_processor_type'])) {
+ // We need one of them to be set!
+ throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
+ }
+ if (empty($this->_paymentProcessor['payment_processor_type_id']) && !empty($this->_paymentProcessor['payment_processor_type'])) {
+ // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not.
+ $this->_paymentProcessor['payment_processor_type_id']
+ = CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor['payment_processor_type']);
+ }
+ if ((int) $this->_paymentProcessor['payment_processor_type_id'] ===
+ CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) {
+ return TRUE;
+ }
+ return FALSE;
}
/**
@@ -74,9 +107,10 @@ public function __construct($mode, &$paymentProcessor) {
* with someone else's login.
*
* @return bool
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
protected function supportsBackOffice() {
- if ($this->_processorName == ts('PayPal Pro')) {
+ if ($this->isPayPalType($this::PAYPAL_PRO)) {
return TRUE;
}
return FALSE;
@@ -92,9 +126,10 @@ protected function supportsBackOffice() {
* 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
*
* @return bool
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
protected function supportsPreApproval() {
- if ($this->_processorName == ts('PayPal Express') || $this->_processorName == ts('PayPal Pro')) {
+ if ($this->isPayPalType($this::PAYPAL_EXPRESS) || $this->isPayPalType($this::PAYPAL_PRO)) {
return TRUE;
}
return FALSE;
@@ -107,20 +142,21 @@ protected function supportsPreApproval() {
*
* @return bool
* Should form building stop at this point?
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function buildForm(&$form) {
if ($this->supportsPreApproval()) {
$this->addPaypalExpressCode($form);
- if ($this->_processorName == ts('PayPal Express')) {
- CRM_Core_Region::instance('billing-block-post')->add(array(
+ if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
+ CRM_Core_Region::instance('billing-block-post')->add([
'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
'name' => 'paypal_express',
- ));
+ ]);
}
- if ($this->_processorName == ts('PayPal Pro')) {
- CRM_Core_Region::instance('billing-block-pre')->add(array(
+ if ($this->isPayPalType($this::PAYPAL_PRO)) {
+ CRM_Core_Region::instance('billing-block-pre')->add([
'template' => 'CRM/Financial/Form/PaypalPro.tpl',
- ));
+ ]);
}
}
return FALSE;
@@ -139,13 +175,25 @@ public function buildForm(&$form) {
protected function addPaypalExpressCode(&$form) {
// @todo use $this->isBackOffice() instead, test.
if (empty($form->isBackOffice)) {
- $form->_expressButtonName = $form->getButtonName('upload', 'express');
+
+ /**
+ * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment',
+ * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name
+ * and then clicking on express button it redirect to confirm screen rather than PayPal Express form
+ */
+
+ if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName) {
+ $form->_expressButtonName = '_qf_' . $form->_formName . '_upload_express';
+ }
+ else {
+ $form->_expressButtonName = $form->getButtonName('upload', 'express');
+ }
$form->assign('expressButtonName', $form->_expressButtonName);
$form->add(
'image',
$form->_expressButtonName,
$this->_paymentProcessor['url_button'],
- array('class' => 'crm-form-submit')
+ ['class' => 'crm-form-submit']
);
}
}
@@ -174,9 +222,11 @@ protected function supportsRecurContributionsForPledges() {
*
* @param array $values
* @param array $errors
+ *
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function validatePaymentInstrument($values, &$errors) {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) {
+ if ($this->isPayPalType($this::PAYPAL_PRO) && !$this->isPaypalExpress($values)) {
CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
}
@@ -195,7 +245,7 @@ public function validatePaymentInstrument($values, &$errors) {
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
protected function setExpressCheckOut(&$params) {
- $args = array();
+ $args = [];
$this->initialize($args, 'SetExpressCheckout');
@@ -239,9 +289,10 @@ protected function setExpressCheckOut(&$params) {
* @param array $storedDetails
*
* @return array
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function getPreApprovalDetails($storedDetails) {
- return empty($storedDetails['token']) ? array() : $this->getExpressCheckoutDetails($storedDetails['token']);
+ return empty($storedDetails['token']) ? [] : $this->getExpressCheckoutDetails($storedDetails['token']);
}
/**
@@ -254,9 +305,10 @@ public function getPreApprovalDetails($storedDetails) {
*
* @return array
* the result in an nice formatted array (or an error object)
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function getExpressCheckoutDetails($token) {
- $args = array();
+ $args = [];
$this->initialize($args, 'GetExpressCheckoutDetails');
$args['token'] = $token;
@@ -270,7 +322,7 @@ public function getExpressCheckoutDetails($token) {
}
/* Success */
- $fieldMap = array(
+ $fieldMap = [
'token' => 'token',
'payer_status' => 'payerstatus',
'payer_id' => 'payerid',
@@ -283,7 +335,7 @@ public function getExpressCheckoutDetails($token) {
'postal_code' => 'shiptozip',
'state_province' => 'shiptostate',
'country' => 'shiptocountrycode',
- );
+ ];
return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
}
@@ -304,7 +356,7 @@ public function doExpressCheckout(&$params) {
if (!empty($params['is_recur'])) {
return $this->createRecurringPayments($params);
}
- $args = array();
+ $args = [];
$this->initialize($args, 'DoExpressCheckoutPayment');
$args['token'] = $params['token'];
@@ -350,13 +402,16 @@ public function doExpressCheckout(&$params) {
/**
* Create recurring payments.
*
+ * Use a pre-authorisation token to activate a recurring payment profile
+ * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
+ *
* @param array $params
*
* @return mixed
+ * @throws \Exception
*/
public function createRecurringPayments(&$params) {
- $args = array();
- // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
+ $args = [];
$this->initialize($args, 'CreateRecurringPaymentsProfile');
$start_time = strtotime(date('m/d/Y'));
@@ -368,15 +423,12 @@ public function createRecurringPayments(&$params) {
$args['currencyCode'] = $params['currencyID'];
$args['payerID'] = $params['payer_id'];
$args['invnum'] = $params['invoiceID'];
- $args['returnURL'] = $params['returnURL'];
- $args['cancelURL'] = $params['cancelURL'];
$args['profilestartdate'] = $start_date;
$args['method'] = 'CreateRecurringPaymentsProfile';
$args['billingfrequency'] = $params['frequency_interval'];
$args['billingperiod'] = ucwords($params['frequency_unit']);
$args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
- //$args['desc'] = 'Recurring Contribution';
- $args['totalbillingcycles'] = $params['installments'];
+ $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
$args['version'] = '56.0';
$args['profilereference'] = "i={$params['invoiceID']}" .
"&m=" .
@@ -394,16 +446,18 @@ public function createRecurringPayments(&$params) {
return $result;
}
- /* Success */
- $params['trxn_id'] = $result['transactionid'];
- $params['gross_amount'] = $result['amt'];
- $params['fee_amount'] = $result['feeamt'];
- $params['net_amount'] = $result['settleamt'];
- if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
- $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
- }
- $params['payment_status'] = $result['paymentstatus'];
- $params['pending_reason'] = $result['pendingreason'];
+ /* Success - result looks like"
+ * array (
+ * 'profileid' => 'I-CP1U0PLG91R2',
+ * 'profilestatus' => 'ActiveProfile',
+ * 'timestamp' => '2018-05-07T03:55:52Z',
+ * 'correlationid' => 'e717999e9bf62',
+ * 'ack' => 'Success',
+ * 'version' => '56.0',
+ * 'build' => '39949200',)
+ */
+ $params['trxn_id'] = $result['profileid'];
+ $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
return $params;
}
@@ -424,7 +478,7 @@ public function initialize(&$args, $method) {
}
/**
- * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
+ * Process payment - this function wraps around both doTransferCheckout and doDirectPayment.
*
* The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
* more agnostic.
@@ -449,9 +503,7 @@ public function initialize(&$args, $method) {
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doPayment(&$params, $component = 'contribute') {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express'
- || ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !empty($params['token']))
- ) {
+ if ($this->isPayPalType($this::PAYPAL_EXPRESS) || ($this->isPayPalType($this::PAYPAL_PRO) && !empty($params['token']))) {
$this->_component = $component;
return $this->doExpressCheckout($params);
@@ -469,15 +521,16 @@ public function doPayment(&$params, $component = 'contribute') {
* @param string $component
* @return array
* the result in an nice formatted array (or an error object)
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doDirectPayment(&$params, $component = 'contribute') {
- $args = array();
+ $args = [];
$this->initialize($args, 'DoDirectPayment');
$args['paymentAction'] = 'Sale';
- $args['amt'] = $params['amount'];
- $args['currencyCode'] = $params['currencyID'];
+ $args['amt'] = $this->getAmount($params);
+ $args['currencyCode'] = $this->getCurrency($params);
$args['invnum'] = $params['invoiceID'];
$args['ipaddress'] = $params['ip_address'];
$args['creditCardType'] = $params['credit_card_type'];
@@ -512,7 +565,7 @@ public function doDirectPayment(&$params, $component = 'contribute') {
$params['amount'] . " Per " .
$params['frequency_interval'] . " " .
$params['frequency_unit'];
- $args['amt'] = $params['amount'];
+ $args['amt'] = $this->getAmount($params);
$args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
$args['version'] = 56.0;
$args['PROFILEREFERENCE'] = "" .
@@ -526,7 +579,7 @@ public function doDirectPayment(&$params, $component = 'contribute') {
$result = $this->invokeAPI($args);
- //WAG
+ // WAG
if (is_a($result, 'CRM_Core_Error')) {
return $result;
}
@@ -566,33 +619,33 @@ public function doDirectPayment(&$params, $component = 'contribute') {
public function doQuery($params) {
//CRM-18140 - trxn_id not returned for recurring paypal transaction
if (!empty($params['is_recur'])) {
- return array();
+ return [];
}
elseif (empty($params['trxn_id'])) {
throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
}
- $args = array(
+ $args = [
'TRANSACTIONID' => $params['trxn_id'],
- );
+ ];
$this->initialize($args, 'GetTransactionDetails');
$result = $this->invokeAPI($args);
- return array(
+ return [
'fee_amount' => $result['feeamt'],
'net_amount' => $params['gross_amount'] - $result['feeamt'],
- );
+ ];
}
/**
* This function checks to see if we have the right config values.
*
- * @return string
+ * @return null|string
* the error message if any
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function checkConfig() {
- $error = array();
- $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
+ $error = [];
- if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
+ if (!$this->isPayPalType($this::PAYPAL_STANDARD)) {
if (empty($this->_paymentProcessor['signature'])) {
$error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
}
@@ -615,9 +668,10 @@ public function checkConfig() {
/**
* @return null|string
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function cancelSubscriptionURL() {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
+ if ($this->isPayPalType($this::PAYPAL_STANDARD)) {
return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
}
else {
@@ -632,9 +686,10 @@ public function cancelSubscriptionURL() {
* Method to check for.
*
* @return bool
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function isSupported($method) {
- if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
+ if (!$this->isPayPalType($this::PAYPAL_PRO)) {
// since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
// by standard or express.
return FALSE;
@@ -647,9 +702,10 @@ public function isSupported($method) {
*
* @return bool
* Should the form button by suppressed?
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function isSuppressSubmitButtons() {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
+ if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
return TRUE;
}
return FALSE;
@@ -660,10 +716,11 @@ public function isSuppressSubmitButtons() {
* @param array $params
*
* @return array|bool|object
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
- public function cancelSubscription(&$message = '', $params = array()) {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
- $args = array();
+ public function cancelSubscription(&$message = '', $params = []) {
+ if ($this->isPayPalType($this::PAYPAL_PRO) || $this->isPayPalType($this::PAYPAL_EXPRESS)) {
+ $args = [];
$this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
$args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
@@ -682,23 +739,44 @@ public function cancelSubscription(&$message = '', $params = array()) {
/**
* Process incoming notification.
+ *
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
- static public function handlePaymentNotification() {
+ public static function handlePaymentNotification() {
$params = array_merge($_GET, $_REQUEST);
$q = explode('/', CRM_Utils_Array::value('q', $params, ''));
$lastParam = array_pop($q);
if (is_numeric($lastParam)) {
$params['processor_id'] = $lastParam;
}
- if (civicrm_api3('PaymentProcessor', 'getvalue', array(
- 'id' => $params['processor_id'],
- 'return' => 'class_name')
- ) == 'Payment_PayPalImpl') {
- $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
+ $result = civicrm_api3('PaymentProcessor', 'get', [
+ 'sequential' => 1,
+ 'id' => $params['processor_id'],
+ 'api.PaymentProcessorType.getvalue' => ['return' => "name"],
+ ]);
+ if (!$result['count']) {
+ throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
}
- else {
- $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
+
+ $paymentProcessorType = CRM_Utils_Array::value('api.PaymentProcessorType.getvalue', $result['values'][0]);
+ switch ($paymentProcessorType) {
+ case 'PayPal':
+ // "PayPal - Website Payments Pro"
+ $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
+ break;
+
+ case 'PayPal_Standard':
+ // "PayPal - Website Payments Standard"
+ $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
+ break;
+
+ default:
+ // If we don't have PayPal Standard or PayPal Pro, something's wrong.
+ // Log an error and exit.
+ throw new CRM_Core_Exception("The processor_id value '{$params['processor_id']}' is for a processor of type '{$paymentProcessorType}', which is invalid in this context.");
}
+
$paypalIPN->main();
}
@@ -707,15 +785,16 @@ static public function handlePaymentNotification() {
* @param array $params
*
* @return array|bool|object
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
- public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
+ public function updateSubscriptionBillingInfo(&$message = '', $params = []) {
+ if ($this->isPayPalType($this::PAYPAL_PRO)) {
$config = CRM_Core_Config::singleton();
- $args = array();
+ $args = [];
$this->initialize($args, 'UpdateRecurringPaymentsProfile');
$args['PROFILEID'] = $params['subscriptionId'];
- $args['AMT'] = $params['amount'];
+ $args['AMT'] = $this->getAmount($params);
$args['CURRENCYCODE'] = $config->defaultCurrency;
$args['CREDITCARDTYPE'] = $params['credit_card_type'];
$args['ACCT'] = $params['credit_card_number'];
@@ -745,15 +824,16 @@ public function updateSubscriptionBillingInfo(&$message = '', $params = array())
* @param array $params
*
* @return array|bool|object
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
- public function changeSubscriptionAmount(&$message = '', $params = array()) {
- if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
+ public function changeSubscriptionAmount(&$message = '', $params = []) {
+ if ($this->isPayPalType($this::PAYPAL_PRO)) {
$config = CRM_Core_Config::singleton();
- $args = array();
+ $args = [];
$this->initialize($args, 'UpdateRecurringPaymentsProfile');
$args['PROFILEID'] = $params['subscriptionId'];
- $args['AMT'] = $params['amount'];
+ $args['AMT'] = $this->getAmount($params);
$args['CURRENCYCODE'] = $config->defaultCurrency;
$args['BILLINGFREQUENCY'] = $params['installments'];
@@ -777,17 +857,18 @@ public function changeSubscriptionAmount(&$message = '', $params = array()) {
* @return array
* - pre_approval_parameters (this will be stored on the calling form & available later)
* - redirect_url (if set the browser will be redirected to this.
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doPreApproval(&$params) {
if (!$this->isPaypalExpress($params)) {
- return array();
+ return [];
}
$this->_component = $params['component'];
$token = $this->setExpressCheckOut($params);
- return array(
- 'pre_approval_parameters' => array('token' => $token),
+ return [
+ 'pre_approval_parameters' => ['token' => $token],
'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
- );
+ ];
}
/**
@@ -798,8 +879,8 @@ public function doPreApproval(&$params) {
*/
public function doTransferCheckout(&$params, $component = 'contribute') {
- $notifyParameters = array('module' => $component);
- $notifyParameterMap = array(
+ $notifyParameters = ['module' => $component];
+ $notifyParameterMap = [
'contactID' => 'contactID',
'contributionID' => 'contributionID',
'eventID' => 'eventID',
@@ -810,7 +891,7 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
'accountingCode' => 'accountingCode',
'contributionRecurID' => 'contributionRecurID',
'contributionPageID' => 'contributionPageID',
- );
+ ];
foreach ($notifyParameterMap as $paramsName => $notifyName) {
if (!empty($params[$paramsName])) {
$notifyParameters[$notifyName] = $params[$paramsName];
@@ -833,7 +914,7 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
TRUE, NULL, FALSE
);
- $paypalParams = array(
+ $paypalParams = [
'business' => $this->_paymentProcessor['user_name'],
'notify_url' => $notifyURL,
'item_name' => $this->getPaymentDescription($params, 127),
@@ -850,10 +931,10 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
'custom' => json_encode($notifyParameters),
'bn' => 'CiviCRM_SP',
- );
+ ];
// add name and address if available, CRM-3130
- $otherVars = array(
+ $otherVars = [
'first_name' => 'first_name',
'last_name' => 'last_name',
'street_address' => 'address1',
@@ -863,7 +944,7 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
'state_province' => 'state',
'postal_code' => 'zip',
'email' => 'email',
- );
+ ];
foreach (array_keys($params) as $p) {
// get the base name without the location type suffixed to it
@@ -895,9 +976,9 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
}
- $paypalParams += array(
+ $paypalParams += [
'cmd' => '_xclick-subscriptions',
- 'a3' => $params['amount'],
+ 'a3' => $this->getAmount($params),
'p3' => $params['frequency_interval'],
't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
'src' => 1,
@@ -905,13 +986,13 @@ public function doTransferCheckout(&$params, $component = 'contribute') {
'srt' => CRM_Utils_Array::value('installments', $params),
'no_note' => 1,
'modify' => 0,
- );
+ ];
}
else {
- $paypalParams += array(
+ $paypalParams += [
'cmd' => '_xclick',
'amount' => $params['amount'],
- );
+ ];
}
// Allow further manipulation of the arguments via custom hooks ..
@@ -964,6 +1045,14 @@ public function invokeAPI($args, $url = NULL) {
$url = $this->_paymentProcessor['url_api'] . 'nvp';
}
+ $p = [];
+ foreach ($args as $n => $v) {
+ $p[] = "$n=" . urlencode($v);
+ }
+
+ //NVPRequest for submitting to server
+ $nvpreq = implode('&', $p);
+
if (!function_exists('curl_init')) {
CRM_Core_Error::fatal("curl functions NOT available.");
}
@@ -980,14 +1069,6 @@ public function invokeAPI($args, $url = NULL) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
- $p = array();
- foreach ($args as $n => $v) {
- $p[] = "$n=" . urlencode($v);
- }
-
- //NVPRequest for submitting to server
- $nvpreq = implode('&', $p);
-
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
@@ -1009,9 +1090,9 @@ public function invokeAPI($args, $url = NULL) {
curl_close($ch);
}
- if (strtolower($result['ack']) != 'success' &&
- strtolower($result['ack']) != 'successwithwarning'
- ) {
+ $outcome = strtolower(CRM_Utils_Array::value('ack', $result));
+
+ if ($outcome != 'success' && $outcome != 'successwithwarning') {
throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
$e = CRM_Core_Error::singleton();
$e->push($result['l_errorcode0'],
@@ -1034,7 +1115,7 @@ public function invokeAPI($args, $url = NULL) {
* @return array
*/
public static function deformat($str) {
- $result = array();
+ $result = [];
while (strlen($str)) {
// position of key
@@ -1060,14 +1141,14 @@ public static function deformat($str) {
* Get array of fields that should be displayed on the payment form.
*
* @return array
- * @throws CiviCRM_API3_Exception
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function getPaymentFormFields() {
- if ($this->_processorName == ts('PayPal Pro')) {
+ if ($this->isPayPalType($this::PAYPAL_PRO)) {
return $this->getCreditCardFormFields();
}
else {
- return array();
+ return [];
}
}
@@ -1080,7 +1161,7 @@ public function getPaymentFormFields() {
* @return array
*/
protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
- $params = array();
+ $params = [];
foreach ($fieldMap as $civicrmField => $paypalField) {
$params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
}
@@ -1095,9 +1176,10 @@ protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
* @param array $params
*
* @return bool
+ * @throws \Civi\Payment\Exception\PaymentProcessorException
*/
protected function isPaypalExpress($params) {
- if ($this->_processorName == ts('PayPal Express')) {
+ if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
return TRUE;
}
@@ -1111,10 +1193,10 @@ protected function isPaypalExpress($params) {
// The contribution form passes a 'button' but the event form might still set one of these fields.
// @todo more standardisation & get paypal fully out of the form layer.
- $possibleExpressFields = array(
+ $possibleExpressFields = [
'_qf_Register_upload_express_x',
'_qf_Payment_upload_express_x',
- );
+ ];
if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {
return TRUE;
}
diff --git a/CRM/Core/Payment/PayPalProIPN.php b/CRM/Core/Payment/PayPalProIPN.php
index adac726bfa88..d88f12de7dec 100644
--- a/CRM/Core/Payment/PayPalProIPN.php
+++ b/CRM/Core/Payment/PayPalProIPN.php
@@ -1,9 +1,9 @@
_inputParameters['rp_invoice_id']);
// for clarify let's also store without the single letter unreadable
//@todo after more refactoring we might ditch storing the one letter stuff
- $mapping = array(
+ $mapping = [
'i' => 'invoice_id',
'm' => 'component',
'c' => 'contact_id',
@@ -111,7 +112,7 @@ public function setInvoiceData() {
'r' => 'contribution_recur_id',
'p' => 'participant_id',
'e' => 'event_id',
- );
+ ];
foreach ($rpInvoiceArray as $rpInvoiceValue) {
$rpValueArray = explode('=', $rpInvoiceValue);
$this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
@@ -161,13 +162,13 @@ public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
* @param array $ids
* @param array $objects
* @param bool $first
- * @return bool
+ * @return void
*/
public function recur(&$input, &$ids, &$objects, $first) {
if (!isset($input['txnType'])) {
- CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
+ Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
echo "Failure: Invalid parameters
";
- return FALSE;
+ return;
}
$recur = &$objects['contributionRecur'];
@@ -176,15 +177,15 @@ public function recur(&$input, &$ids, &$objects, $first) {
// make sure the invoice is valid and matches what we have in
// the contribution record
if ($recur->invoice_id != $input['invoice']) {
- CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
+ Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
- return FALSE;
+ return;
}
$now = date('YmdHis');
// fix dates that already exist
- $dates = array('create', 'start', 'end', 'cancel', 'modified');
+ $dates = ['create', 'start', 'end', 'cancel', 'modified'];
foreach ($dates as $date) {
$name = "{$date}_date";
if ($recur->$name) {
@@ -211,21 +212,20 @@ public function recur(&$input, &$ids, &$objects, $first) {
//set transaction type
$txnType = $this->retrieve('txn_type', 'String');
//Changes for paypal pro recurring payment
- $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
- $contributionStatuses = $contributionStatuses['values'];
+ $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
switch ($txnType) {
case 'recurring_payment_profile_created':
- if (in_array($recur->contribution_status_id, array(
- array_search('Pending', $contributionStatuses),
- array_search('In Progress', $contributionStatuses),
- ))
+ if (in_array($recur->contribution_status_id, [
+ $contributionStatuses['Pending'],
+ $contributionStatuses['In Progress'],
+ ])
&& !empty($recur->processor_id)
) {
echo "already handled";
- return FALSE;
+ return;
}
$recur->create_date = $now;
- $recur->contribution_status_id = 2;
+ $recur->contribution_status_id = $contributionStatuses['Pending'];
$recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
$recur->trxn_id = $recur->processor_id;
$subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
@@ -237,16 +237,16 @@ public function recur(&$input, &$ids, &$objects, $first) {
$recur->start_date = $now;
}
else {
- $input['invoice_id'] = md5(uniqid(rand(), TRUE));
- $input['original_contribution_id'] = $ids['contribution'];
- $input['contribution_recur_id'] = $ids['contributionRecur'];
-
if ($input['paymentStatus'] != 'Completed') {
throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
}
+
// In future moving to create pending & then complete, but this OK for now.
// Also consider accepting 'Failed' like other processors.
- $input['contribution_status_id'] = 1;
+ $input['contribution_status_id'] = $contributionStatuses['Completed'];
+ $input['invoice_id'] = md5(uniqid(rand(), TRUE));
+ $input['original_contribution_id'] = $ids['contribution'];
+ $input['contribution_recur_id'] = $ids['contributionRecur'];
civicrm_api3('Contribution', 'repeattransaction', $input);
return;
@@ -256,9 +256,9 @@ public function recur(&$input, &$ids, &$objects, $first) {
if ($this->retrieve('profile_status', 'String') == 'Expired') {
if (!empty($recur->end_date)) {
echo "already handled";
- return FALSE;
+ return;
}
- $recur->contribution_status_id = 1;
+ $recur->contribution_status_id = $contributionStatuses['Completed'];
$recur->end_date = $now;
$sendNotification = TRUE;
$subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
@@ -266,8 +266,8 @@ public function recur(&$input, &$ids, &$objects, $first) {
// make sure the contribution status is not done
// since order of ipn's is unknown
- if ($recur->contribution_status_id != 1) {
- $recur->contribution_status_id = 5;
+ if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
+ $recur->contribution_status_id = $contributionStatuses['In Progress'];
}
break;
}
@@ -291,7 +291,7 @@ public function recur(&$input, &$ids, &$objects, $first) {
}
if ($txnType != 'recurring_payment') {
- return TRUE;
+ return;
}
if (!$first) {
@@ -300,9 +300,9 @@ public function recur(&$input, &$ids, &$objects, $first) {
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->trxn_id = $input['trxn_id'];
if ($contribution->trxn_id && $contribution->find()) {
- CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
+ Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
echo "Success: Contribution has already been handled
";
- return TRUE;
+ return;
}
$contribution->contact_id = $recur->contact_id;
@@ -319,19 +319,17 @@ public function recur(&$input, &$ids, &$objects, $first) {
// CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
$objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
- $this->single($input, $ids, $objects,
- TRUE, $first
- );
+ $this->single($input, $ids, $objects, TRUE, $first);
}
/**
- * @param $input
- * @param $ids
- * @param $objects
+ * @param array $input
+ * @param array $ids
+ * @param array $objects
* @param bool $recur
* @param bool $first
*
- * @return bool
+ * @return void
*/
public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
$contribution = &$objects['contribution'];
@@ -339,9 +337,9 @@ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE
// make sure the invoice is valid and matches what we have in the contribution record
if ((!$recur) || ($recur && $first)) {
if ($contribution->invoice_id != $input['invoice']) {
- CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
+ Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
echo "Failure: Invoice values dont match between database and IPN request
contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
- return FALSE;
+ return;
}
}
else {
@@ -350,9 +348,9 @@ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE
if (!$recur) {
if ($contribution->total_amount != $input['amount']) {
- CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
+ Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
echo "Failure: Amount values dont match between database and IPN request
";
- return FALSE;
+ return;
}
}
else {
@@ -363,24 +361,29 @@ public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE
$status = $input['paymentStatus'];
if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
- return $this->failed($objects, $transaction);
+ $this->failed($objects, $transaction);
+ return;
}
elseif ($status == 'Pending') {
- return $this->pending($objects, $transaction);
+ $this->pending($objects, $transaction);
+ return;
}
elseif ($status == 'Refunded' || $status == 'Reversed') {
- return $this->cancelled($objects, $transaction);
+ $this->cancelled($objects, $transaction);
+ return;
}
elseif ($status != 'Completed') {
- return $this->unhandled($objects, $transaction);
+ $this->unhandled($objects, $transaction);
+ return;
}
// check if contribution is already completed, if so we ignore this ipn
- if ($contribution->contribution_status_id == 1) {
+ $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+ if ($contribution->contribution_status_id == $completedStatusId) {
$transaction->commit();
- CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
+ Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
echo "Success: Contribution has already been handled
";
- return TRUE;
+ return;
}
$this->completeTransaction($input, $ids, $objects, $transaction, $recur);
@@ -397,15 +400,18 @@ public function getPayPalPaymentProcessorID() {
// processor id & the handleNotification function (which should call the completetransaction api & by-pass this
// entirely). The only thing the IPN class should really do is extract data from the request, validate it
// & call completetransaction or call fail? (which may not exist yet).
+
+ Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal Pro IPN - this will cause problems if you have more than one instance');
+
$paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
'PayPal', 'id', 'name'
);
- return (int) civicrm_api3('PaymentProcessor', 'getvalue', array(
+ return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
'is_test' => 0,
- 'options' => array('limit' => 1),
+ 'options' => ['limit' => 1],
'payment_processor_type_id' => $paymentProcessorTypeID,
'return' => 'id',
- ));
+ ]);
}
@@ -414,16 +420,16 @@ public function getPayPalPaymentProcessorID() {
* (with the input parameters) & call this & all will be done
*
* @todo the references to POST throughout this class need to be removed
- * @return bool
+ * @return void
*/
public function main() {
CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
if ($this->_isPaymentExpress) {
$this->handlePaymentExpress();
- return FALSE;
+ return;
}
- $objects = $ids = $input = array();
+ $objects = $ids = $input = [];
$this->_component = $input['component'] = self::getValue('m');
$input['invoice'] = self::getValue('i', TRUE);
// get the contribution and contact ids from the GET params
@@ -455,25 +461,19 @@ public function main() {
INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
WHERE m.contribution_recur_id = %2
LIMIT 1";
- $sqlParams = array(
- 1 => array($ids['contribution'], 'Integer'),
- 2 => array($ids['contributionRecur'], 'Integer'),
- );
+ $sqlParams = [
+ 1 => [$ids['contribution'], 'Integer'],
+ 2 => [$ids['contributionRecur'], 'Integer'],
+ ];
if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
$ids['membership'] = $membershipId;
}
}
- // This is an unreliable method as there could be more than one instance.
- // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
- // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
- // entirely). The only thing the IPN class should really do is extract data from the request, validate it
- // & call completetransaction or call fail? (which may not exist yet).
-
$paymentProcessorID = self::getPayPalPaymentProcessorID();
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
- return FALSE;
+ return;
}
self::$_paymentProcessor = &$objects['paymentProcessor'];
@@ -484,31 +484,27 @@ public function main() {
if ($ids['contributionRecur']) {
// check if first contribution is completed, else complete first contribution
$first = TRUE;
- if ($objects['contribution']->contribution_status_id == 1) {
+ $completedStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+ if ($objects['contribution']->contribution_status_id == $completedStatusId) {
$first = FALSE;
}
- return $this->recur($input, $ids, $objects, $first);
- }
- else {
- return $this->single($input, $ids, $objects, FALSE, FALSE);
+ $this->recur($input, $ids, $objects, $first);
+ return;
}
}
- else {
- return $this->single($input, $ids, $objects, FALSE, FALSE);
- }
+ $this->single($input, $ids, $objects, FALSE, FALSE);
}
/**
- * @param $input
- * @param $ids
+ * @param array $input
+ * @param array $ids
*
- * @return bool
+ * @return void
* @throws CRM_Core_Exception
*/
public function getInput(&$input, &$ids) {
-
if (!$this->getBillingID($ids)) {
- return FALSE;
+ return;
}
$input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
@@ -518,7 +514,7 @@ public function getInput(&$input, &$ids) {
$input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
$billingID = $ids['billing'];
- $lookup = array(
+ $lookup = [
"first_name" => 'first_name',
"last_name" => 'last_name',
"street_address-{$billingID}" => 'address_street',
@@ -526,7 +522,7 @@ public function getInput(&$input, &$ids) {
"state-{$billingID}" => 'address_state',
"postal_code-{$billingID}" => 'address_zip',
"country-{$billingID}" => 'address_country_code',
- );
+ ];
foreach ($lookup as $name => $paypalName) {
$value = self::retrieve($paypalName, 'String', 'POST', FALSE);
$input[$name] = $value ? $value : NULL;
@@ -537,10 +533,12 @@ public function getInput(&$input, &$ids) {
$input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
$input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
$input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
+ $input['total_amount'] = $input['amount'];
}
/**
* Handle payment express IPNs.
+ *
* For one off IPNS no actual response is required
* Recurring is more difficult as we have limited confirmation material
* lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
@@ -557,49 +555,56 @@ public function handlePaymentExpress() {
// also note that a lot of the complexity above could be removed if we used
// http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
// as membership id etc can be derived by the load objects fn
- $objects = $ids = $input = array();
+ $objects = $ids = $input = [];
$isFirst = FALSE;
+ $input['invoice'] = self::getValue('i', FALSE);
+ //Avoid return in case of unit test.
+ if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
+ return;
+ }
$input['txnType'] = $this->retrieve('txn_type', 'String');
- if ($input['txnType'] != 'recurring_payment') {
+ $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
+ 'return' => 'contact_id, id, payment_processor_id',
+ 'invoice_id' => $input['invoice'],
+ ]);
+
+ if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
}
- $input['invoice'] = self::getValue('i', FALSE);
+
$this->getInput($input, $ids);
- if ($this->transactionExists($input['trxn_id'])) {
+ if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
throw new CRM_Core_Exception('This transaction has already been processed');
}
- $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array(
- 'return' => 'contact_id, id',
- 'invoice_id' => $input['invoice'],
- ));
$ids['contact'] = $contributionRecur['contact_id'];
$ids['contributionRecur'] = $contributionRecur['id'];
- $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice']));
+ $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
$ids['contribution'] = $result['id'];
- //@todo hard - coding 'pending' for now
- if ($result['contribution_status_id'] == 2) {
+ //@todo hardcoding 'pending' for now
+ $pendingStatusId = CRM_Core_Pseudoconstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
+ if ($result['contribution_status_id'] == $pendingStatusId) {
$isFirst = TRUE;
}
// arg api won't get this - fix it
- $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(
- 1 => array(
- $ids['contribution'],
- 'Integer',
- ),
- ));
+ $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
+ 1 => [
+ $ids['contribution'],
+ 'Integer',
+ ],
+ ]);
// only handle component at this stage - not terribly sure how a recurring event payment would arise
// & suspec main function may be a victom of copy & paste
// membership would be an easy add - but not relevant to my customer...
$this->_component = $input['component'] = 'contribute';
$input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self::retrieve('time_created', 'String')));
- $paymentProcessorID = self::getPayPalPaymentProcessorID();
+ $paymentProcessorID = $contributionRecur['payment_processor_id'];
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
throw new CRM_Core_Exception('Data did not validate');
}
- return $this->recur($input, $ids, $objects, $isFirst);
+ $this->recur($input, $ids, $objects, $isFirst);
}
/**
@@ -609,9 +614,9 @@ public function handlePaymentExpress() {
*/
public function transactionExists($trxn_id) {
if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
- array(
- 1 => array($trxn_id, 'String'),
- ))
+ [
+ 1 => [$trxn_id, 'String'],
+ ])
) {
return TRUE;
}
diff --git a/CRM/Core/Payment/PayflowPro.php b/CRM/Core/Payment/PayflowPro.php
index 0a914317ba25..1d4b92c5e96c 100644
--- a/CRM/Core/Payment/PayflowPro.php
+++ b/CRM/Core/Payment/PayflowPro.php
@@ -1,7 +1,7 @@
$user,
'VENDOR' => $this->_paymentProcessor['user_name'],
'PARTNER' => $this->_paymentProcessor['signature'],
@@ -102,7 +103,7 @@ public function doDirectPayment(&$params) {
'CVV2' => $params['cvv2'],
'EXPDATE' => urlencode(sprintf('%02d', (int) $params['month']) . substr($params['year'], 2, 2)),
'ACCTTYPE' => urlencode($params['credit_card_type']),
- 'AMT' => urlencode($params['amount']),
+ 'AMT' => urlencode($this->getAmount($params)),
'CURRENCY' => urlencode($params['currency']),
'FIRSTNAME' => $params['billing_first_name'],
//credit card name
@@ -121,7 +122,7 @@ public function doDirectPayment(&$params) {
'ORDERDESC' => urlencode($params['description']),
'VERBOSITY' => 'MEDIUM',
'BILLTOCOUNTRY' => urlencode($params['country']),
- );
+ ];
if ($params['installments'] == 1) {
$params['is_recur'] = FALSE;
@@ -131,7 +132,7 @@ public function doDirectPayment(&$params) {
$payflow_query_array['TRXTYPE'] = 'R';
$payflow_query_array['OPTIONALTRX'] = 'S';
- $payflow_query_array['OPTIONALTRXAMT'] = $params['amount'];
+ $payflow_query_array['OPTIONALTRXAMT'] = $this->getAmount($params);
//Amount of the initial Transaction. Required
$payflow_query_array['ACTION'] = 'A';
//A for add recurring (M-modify,C-cancel,R-reactivate,I-inquiry,P-payment
@@ -272,7 +273,7 @@ public function doDirectPayment(&$params) {
return self::errorExit(9016, "No RESULT code from PayPal.");
}
- $nvpArray = array();
+ $nvpArray = [];
while (strlen($result)) {
// name
$keypos = strpos($result, '=');
@@ -303,7 +304,7 @@ public function doDirectPayment(&$params) {
/*******************************************************
* Success !
- * This is a successful transaction. PayFlow Pro does return further information
+ * This is a successful transaction. Payflow Pro does return further information
* about transactions to help you identify fraud including whether they pass
* the cvv check, the avs check. This is stored in
* CiviCRM as part of the transact
@@ -344,10 +345,9 @@ public function doDirectPayment(&$params) {
return self::errorExit(9014, "Check the code - all transactions should have been headed off before they got here. Something slipped through the net");
}
- /*
- * Produces error message and returns from class
- */
/**
+ * Produces error message and returns from class
+ *
* @param null $errorCode
* @param null $errorMessage
*
@@ -364,11 +364,9 @@ public function &errorExit($errorCode = NULL, $errorMessage = NULL) {
return $e;
}
-
- /*
- * NOTE: 'doTransferCheckout' not implemented
- */
/**
+ * NOTE: 'doTransferCheckout' not implemented
+ *
* @param array $params
* @param $component
*
@@ -378,37 +376,23 @@ public function doTransferCheckout(&$params, $component) {
CRM_Core_Error::fatal(ts('This function is not implemented'));
}
- /*
+ /**
* This public function checks to see if we have the right processor config values set
*
* NOTE: Called by Events and Contribute to check config params are set prior to trying
* register any credit card details
*
- * @param string $mode
- * The mode we are operating in (live or test) - not used.
- *
- * returns string $errorMsg if any errors found - null if OK
- */
-
- // function checkConfig( $mode ) // CiviCRM V1.9 Declaration
-
- /**
- * CiviCRM V2.0 Declaration
- * This function checks to see if we have the right config values
- *
- * @internal param string $mode the mode we are operating in (live or test)
- *
- * @return string
- * the error message if any
+ * @return string|null
+ * the error message if any, null if OK
*/
public function checkConfig() {
- $errorMsg = array();
+ $errorMsg = [];
if (empty($this->_paymentProcessor['user_name'])) {
$errorMsg[] = ' ' . ts('ssl_merchant_id is not set for this payment processor');
}
if (empty($this->_paymentProcessor['url_site'])) {
- $errorMsg[] = ' ' . ts('URL is not set for %1', array(1 => $this->_paymentProcessor['name']));
+ $errorMsg[] = ' ' . ts('URL is not set for %1', [1 => $this->_paymentProcessor['name']]);
}
if (!empty($errorMsg)) {
@@ -418,12 +402,10 @@ public function checkConfig() {
return NULL;
}
}
- //end check config
- /*
- * convert to a name/value pair (nvp) string
- */
/**
+ * convert to a name/value pair (nvp) string
+ *
* @param $payflow_query_array
*
* @return array|string
@@ -437,22 +419,15 @@ public function convert_to_nvp($payflow_query_array) {
return $payflow_query;
}
- /*
- * Submit transaction using CuRL
- * @submiturl string Url to direct HTTPS GET to
- * @payflow_query value string to be posted
- */
/**
- * @param $submiturl
- * @param $payflow_query
+ * Submit transaction using cURL
+ *
+ * @param string $submiturl Url to direct HTTPS GET to
+ * @param $payflow_query value string to be posted
*
* @return mixed|object
*/
public function submit_transaction($submiturl, $payflow_query) {
- /*
- * Submit transaction using CuRL
- */
-
// get data ready for API
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// Here's your custom headers; adjust appropriately for your setup:
@@ -467,7 +442,7 @@ public function submit_transaction($submiturl, $payflow_query) {
$headers[] = "X-VPS-Timeout: 45";
//random unique number - the transaction is retried using this transaction ID
// in this function but if that doesn't work and it is re- submitted
- // it is treated as a new attempt. PayflowPro doesn't allow
+ // it is treated as a new attempt. Payflow Pro doesn't allow
// you to change details (e.g. card no) when you re-submit
// you can only try the same details
$headers[] = "X-VPS-Request-ID: " . rand(1, 1000000000);
@@ -529,7 +504,7 @@ public function submit_transaction($submiturl, $payflow_query) {
}
}
if ($responseHeaders['http_code'] != 200) {
- return self::errorExit(9015, "Error connecting to the payflo API server.");
+ return self::errorExit(9015, "Error connecting to the Payflow Pro API server.");
}
/*
@@ -591,84 +566,5 @@ public function submit_transaction($submiturl, $payflow_query) {
curl_close($ch);
return $responseData;
}
- //end submit_transaction
-
- /**
- * @param int $recurringProfileID
- * @param int $processorID
- *
- * @throws Exception
- */
- public function getRecurringTransactionStatus($recurringProfileID, $processorID) {
- if (!defined('CURLOPT_SSLCERT')) {
- CRM_Core_Error::fatal(ts('PayFlowPro requires curl with SSL support'));
- }
-
- /*
- * define variables for connecting with the gateway
- */
-
- //if you have not set up a separate user account the vendor name is used as the username
- if (!$this->_paymentProcessor['subject']) {
- $user = $this->_paymentProcessor['user_name'];
- }
- else {
- $user = $this->_paymentProcessor['subject'];
- }
- //$recurringProfileID = "RT0000000001";
- // c $trythis = $this->getRecurringTransactionStatus($recurringProfileID,17);
-
- /*
- *Create the array of variables to be sent to the processor from the $params array
- * passed into this function
- *
- */
-
- $payflow_query_array = array(
- 'USER' => $user,
- 'VENDOR' => $this->_paymentProcessor['user_name'],
- 'PARTNER' => $this->_paymentProcessor['signature'],
- 'PWD' => $this->_paymentProcessor['password'],
- // C - Direct Payment using credit card
- 'TENDER' => 'C',
- // A - Authorization, S - Sale
- 'TRXTYPE' => 'R',
- 'ACTION' => 'I',
- //A for add recurring
- //(M-modify,C-cancel,R-reactivate,
- //I-inquiry,P-payment
- 'ORIGPROFILEID' => $recurringProfileID,
- 'PAYMENTHISTORY' => 'Y',
- );
-
- $payflow_query = $this->convert_to_nvp($payflow_query_array);
- echo $payflow_query;
- $submiturl = $this->_paymentProcessor['url_site'];
- //ie. url at payment processor to submit to.
- $responseData = self::submit_transaction($submiturl, $payflow_query);
- /*
- * Payment successfully sent to gateway - process the response now
- */
-
- $result = strstr($responseData, "RESULT");
- $nvpArray = array();
- while (strlen($result)) {
- // name
- $keypos = strpos($result, '=');
- $keyval = substr($result, 0, $keypos);
- // value
- $valuepos = strpos($result, '&') ? strpos($result, '&') : strlen($result);
- $valval = substr($result, $keypos + 1, $valuepos - $keypos - 1);
- // decoding the respose
- $nvpArray[$keyval] = $valval;
- $result = substr($result, $valuepos + 1, strlen($result));
- }
- // get the result code to validate.
- $result_code = $nvpArray['RESULT'];
- print_r($responseData);
-
- //RESPMSG=Invalid Profile ID: Invalid recurring profile ID
- //RT0000000001
- }
}
diff --git a/CRM/Core/Payment/PaymentExpress.php b/CRM/Core/Payment/PaymentExpress.php
index f26ddfd571ba..28552293feed 100644
--- a/CRM/Core/Payment/PaymentExpress.php
+++ b/CRM/Core/Payment/PaymentExpress.php
@@ -1,7 +1,7 @@
_paymentProcessor['user_name'])) {
$error[] = ts('UserID is not set in the Administer » System Settings » Payment Processors');
@@ -159,7 +159,7 @@ public function doTransferCheckout(&$params, $component) {
}
- $dpsParams = array(
+ $dpsParams = [
'AmountInput' => str_replace(",", "", number_format($params['amount'], 2)),
'CurrencyInput' => $params['currencyID'],
'MerchantReference' => $merchantRef,
@@ -171,7 +171,7 @@ public function doTransferCheckout(&$params, $component) {
'TxnId' => '',
'UrlFail' => $url,
'UrlSuccess' => $url,
- );
+ ];
// Allow further manipulation of params via custom hooks
CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $dpsParams);
diff --git a/CRM/Core/Payment/PaymentExpressIPN.php b/CRM/Core/Payment/PaymentExpressIPN.php
index 079f81b1aa5a..e3e5b0d1a026 100644
--- a/CRM/Core/Payment/PaymentExpressIPN.php
+++ b/CRM/Core/Payment/PaymentExpressIPN.php
@@ -1,7 +1,7 @@
invoice_id != $input['invoice']) {
CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
echo "Failure: Invoice values dont match between database and IPN request
";
- return;
+ return FALSE;
}
// lets replace invoice-id with Payment Processor -number because thats what is common and unique
@@ -157,7 +157,7 @@ public function newOrderNotify($success, $privateData, $component, $amount, $tra
if ($contribution->total_amount != $input['amount']) {
CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
echo "Failure: Amount values dont match between database and IPN request. " . $contribution->total_amount . "/" . $input['amount'] . "
";
- return;
+ return FALSE;
}
$transaction = new CRM_Core_Transaction();
@@ -255,7 +255,7 @@ public static function getContext($privateData, $orderNo) {
}
}
- return array($isTest, $component, $duplicateTransaction);
+ return [$isTest, $component, $duplicateTransaction];
}
/**
@@ -286,11 +286,11 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
}
if ($dps_method == "pxpay") {
- $processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml(array(
+ $processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml([
'PxPayUserId' => $dps_user,
'PxPayKey' => $dps_key,
'Response' => $_GET['result'],
- ));
+ ]);
$processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml('ProcessResponse', $processResponse);
fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
@@ -308,7 +308,7 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
$info = curl_getinfo($curl);
if ($info['http_code'] < 200 || $info['http_code'] > 299) {
$log_message = "DPS error: HTTP %1 retrieving %2.";
- CRM_Core_Error::fatal(ts($log_message, array(1 => $info['http_code'], 2 => $info['url'])));
+ CRM_Core_Error::fatal(ts($log_message, [1 => $info['http_code'], 2 => $info['url']]));
}
else {
fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"), $response));
@@ -318,7 +318,7 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
$valid = CRM_Core_Payment_PaymentExpressUtils::_xmlAttribute($response, 'valid');
// CRM_Core_Payment_PaymentExpressUtils::_xmlAttribute() returns NULL if preg fails.
if (is_null($valid)) {
- CRM_Core_Error::fatal(ts("DPS error: Unable to parse XML response from DPS.", array(1 => $valid)));
+ CRM_Core_Error::fatal(ts("DPS error: Unable to parse XML response from DPS.", [1 => $valid]));
}
$success = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'Success');
$txnId = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'TxnId');
@@ -439,7 +439,7 @@ public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps
* @return array
*/
public static function stringToArray($str) {
- $vars = $labels = array();
+ $vars = $labels = [];
$labels = explode(',', $str);
foreach ($labels as $label) {
$terms = explode('=', $label);
diff --git a/CRM/Core/Payment/PaymentExpressUtils.php b/CRM/Core/Payment/PaymentExpressUtils.php
index 194f870b9b62..c4a544e29e73 100644
--- a/CRM/Core/Payment/PaymentExpressUtils.php
+++ b/CRM/Core/Payment/PaymentExpressUtils.php
@@ -1,7 +1,7 @@
assign('suppressSubmitButton', $form->_paymentObject->isSuppressSubmitButtons());
- $currency = CRM_Utils_Array::value('currency', $form->_values);
- // For event forms, currency is in a different spot
- if (empty($currency)) {
- $currency = CRM_Utils_Array::value('currency', $form->_values['event']);
- }
- $form->assign('currency', $currency);
+ CRM_Financial_Form_Payment::addCreditCardJs($form->getPaymentProcessorID());
+ $form->assign('paymentProcessorID', $form->getPaymentProcessorID());
+
+ $form->assign('currency', $form->getCurrency());
// also set cancel subscription url
if (!empty($form->_paymentProcessor['is_recur']) && !empty($form->_values['is_recur'])) {
@@ -85,12 +84,12 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
}
if (!empty($form->_values['custom_pre_id'])) {
- $profileAddressFields = array();
+ $profileAddressFields = [];
$fields = CRM_Core_BAO_UFGroup::getFields($form->_values['custom_pre_id'], FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
foreach ((array) $fields as $key => $value) {
- CRM_Core_BAO_UFField::assignAddressField($key, $profileAddressFields, array('uf_group_id' => $form->_values['custom_pre_id']));
+ CRM_Core_BAO_UFField::assignAddressField($key, $profileAddressFields, ['uf_group_id' => $form->_values['custom_pre_id']]);
}
if (count($profileAddressFields)) {
$form->set('profileAddressFields', $profileAddressFields);
@@ -133,7 +132,7 @@ public static function preProcess(&$form, $type = NULL, $mode = NULL) {
) {
CRM_Core_Error::fatal(ts('This contribution page is configured to support separate contribution and membership payments. This %1 plugin does not currently support multiple simultaneous payments, or the option to "Execute real-time monetary transactions" is disabled. Please contact the site administrator and notify them of this error',
- array(1 => $form->_paymentProcessor['payment_processor_type'])
+ [1 => $form->_paymentProcessor['payment_processor_type']]
)
);
}
diff --git a/CRM/Core/Payment/Realex.php b/CRM/Core/Payment/Realex.php
index 9af1649742ae..5a4931d214b4 100644
--- a/CRM/Core/Payment/Realex.php
+++ b/CRM/Core/Payment/Realex.php
@@ -1,7 +1,7 @@
get('verifySSL'));
@@ -204,12 +204,12 @@ public function doDirectPayment(&$params) {
// FIXME: We are using the trxn_result_code column to store all these extra details since there
// seems to be nowhere else to put them. This is THE WRONG THING TO DO!
- $extras = array(
+ $extras = [
'authcode' => $response['AUTHCODE'],
'batch_id' => $response['BATCHID'],
'message' => $response['MESSAGE'],
'trxn_result_code' => $response['RESULT'],
- );
+ ];
$params['trxn_id'] = $response['PASREF'];
$params['trxn_result_code'] = serialize($extras);
@@ -230,8 +230,8 @@ public function doDirectPayment(&$params) {
* An array of the result with following keys:
*/
public function xml_parse_into_assoc($xml) {
- $input = array();
- $result = array();
+ $input = [];
+ $result = [];
$result['#error'] = FALSE;
$result['#return'] = NULL;
@@ -250,11 +250,11 @@ public function xml_parse_into_assoc($xml) {
}
else {
$result['#error'] = ts('Error parsing XML result - error code = %1 at line %2 char %3',
- array(
+ [
1 => xml_get_error_code($xmlparser),
2 => xml_get_current_line_number($xmlparser),
3 => xml_get_current_column_number($xmlparser),
- )
+ ]
);
}
}
@@ -269,8 +269,8 @@ public function xml_parse_into_assoc($xml) {
* @return array
*/
public function _xml_parse($input, $depth = 1) {
- $output = array();
- $children = array();
+ $output = [];
+ $children = [];
foreach ($input as $data) {
if ($data['level'] == $depth) {
@@ -280,7 +280,7 @@ public function _xml_parse($input, $depth = 1) {
break;
case 'open':
- $children = array();
+ $children = [];
break;
case 'close':
@@ -475,7 +475,7 @@ public function &error($errorCode = NULL, $errorMessage = NULL) {
* the error message if any
*/
public function checkConfig() {
- $error = array();
+ $error = [];
if (empty($this->_paymentProcessor['user_name'])) {
$error[] = ts('Merchant ID is not set for this payment processor');
}
diff --git a/CRM/Core/Payment/eWAY.php b/CRM/Core/Payment/eWAY.php
index 10be2be36621..68992819af9a 100644
--- a/CRM/Core/Payment/eWAY.php
+++ b/CRM/Core/Payment/eWAY.php
@@ -1,7 +1,7 @@
_paymentProcessor['user_name'])) {
$errorMsg[] = ts('eWAY CustomerID is not set for this payment processor');
diff --git a/CRM/Core/Permission.php b/CRM/Core/Permission.php
index c934bc6098c1..d1ed8ea0559e 100644
--- a/CRM/Core/Permission.php
+++ b/CRM/Core/Permission.php
@@ -1,9 +1,9 @@
userPermissionTemp;
foreach ($permissions as $permission) {
if (is_array($permission)) {
foreach ($permission as $orPerm) {
- if (self::check($orPerm)) {
+ if (self::check($orPerm, $contactId)) {
//one of our 'or' permissions has succeeded - stop checking this permission
return TRUE;
}
@@ -135,9 +140,9 @@ public static function check($permissions) {
}
else {
// This is an individual permission
- $granted = CRM_Core_Config::singleton()->userPermissionClass->check($permission);
+ $granted = CRM_Core_Config::singleton()->userPermissionClass->check($permission, $userId);
// Call the permission_check hook to permit dynamic escalation (CRM-19256)
- CRM_Utils_Hook::permission_check($permission, $granted);
+ CRM_Utils_Hook::permission_check($permission, $granted, $contactId);
if (
!$granted
&& !($tempPerm && $tempPerm->check($permission))
@@ -249,8 +254,8 @@ public static function customGroupAdmin() {
*/
public static function customGroup($type = CRM_Core_Permission::VIEW, $reset = FALSE) {
$customGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id',
- array('fresh' => $reset));
- $defaultGroups = array();
+ ['fresh' => $reset]);
+ $defaultGroups = [];
// check if user has all powerful permission
// or administer civicrm permission (CRM-1905)
@@ -375,7 +380,7 @@ public static function event($type = CRM_Core_Permission::VIEW, $eventID = NULL,
}
}
$events = CRM_Event_PseudoConstant::event(NULL, TRUE);
- $includeEvents = array();
+ $includeEvents = [];
// check if user has all powerful permission
if (self::check('register for events')) {
@@ -472,7 +477,7 @@ public static function checkActionPermission($module, $action) {
$permissionName = "delete in $module";
}
else {
- $editPermissions = array(
+ $editPermissions = [
'CiviEvent' => 'edit event participants',
'CiviMember' => 'edit memberships',
'CiviPledge' => 'edit pledges',
@@ -480,7 +485,7 @@ public static function checkActionPermission($module, $action) {
'CiviGrant' => 'edit grants',
'CiviMail' => 'access CiviMail',
'CiviAuction' => 'add auction items',
- );
+ ];
$permissionName = CRM_Utils_Array::value($module, $editPermissions);
}
@@ -580,7 +585,7 @@ public static function checkMenuItem(&$item) {
* @return array
*/
public static function basicPermissions($all = FALSE, $descriptions = FALSE) {
- $cacheKey = implode('-', array($all, $descriptions));
+ $cacheKey = implode('-', [$all, $descriptions]);
if (empty(Civi::$statics[__CLASS__][__FUNCTION__][$cacheKey])) {
Civi::$statics[__CLASS__][__FUNCTION__][$cacheKey] = self::assembleBasicPermissions($all, $descriptions);
}
@@ -600,7 +605,7 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
$permissions = self::getCorePermissions($descriptions);
if (self::isMultisiteEnabled()) {
- $permissions['administer Multiple Organizations'] = array($prefix . ts('administer Multiple Organizations'));
+ $permissions['administer Multiple Organizations'] = [$prefix . ts('administer Multiple Organizations')];
}
if (!$descriptions) {
@@ -622,7 +627,7 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
foreach ($perm as $p => $attr) {
if (!is_array($attr)) {
- $attr = array($attr);
+ $attr = [$attr];
}
$attr[0] = $info['translatedName'] . ': ' . $attr[0];
@@ -648,11 +653,11 @@ public static function assembleBasicPermissions($all = FALSE, $descriptions = FA
* @return array
*/
public static function getAnonymousPermissionsWarnings() {
- static $permissions = array();
+ static $permissions = [];
if (empty($permissions)) {
- $permissions = array(
+ $permissions = [
'administer CiviCRM',
- );
+ ];
$components = CRM_Core_Component::getComponents();
foreach ($components as $comp) {
if (!method_exists($comp, 'getAnonymousPermissionWarnings')) {
@@ -680,212 +685,236 @@ public static function validateForPermissionWarnings($anonymous_perms) {
*/
public static function getCorePermissions() {
$prefix = ts('CiviCRM') . ': ';
- $permissions = array(
- 'add contacts' => array(
+ $permissions = [
+ 'add contacts' => [
$prefix . ts('add contacts'),
ts('Create a new contact record in CiviCRM'),
- ),
- 'view all contacts' => array(
+ ],
+ 'view all contacts' => [
$prefix . ts('view all contacts'),
ts('View ANY CONTACT in the CiviCRM database, export contact info and perform activities such as Send Email, Phone Call, etc.'),
- ),
- 'edit all contacts' => array(
+ ],
+ 'edit all contacts' => [
$prefix . ts('edit all contacts'),
ts('View, Edit and Delete ANY CONTACT in the CiviCRM database; Create and edit relationships, tags and other info about the contacts'),
- ),
- 'view my contact' => array(
+ ],
+ 'view my contact' => [
$prefix . ts('view my contact'),
- ),
- 'edit my contact' => array(
+ ],
+ 'edit my contact' => [
$prefix . ts('edit my contact'),
- ),
- 'delete contacts' => array(
+ ],
+ 'delete contacts' => [
$prefix . ts('delete contacts'),
- ),
- 'access deleted contacts' => array(
+ ],
+ 'access deleted contacts' => [
$prefix . ts('access deleted contacts'),
ts('Access contacts in the trash'),
- ),
- 'import contacts' => array(
+ ],
+ 'import contacts' => [
$prefix . ts('import contacts'),
ts('Import contacts and activities'),
- ),
- 'import SQL datasource' => array(
+ ],
+ 'import SQL datasource' => [
$prefix . ts('import SQL datasource'),
ts('When importing, consume data directly from a SQL datasource'),
- ),
- 'edit groups' => array(
+ ],
+ 'edit groups' => [
$prefix . ts('edit groups'),
ts('Create new groups, edit group settings (e.g. group name, visibility...), delete groups'),
- ),
- 'administer CiviCRM' => array(
+ ],
+ 'administer CiviCRM' => [
$prefix . ts('administer CiviCRM'),
ts('Perform all tasks in the Administer CiviCRM control panel and Import Contacts'),
- ),
- 'skip IDS check' => array(
+ ],
+ 'skip IDS check' => [
$prefix . ts('skip IDS check'),
- ts('IDS system is bypassed for users with this permission. Prevents false errors for admin users.'),
- ),
- 'access uploaded files' => array(
+ ts('Warning: Give to trusted roles only; this permission has security implications. IDS system is bypassed for users with this permission. Prevents false errors for admin users.'),
+ ],
+ 'access uploaded files' => [
$prefix . ts('access uploaded files'),
ts('View / download files including images and photos'),
- ),
- 'profile listings and forms' => array(
+ ],
+ 'profile listings and forms' => [
$prefix . ts('profile listings and forms'),
- ts('Access the profile Search form and listings'),
- ),
- 'profile listings' => array(
+ ts('Warning: Give to trusted roles only; this permission has privacy implications. Add/edit data in online forms and access public searchable directories.'),
+ ],
+ 'profile listings' => [
$prefix . ts('profile listings'),
- ),
- 'profile create' => array(
+ ts('Warning: Give to trusted roles only; this permission has privacy implications. Access public searchable directories.'),
+ ],
+ 'profile create' => [
$prefix . ts('profile create'),
- ts('Use profiles in Create mode'),
- ),
- 'profile edit' => array(
+ ts('Add data in a profile form.'),
+ ],
+ 'profile edit' => [
$prefix . ts('profile edit'),
- ts('Use profiles in Edit mode'),
- ),
- 'profile view' => array(
+ ts('Edit data in a profile form.'),
+ ],
+ 'profile view' => [
$prefix . ts('profile view'),
- ),
- 'access all custom data' => array(
+ ts('View data in a profile.'),
+ ],
+ 'access all custom data' => [
$prefix . ts('access all custom data'),
ts('View all custom fields regardless of ACL rules'),
- ),
- 'view all activities' => array(
+ ],
+ 'view all activities' => [
$prefix . ts('view all activities'),
ts('View all activities (for visible contacts)'),
- ),
- 'delete activities' => array(
+ ],
+ 'delete activities' => [
$prefix . ts('Delete activities'),
- ),
- 'access CiviCRM' => array(
- $prefix . ts('access CiviCRM'),
- ts('Master control for access to the main CiviCRM backend and API'),
- ),
- 'access Contact Dashboard' => array(
+ ],
+ 'edit inbound email basic information' => [
+ $prefix . ts('edit inbound email basic information'),
+ ts('Edit all inbound email activities (for visible contacts) basic information. Content editing not allowed.'),
+ ],
+ 'edit inbound email basic information and content' => [
+ $prefix . ts('edit inbound email basic information and content'),
+ ts('Edit all inbound email activities (for visible contacts) basic information and content.'),
+ ],
+ 'access CiviCRM' => [
+ $prefix . ts('access CiviCRM backend and API'),
+ ts('Master control for access to the main CiviCRM backend and API. Give to trusted roles only.'),
+ ],
+ 'access Contact Dashboard' => [
$prefix . ts('access Contact Dashboard'),
ts('View Contact Dashboard (for themselves and visible contacts)'),
- ),
- 'translate CiviCRM' => array(
+ ],
+ 'translate CiviCRM' => [
$prefix . ts('translate CiviCRM'),
ts('Allow User to enable multilingual'),
- ),
- 'manage tags' => array(
+ ],
+ 'manage tags' => [
$prefix . ts('manage tags'),
ts('Create and rename tags'),
- ),
- 'administer reserved groups' => array(
+ ],
+ 'administer reserved groups' => [
$prefix . ts('administer reserved groups'),
ts('Edit and disable Reserved Groups (Needs Edit Groups)'),
- ),
- 'administer Tagsets' => array(
+ ],
+ 'administer Tagsets' => [
$prefix . ts('administer Tagsets'),
- ),
- 'administer reserved tags' => array(
+ ],
+ 'administer reserved tags' => [
$prefix . ts('administer reserved tags'),
- ),
- 'administer dedupe rules' => array(
+ ],
+ 'administer dedupe rules' => [
$prefix . ts('administer dedupe rules'),
ts('Create and edit rules, change the supervised and unsupervised rules'),
- ),
- 'merge duplicate contacts' => array(
+ ],
+ 'merge duplicate contacts' => [
$prefix . ts('merge duplicate contacts'),
ts('Delete Contacts must also be granted in order for this to work.'),
- ),
- 'force merge duplicate contacts' => array(
+ ],
+ 'force merge duplicate contacts' => [
$prefix . ts('force merge duplicate contacts'),
ts('Delete Contacts must also be granted in order for this to work.'),
- ),
- 'view debug output' => array(
+ ],
+ 'view debug output' => [
$prefix . ts('view debug output'),
ts('View results of debug and backtrace'),
- ),
+ ],
- 'view all notes' => array(
+ 'view all notes' => [
$prefix . ts('view all notes'),
ts("View notes (for visible contacts) even if they're marked admin only"),
- ),
- 'access AJAX API' => array(
+ ],
+ 'add contact notes' => [
+ $prefix . ts('add contact notes'),
+ ts("Create notes for contacts"),
+ ],
+ 'access AJAX API' => [
$prefix . ts('access AJAX API'),
ts('Allow API access even if Access CiviCRM is not granted'),
- ),
- 'access contact reference fields' => array(
+ ],
+ 'access contact reference fields' => [
$prefix . ts('access contact reference fields'),
ts('Allow entering data into contact reference fields'),
- ),
- 'create manual batch' => array(
+ ],
+ 'create manual batch' => [
$prefix . ts('create manual batch'),
ts('Create an accounting batch (with Access to CiviContribute and View Own/All Manual Batches)'),
- ),
- 'edit own manual batches' => array(
+ ],
+ 'edit own manual batches' => [
$prefix . ts('edit own manual batches'),
ts('Edit accounting batches created by user'),
- ),
- 'edit all manual batches' => array(
+ ],
+ 'edit all manual batches' => [
$prefix . ts('edit all manual batches'),
ts('Edit all accounting batches'),
- ),
- 'close own manual batches' => array(
+ ],
+ 'close own manual batches' => [
$prefix . ts('close own manual batches'),
ts('Close accounting batches created by user (with Access to CiviContribute)'),
- ),
- 'close all manual batches' => array(
+ ],
+ 'close all manual batches' => [
$prefix . ts('close all manual batches'),
ts('Close all accounting batches (with Access to CiviContribute)'),
- ),
- 'reopen own manual batches' => array(
+ ],
+ 'reopen own manual batches' => [
$prefix . ts('reopen own manual batches'),
ts('Reopen accounting batches created by user (with Access to CiviContribute)'),
- ),
- 'reopen all manual batches' => array(
+ ],
+ 'reopen all manual batches' => [
$prefix . ts('reopen all manual batches'),
ts('Reopen all accounting batches (with Access to CiviContribute)'),
- ),
- 'view own manual batches' => array(
+ ],
+ 'view own manual batches' => [
$prefix . ts('view own manual batches'),
ts('View accounting batches created by user (with Access to CiviContribute)'),
- ),
- 'view all manual batches' => array(
+ ],
+ 'view all manual batches' => [
$prefix . ts('view all manual batches'),
ts('View all accounting batches (with Access to CiviContribute)'),
- ),
- 'delete own manual batches' => array(
+ ],
+ 'delete own manual batches' => [
$prefix . ts('delete own manual batches'),
ts('Delete accounting batches created by user'),
- ),
- 'delete all manual batches' => array(
+ ],
+ 'delete all manual batches' => [
$prefix . ts('delete all manual batches'),
ts('Delete all accounting batches'),
- ),
- 'export own manual batches' => array(
+ ],
+ 'export own manual batches' => [
$prefix . ts('export own manual batches'),
ts('Export accounting batches created by user'),
- ),
- 'export all manual batches' => array(
+ ],
+ 'export all manual batches' => [
$prefix . ts('export all manual batches'),
ts('Export all accounting batches'),
- ),
- 'administer payment processors' => array(
+ ],
+ 'administer payment processors' => [
$prefix . ts('administer payment processors'),
ts('Add, Update, or Disable Payment Processors'),
- ),
- 'edit message templates' => array(
+ ],
+ 'edit message templates' => [
$prefix . ts('edit message templates'),
- ),
- 'view my invoices' => array(
+ ],
+ 'edit system workflow message templates' => [
+ $prefix . ts('edit system workflow message templates'),
+ ],
+ 'edit user-driven message templates' => [
+ $prefix . ts('edit user-driven message templates'),
+ ],
+ 'view my invoices' => [
$prefix . ts('view my invoices'),
ts('Allow users to view/ download their own invoices'),
- ),
- 'edit api keys' => array(
+ ],
+ 'edit api keys' => [
$prefix . ts('edit api keys'),
ts('Edit API keys'),
- ),
- 'edit own api keys' => array(
+ ],
+ 'edit own api keys' => [
$prefix . ts('edit own api keys'),
ts('Edit user\'s own API keys'),
- ),
- );
+ ],
+ 'send SMS' => [
+ $prefix . ts('send SMS'),
+ ts('Send an SMS'),
+ ],
+ ];
return $permissions;
}
@@ -909,59 +938,62 @@ public static function getCorePermissions() {
* @return array of permissions
*/
public static function getEntityActionPermissions() {
- $permissions = array();
+ $permissions = [];
// These are the default permissions - if any entity does not declare permissions for a given action,
// (or the entity does not declare permissions at all) - then the action will be used from here
- $permissions['default'] = array(
+ $permissions['default'] = [
// applies to getfields, getoptions, etc.
- 'meta' => array('access CiviCRM'),
+ 'meta' => ['access CiviCRM'],
// catch-all, applies to create, get, delete, etc.
// If an entity declares it's own 'default' action it will override this one
- 'default' => array('administer CiviCRM'),
- );
+ 'default' => ['administer CiviCRM'],
+ ];
// Note: Additional permissions in DynamicFKAuthorization
- $permissions['attachment'] = array(
- 'default' => array(
- array('access CiviCRM', 'access AJAX API'),
- ),
- );
+ $permissions['attachment'] = [
+ 'default' => [
+ ['access CiviCRM', 'access AJAX API'],
+ ],
+ ];
// Contact permissions
- $permissions['contact'] = array(
- 'create' => array(
+ $permissions['contact'] = [
+ 'create' => [
'access CiviCRM',
'add contacts',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'delete contacts',
- ),
+ ],
// managed by query object
- 'get' => array(),
+ 'get' => [],
// managed by _civicrm_api3_check_edit_permissions
- 'update' => array(),
- 'getquick' => array(
- array('access CiviCRM', 'access AJAX API'),
- ),
- );
+ 'update' => [],
+ 'getquick' => [
+ ['access CiviCRM', 'access AJAX API'],
+ ],
+ 'duplicatecheck' => [
+ 'access CiviCRM',
+ ],
+ ];
// CRM-16963 - Permissions for country.
- $permissions['country'] = array(
- 'get' => array(
+ $permissions['country'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'administer CiviCRM',
- ),
- );
+ ],
+ ];
// Contact-related data permissions.
- $permissions['address'] = array(
+ $permissions['address'] = [
// get is managed by BAO::addSelectWhereClause
// create/delete are managed by _civicrm_api3_check_edit_permissions
- 'default' => array(),
- );
+ 'default' => [],
+ ];
$permissions['email'] = $permissions['address'];
$permissions['phone'] = $permissions['address'];
$permissions['website'] = $permissions['address'];
@@ -969,491 +1001,500 @@ public static function getEntityActionPermissions() {
$permissions['open_i_d'] = $permissions['address'];
// Also managed by ACLs - CRM-19448
- $permissions['entity_tag'] = array('default' => array());
+ $permissions['entity_tag'] = ['default' => []];
$permissions['note'] = $permissions['entity_tag'];
// Allow non-admins to get and create tags to support tagset widget
// Delete is still reserved for admins
- $permissions['tag'] = array(
- 'get' => array('access CiviCRM'),
- 'create' => array('access CiviCRM'),
- 'update' => array('access CiviCRM'),
- );
+ $permissions['tag'] = [
+ 'get' => ['access CiviCRM'],
+ 'create' => ['access CiviCRM'],
+ 'update' => ['access CiviCRM'],
+ ];
//relationship permissions
- $permissions['relationship'] = array(
+ $permissions['relationship'] = [
// get is managed by BAO::addSelectWhereClause
- 'get' => array(),
- 'delete' => array(
+ 'get' => [],
+ 'delete' => [
'access CiviCRM',
'edit all contacts',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'edit all contacts',
- ),
- );
+ ],
+ ];
// CRM-17741 - Permissions for RelationshipType.
- $permissions['relationship_type'] = array(
- 'get' => array(
+ $permissions['relationship_type'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'administer CiviCRM',
- ),
- );
+ ],
+ ];
// Activity permissions
- $permissions['activity'] = array(
- 'delete' => array(
+ $permissions['activity'] = [
+ 'delete' => [
'access CiviCRM',
'delete activities',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
// Note that view all activities is also required within the api
// if the id is not passed in. Where the id is passed in the activity
// specific check functions are used and tested.
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'view all activities',
- ),
- );
+ ],
+ ];
+ $permissions['activity_contact'] = $permissions['activity'];
// Case permissions
- $permissions['case'] = array(
- 'create' => array(
+ $permissions['case'] = [
+ 'create' => [
'access CiviCRM',
'add cases',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'delete in CiviCase',
- ),
- 'restore' => array(
+ ],
+ 'restore' => [
'administer CiviCase',
- ),
- 'merge' => array(
+ ],
+ 'merge' => [
'administer CiviCase',
- ),
- 'default' => array(
+ ],
+ 'default' => [
// At minimum the user needs one of the following. Finer-grained access is controlled by CRM_Case_BAO_Case::addSelectWhereClause
- array('access my cases and activities', 'access all cases and activities'),
- ),
- );
+ ['access my cases and activities', 'access all cases and activities'],
+ ],
+ ];
$permissions['case_contact'] = $permissions['case'];
- $permissions['case_type'] = array(
- 'default' => array('administer CiviCase'),
- 'get' => array(
+ $permissions['case_type'] = [
+ 'default' => ['administer CiviCase'],
+ 'get' => [
// nested array = OR
- array('access my cases and activities', 'access all cases and activities'),
- ),
- );
+ ['access my cases and activities', 'access all cases and activities'],
+ ],
+ ];
// Campaign permissions
- $permissions['campaign'] = array(
- 'get' => array('access CiviCRM'),
- 'default' => array(
+ $permissions['campaign'] = [
+ 'get' => ['access CiviCRM'],
+ 'default' => [
// nested array = OR
- array('administer CiviCampaign', 'manage campaign'),
- ),
- );
+ ['administer CiviCampaign', 'manage campaign'],
+ ],
+ ];
$permissions['survey'] = $permissions['campaign'];
// Financial permissions
- $permissions['contribution'] = array(
- 'get' => array(
+ $permissions['contribution'] = [
+ 'get' => [
'access CiviCRM',
'access CiviContribute',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'completetransaction' => array(
+ ],
+ 'completetransaction' => [
'edit contributions',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
$permissions['line_item'] = $permissions['contribution'];
// Payment permissions
- $permissions['payment'] = array(
- 'get' => array(
+ $permissions['payment'] = [
+ 'get' => [
'access CiviCRM',
'access CiviContribute',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'cancel' => array(
+ ],
+ 'cancel' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- 'create' => array(
+ ],
+ 'create' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
$permissions['contribution_recur'] = $permissions['payment'];
// Custom field permissions
- $permissions['custom_field'] = array(
- 'default' => array(
+ $permissions['custom_field'] = [
+ 'default' => [
'administer CiviCRM',
'access all custom data',
- ),
- );
+ ],
+ ];
$permissions['custom_group'] = $permissions['custom_field'];
// Event permissions
- $permissions['event'] = array(
- 'create' => array(
+ $permissions['event'] = [
+ 'create' => [
'access CiviCRM',
'access CiviEvent',
'edit all events',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviEvent',
'delete in CiviEvent',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviEvent',
'view event info',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviEvent',
'edit all events',
- ),
- );
+ ],
+ ];
// Loc block is only used for events
$permissions['loc_block'] = $permissions['event'];
- $permissions['state_province'] = array(
- 'get' => array(
+ $permissions['state_province'] = [
+ 'get' => [
'access CiviCRM',
- ),
- );
+ ],
+ ];
// Price sets are shared by several components, user needs access to at least one of them
- $permissions['price_set'] = array(
- 'default' => array(
- array('access CiviEvent', 'access CiviContribute', 'access CiviMember'),
- ),
- 'get' => array(
- array('access CiviCRM', 'view event info', 'make online contributions'),
- ),
- );
+ $permissions['price_set'] = [
+ 'default' => [
+ ['access CiviEvent', 'access CiviContribute', 'access CiviMember'],
+ ],
+ 'get' => [
+ ['access CiviCRM', 'view event info', 'make online contributions'],
+ ],
+ ];
// File permissions
- $permissions['file'] = array(
- 'default' => array(
+ $permissions['file'] = [
+ 'default' => [
'access CiviCRM',
'access uploaded files',
- ),
- );
+ ],
+ ];
$permissions['files_by_entity'] = $permissions['file'];
// Group permissions
- $permissions['group'] = array(
- 'get' => array(
+ $permissions['group'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'edit groups',
- ),
- );
+ ],
+ ];
$permissions['group_nesting'] = $permissions['group'];
$permissions['group_organization'] = $permissions['group'];
//Group Contact permission
- $permissions['group_contact'] = array(
- 'get' => array(
+ $permissions['group_contact'] = [
+ 'get' => [
'access CiviCRM',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'edit all contacts',
- ),
- );
+ ],
+ ];
// CiviMail Permissions
- $civiMailBasePerms = array(
+ $civiMailBasePerms = [
// To get/preview/update, one must have least one of these perms:
// Mailing API implementations enforce nuances of create/approve/schedule permissions.
'access CiviMail',
'create mailings',
'schedule mailings',
'approve mailings',
- );
- $permissions['mailing'] = array(
- 'get' => array(
+ ];
+ $permissions['mailing'] = [
+ 'get' => [
'access CiviCRM',
$civiMailBasePerms,
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
$civiMailBasePerms,
'delete in CiviMail',
- ),
- 'submit' => array(
+ ],
+ 'submit' => [
'access CiviCRM',
- array('access CiviMail', 'schedule mailings'),
- ),
- 'default' => array(
+ ['access CiviMail', 'schedule mailings'],
+ ],
+ 'default' => [
'access CiviCRM',
$civiMailBasePerms,
- ),
- );
+ ],
+ ];
$permissions['mailing_group'] = $permissions['mailing'];
$permissions['mailing_job'] = $permissions['mailing'];
$permissions['mailing_recipients'] = $permissions['mailing'];
- $permissions['mailing_a_b'] = array(
- 'get' => array(
+ $permissions['mailing_a_b'] = [
+ 'get' => [
'access CiviCRM',
'access CiviMail',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviMail',
'delete in CiviMail',
- ),
- 'submit' => array(
+ ],
+ 'submit' => [
'access CiviCRM',
- array('access CiviMail', 'schedule mailings'),
- ),
- 'default' => array(
+ ['access CiviMail', 'schedule mailings'],
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviMail',
- ),
- );
+ ],
+ ];
// Membership permissions
- $permissions['membership'] = array(
- 'get' => array(
+ $permissions['membership'] = [
+ 'get' => [
'access CiviCRM',
'access CiviMember',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviMember',
'delete in CiviMember',
- ),
- 'default' => array(
+ ],
+ 'default' => [
'access CiviCRM',
'access CiviMember',
'edit memberships',
- ),
- );
+ ],
+ ];
$permissions['membership_status'] = $permissions['membership'];
$permissions['membership_type'] = $permissions['membership'];
- $permissions['membership_payment'] = array(
- 'create' => array(
+ $permissions['membership_payment'] = [
+ 'create' => [
'access CiviCRM',
'access CiviMember',
'edit memberships',
'access CiviContribute',
'edit contributions',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviMember',
'delete in CiviMember',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviMember',
'access CiviContribute',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviMember',
'edit memberships',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
// Participant permissions
- $permissions['participant'] = array(
- 'create' => array(
+ $permissions['participant'] = [
+ 'create' => [
'access CiviCRM',
'access CiviEvent',
'register for events',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviEvent',
'view event participants',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
- ),
- );
- $permissions['participant_payment'] = array(
- 'create' => array(
+ ],
+ ];
+ $permissions['participant_payment'] = [
+ 'create' => [
'access CiviCRM',
'access CiviEvent',
'register for events',
'access CiviContribute',
'edit contributions',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviEvent',
'view event participants',
'access CiviContribute',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviEvent',
'edit event participants',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
// Pledge permissions
- $permissions['pledge'] = array(
- 'create' => array(
+ $permissions['pledge'] = [
+ 'create' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviPledge',
'delete in CiviPledge',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviPledge',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
- ),
- );
+ ],
+ ];
//CRM-16777: Disable schedule reminder for user that have 'edit all events' and 'administer CiviCRM' permission.
- $permissions['action_schedule'] = array(
- 'update' => array(
- array(
+ $permissions['action_schedule'] = [
+ 'update' => [
+ [
'access CiviCRM',
'edit all events',
- ),
- ),
- );
+ ],
+ ],
+ ];
- $permissions['pledge_payment'] = array(
- 'create' => array(
+ $permissions['pledge_payment'] = [
+ 'create' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
'access CiviContribute',
'edit contributions',
- ),
- 'delete' => array(
+ ],
+ 'delete' => [
'access CiviCRM',
'access CiviPledge',
'delete in CiviPledge',
'access CiviContribute',
'delete in CiviContribute',
- ),
- 'get' => array(
+ ],
+ 'get' => [
'access CiviCRM',
'access CiviPledge',
'access CiviContribute',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
'access CiviPledge',
'edit pledges',
'access CiviContribute',
'edit contributions',
- ),
- );
+ ],
+ ];
// Profile permissions
- $permissions['profile'] = array(
- 'get' => array(), // the profile will take care of this
- );
+ $permissions['profile'] = [
+ // the profile will take care of this
+ 'get' => [],
+ ];
- $permissions['uf_group'] = array(
- 'create' => array(
+ $permissions['uf_group'] = [
+ 'create' => [
'access CiviCRM',
- array(
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- ),
- 'get' => array(
+ ],
+ ],
+ 'get' => [
'access CiviCRM',
- ),
- 'update' => array(
+ ],
+ 'update' => [
'access CiviCRM',
- array(
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- ),
- );
+ ],
+ ],
+ ];
$permissions['uf_field'] = $permissions['uf_join'] = $permissions['uf_group'];
- $permissions['uf_field']['delete'] = array(
+ $permissions['uf_field']['delete'] = [
'access CiviCRM',
- array(
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- );
+ ],
+ ];
$permissions['option_value'] = $permissions['uf_group'];
$permissions['option_group'] = $permissions['option_value'];
- $permissions['message_template'] = array(
- 'get' => array('access CiviCRM'),
- 'create' => array('edit message templates'),
- 'update' => array('edit message templates'),
- );
+ $permissions['custom_value'] = [
+ 'gettree' => ['access CiviCRM'],
+ ];
+
+ $permissions['message_template'] = [
+ 'get' => ['access CiviCRM'],
+ 'create' => [['edit message templates', 'edit user-driven message templates', 'edit system workflow message templates']],
+ 'update' => [['edit message templates', 'edit user-driven message templates', 'edit system workflow message templates']],
+ ];
+
+ $permissions['report_template']['update'] = 'save Report Criteria';
+ $permissions['report_template']['create'] = 'save Report Criteria';
return $permissions;
}
@@ -1504,17 +1545,17 @@ public static function giveMeAllACLs() {
//check for acl.
$aclPermission = self::getPermission();
- if (in_array($aclPermission, array(
+ if (in_array($aclPermission, [
CRM_Core_Permission::EDIT,
CRM_Core_Permission::VIEW,
- ))
+ ])
) {
return TRUE;
}
// run acl where hook and see if the user is supplying an ACL clause
// that is not false
- $tables = $whereTables = array();
+ $tables = $whereTables = [];
$where = NULL;
CRM_Utils_Hook::aclWhereClause(CRM_Core_Permission::VIEW,
@@ -1539,7 +1580,7 @@ public static function getComponentName($permission) {
return $componentName;
}
- static $allCompPermissions = array();
+ static $allCompPermissions = [];
if (empty($allCompPermissions)) {
$components = CRM_Core_Component::getComponents();
foreach ($components as $name => $comp) {
@@ -1603,8 +1644,7 @@ public static function isMultisiteEnabled() {
* invoices permission and the invoice author is the current user.
*/
public static function checkDownloadInvoice() {
- global $user;
- $cid = CRM_Core_BAO_UFMatch::getContactId($user->uid);
+ $cid = CRM_Core_Session::getLoggedInContactID();
if (CRM_Core_Permission::check('access CiviContribute') ||
(CRM_Core_Permission::check('view my invoices') && $_GET['cid'] == $cid)
) {
diff --git a/CRM/Core/Permission/Backdrop.php b/CRM/Core/Permission/Backdrop.php
index 2c1f7e399967..e2277df2f173 100644
--- a/CRM/Core/Permission/Backdrop.php
+++ b/CRM/Core/Permission/Backdrop.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal', [
'view user account' => 'access user profiles',
'administer users' => 'administer users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -85,7 +84,11 @@ public function check($str, $contactID = NULL) {
return TRUE;
}
if (function_exists('user_access')) {
- return user_access($str) ? TRUE : FALSE;
+ $account = NULL;
+ if ($userId) {
+ $account = user_load($userId);
+ }
+ return user_access($str, $account);
}
return TRUE;
}
@@ -145,7 +148,7 @@ public function upgradePermissions($permissions) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
@@ -153,27 +156,27 @@ public function permissionEmails($permissionName) {
// FIXME!!!!
/**
- $uids = array();
- $sql = "
- SELECT {users}.uid, {role_permission}.permission
- FROM {users}
- JOIN {users_roles}
- ON {users}.uid = {users_roles}.uid
- JOIN {role_permission}
- ON {role_permission}.rid = {users_roles}.rid
- WHERE {role_permission}.permission = '{$permissionName}'
- AND {users}.status = 1
- ";
-
- $result = db_query($sql);
- foreach ($result as $record) {
- $uids[] = $record->uid;
- }
-
- $_cache[$permissionName] = self::getContactEmails($uids);
- return $_cache[$permissionName];
+ * $uids = array();
+ * $sql = "
+ * SELECT {users}.uid, {role_permission}.permission
+ * FROM {users}
+ * JOIN {users_roles}
+ * ON {users}.uid = {users_roles}.uid
+ * JOIN {role_permission}
+ * ON {role_permission}.rid = {users_roles}.rid
+ * WHERE {role_permission}.permission = '{$permissionName}'
+ * AND {users}.status = 1
+ * ";
+ *
+ * $result = db_query($sql);
+ * foreach ($result as $record) {
+ * $uids[] = $record->uid;
+ * }
+ *
+ * $_cache[$permissionName] = self::getContactEmails($uids);
+ * return $_cache[$permissionName];
*/
- return array();
+ return [];
}
}
diff --git a/CRM/Core/Permission/Base.php b/CRM/Core/Permission/Base.php
index 5a56ef143530..d598e15cb3b0 100644
--- a/CRM/Core/Permission/Base.php
+++ b/CRM/Core/Permission/Base.php
@@ -1,9 +1,9 @@
$label) {
- $permissions[$permission] = (is_array($label)) ? $label : array($label);
+ $permissions[$permission] = (is_array($label)) ? $label : [$label];
}
}
else {
diff --git a/CRM/Core/Permission/Drupal.php b/CRM/Core/Permission/Drupal.php
index d83d795af5e9..9c0bbdee78c9 100644
--- a/CRM/Core/Permission/Drupal.php
+++ b/CRM/Core/Permission/Drupal.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal', [
'view user account' => 'access user profiles',
'administer users' => 'administer users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -85,7 +84,11 @@ public function check($str, $contactID = NULL) {
return TRUE;
}
if (function_exists('user_access')) {
- return user_access($str) ? TRUE : FALSE;
+ $account = NULL;
+ if ($userId) {
+ $account = user_load($userId);
+ }
+ return user_access($str, $account);
}
return TRUE;
}
@@ -142,13 +145,13 @@ public function upgradePermissions($permissions) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid, {role_permission}.permission
FROM {users}
diff --git a/CRM/Core/Permission/Drupal6.php b/CRM/Core/Permission/Drupal6.php
index 131663af091e..d969ed42373f 100644
--- a/CRM/Core/Permission/Drupal6.php
+++ b/CRM/Core/Permission/Drupal6.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal6', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal6', [
'view user account' => 'access user profiles',
'administer users' => 'administer users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -84,7 +84,11 @@ public function check($str, $contactID = NULL) {
return TRUE;
}
if (function_exists('user_access')) {
- return user_access($str) ? TRUE : FALSE;
+ $account = NULL;
+ if ($userId) {
+ $account = user_load($userId);
+ }
+ return user_access($str, $account);
}
return TRUE;
}
@@ -100,7 +104,7 @@ public function check($str, $contactID = NULL) {
*/
public function checkGroupRole($array) {
if (function_exists('user_load') && isset($array)) {
- $user = user_load(array('uid' => $GLOBALS['user']->uid));
+ $user = user_load(['uid' => $GLOBALS['user']->uid]);
//if giver roles found in user roles - return true
foreach ($array as $key => $value) {
if (in_array($value, $user->roles)) {
@@ -121,13 +125,13 @@ public function checkGroupRole($array) {
* a comma separated list of email addresses
*/
public function roleEmails($roleName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$roleName])) {
return $_cache[$roleName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid
FROM {users}
@@ -156,13 +160,13 @@ public function roleEmails($roleName) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid, {permission}.perm
FROM {users}
@@ -207,7 +211,7 @@ public function upgradePermissions($permissions) {
* Array of permissions, in the same format as CRM_Core_Permission::getCorePermissions().
*/
public static function getModulePermissions($module) {
- $return_permissions = array();
+ $return_permissions = [];
$fn_name = "{$module}_civicrm_permission";
if (function_exists($fn_name)) {
$fn_name($return_permissions);
diff --git a/CRM/Core/Permission/Drupal8.php b/CRM/Core/Permission/Drupal8.php
index 34fb06212f6a..dc2e4df2154e 100644
--- a/CRM/Core/Permission/Drupal8.php
+++ b/CRM/Core/Permission/Drupal8.php
@@ -1,9 +1,9 @@
translatePermission($str, 'Drupal', array(
+ public function check($str, $userId = NULL) {
+ $str = $this->translatePermission($str, 'Drupal', [
'view user account' => 'access user profiles',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
@@ -58,7 +59,8 @@ public function check($str, $contactID = NULL) {
if ($str == CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION) {
return TRUE;
}
- return \Drupal::currentUser()->hasPermission($str);
+ $acct = $userId ? \Drupal\user\Entity\User::load($userId) : \Drupal::currentUser();
+ return $acct->hasPermission($str);
}
/**
@@ -71,7 +73,7 @@ public function check($str, $contactID = NULL) {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
@@ -82,7 +84,7 @@ function (\Drupal\user\RoleInterface $role) {
return $role->id();
}, user_roles(TRUE, $permissionName)
);
- $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(array('roles' => $role_ids));
+ $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['roles' => $role_ids]);
$uids = array_keys($users);
$_cache[$permissionName] = self::getContactEmails($uids);
diff --git a/CRM/Core/Permission/DrupalBase.php b/CRM/Core/Permission/DrupalBase.php
index bfcfe96848c5..b691211be25a 100644
--- a/CRM/Core/Permission/DrupalBase.php
+++ b/CRM/Core/Permission/DrupalBase.php
@@ -1,9 +1,9 @@
_viewPermissionedGroups)) {
- $this->_viewPermissionedGroups = $this->_editPermissionedGroups = array();
+ $this->_viewPermissionedGroups = $this->_editPermissionedGroups = [];
}
$groupKey = $groupType ? $groupType : 'all';
if (!isset($this->_viewPermissionedGroups[$groupKey])) {
- $this->_viewPermissionedGroups[$groupKey] = $this->_editPermissionedGroups[$groupKey] = array();
+ $this->_viewPermissionedGroups[$groupKey] = $this->_editPermissionedGroups[$groupKey] = [];
$groups = CRM_Core_PseudoConstant::allGroup($groupType, $excludeHidden);
@@ -162,7 +162,7 @@ public function groupClause($type, &$tables, &$whereTables) {
$clause = ' ( 0 ) ';
}
else {
- $clauses = array();
+ $clauses = [];
$groups = implode(', ', $this->_editPermissionedGroups[$groupKey]);
$clauses[] = ' ( civicrm_group_contact.group_id IN ( ' . implode(', ', array_keys($this->_editPermissionedGroups[$groupKey])) . " ) AND civicrm_group_contact.status = 'Added' ) ";
$tables['civicrm_group_contact'] = 1;
@@ -193,7 +193,7 @@ public function groupClause($type, &$tables, &$whereTables) {
$clause = ' ( 0 ) ';
}
else {
- $clauses = array();
+ $clauses = [];
$groups = implode(', ', $this->_viewPermissionedGroups[$groupKey]);
$clauses[] = ' civicrm_group.id IN (' . implode(', ', array_keys($this->_viewPermissionedGroups[$groupKey])) . " ) ";
$tables['civicrm_group'] = 1;
@@ -245,7 +245,7 @@ public function getContactEmails($uids) {
$dao = CRM_Core_DAO::executeQuery($sql);
- $emails = array();
+ $emails = [];
while ($dao->fetch()) {
$emails[] = $dao->email;
}
@@ -292,13 +292,13 @@ public function isModulePermissionSupported() {
* a comma separated list of email addresses
*/
public function permissionEmails($permissionName) {
- static $_cache = array();
+ static $_cache = [];
if (isset($_cache[$permissionName])) {
return $_cache[$permissionName];
}
- $uids = array();
+ $uids = [];
$sql = "
SELECT {users}.uid, {role_permission}.permission
FROM {users}
diff --git a/CRM/Core/Permission/Joomla.php b/CRM/Core/Permission/Joomla.php
index 090d30ab36e3..97c7a054c282 100644
--- a/CRM/Core/Permission/Joomla.php
+++ b/CRM/Core/Permission/Joomla.php
@@ -1,9 +1,9 @@
translateJoomlaPermission($str);
if ($translated === CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
@@ -61,7 +67,7 @@ public function check($str) {
// we've not yet figured out how to bootstrap joomla, so we should
// not execute hooks if joomla is not loaded
if (defined('_JEXEC')) {
- $user = JFactory::getUser();
+ $user = JFactory::getUser($userId);
$api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
// If we are coming from REST we don't have a user but we do have the api_key for a user.
@@ -69,7 +75,7 @@ public function check($str) {
// This is a codeblock copied from /Civicrm/Utils/REST
$uid = NULL;
if (!$uid) {
- $store = NULL;
+ $store = NULL;
$contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
@@ -115,7 +121,7 @@ public function translateJoomlaPermission($perm) {
return CRM_Core_Permission::ALWAYS_DENY_PERMISSION;
case NULL:
- return array('civicrm.' . CRM_Utils_String::munge(strtolower($name)), 'com_civicrm');
+ return ['civicrm.' . CRM_Utils_String::munge(strtolower($name)), 'com_civicrm'];
default:
return CRM_Core_Permission::ALWAYS_DENY_PERMISSION;
@@ -139,7 +145,7 @@ public function checkGroupRole($array) {
* @inheritDoc
*/
public function upgradePermissions($permissions) {
- $translatedPerms = array();
+ $translatedPerms = [];
// Flipping the $permissions array gives us just the raw names of the
// permissions. The descriptions, etc., are irrelevant for the purposes of
@@ -175,14 +181,15 @@ private function getUserGroupPermsAssociations() {
$query = $db->getQuery(TRUE);
$query
- ->select($db->quoteName('rules'))
- ->from($db->quoteName('#__assets'))
- ->where($db->quoteName('name') . ' = ' . $db->quote('com_civicrm'));
+ ->select($db->quoteName('rules'))
+ ->from($db->quoteName('#__assets'))
+ ->where($db->quoteName('name') . ' = ' . $db->quote('com_civicrm'));
$db->setQuery($query);
- // Load the result as a stdClass object, decoding JSON on the way
- return json_decode($db->loadObject()->rules);
+ // Joomla gotcha: loadObject returns NULL in the case of no matches.
+ $result = $db->loadObject();
+ return $result ? json_decode($result->rules) : (object) [];
}
/**
@@ -198,9 +205,9 @@ private function updateGroupPermsAssociations($associations) {
$query = $db->getQuery(TRUE);
$query
- ->update($db->quoteName('#__assets'))
- ->set($db->quoteName('rules') . ' = ' . $db->quote(json_encode($associations)))
- ->where($db->quoteName('name') . ' = ' . $db->quote('com_civicrm'));
+ ->update($db->quoteName('#__assets'))
+ ->set($db->quoteName('rules') . ' = ' . $db->quote(json_encode($associations)))
+ ->where($db->quoteName('name') . ' = ' . $db->quote('com_civicrm'));
$db->setQuery($query)->execute();
}
diff --git a/CRM/Core/Permission/Soap.php b/CRM/Core/Permission/Soap.php
index fcb87791b2d0..dd746e631ed8 100644
--- a/CRM/Core/Permission/Soap.php
+++ b/CRM/Core/Permission/Soap.php
@@ -1,9 +1,9 @@
array($perm))
@@ -103,7 +103,7 @@ public function check($perm) {
* Array(string $permName => bool $granted).
*/
protected function index($grants) {
- $idx = array();
+ $idx = [];
foreach ($grants as $grant) {
foreach ($grant as $perm) {
$idx[$perm] = 1;
diff --git a/CRM/Core/Permission/UnitTests.php b/CRM/Core/Permission/UnitTests.php
index 86b199bff690..0dccf48cdfee 100644
--- a/CRM/Core/Permission/UnitTests.php
+++ b/CRM/Core/Permission/UnitTests.php
@@ -1,9 +1,9 @@
translatePermission($str, 'WordPress', array(
+ $str = $this->translatePermission($str, 'WordPress', [
'administer users' => 'edit_users',
- ));
+ ]);
if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
return FALSE;
}
@@ -74,16 +76,18 @@ public function check($str) {
return TRUE;
}
- if (current_user_can('super admin') || current_user_can('administrator')) {
+ $user = $userId ? get_userdata($userId) : wp_get_current_user();
+
+ if ($user->has_cap('super admin') || $user->has_cap('administrator')) {
return TRUE;
}
// Make string lowercase and convert spaces into underscore
$str = CRM_Utils_String::munge(strtolower($str));
- if (is_user_logged_in()) {
+ if ($user->exists()) {
// Check whether the logged in user has the capabilitity
- if (current_user_can($str)) {
+ if ($user->has_cap($str)) {
return TRUE;
}
}
diff --git a/CRM/Core/PrevNextCache/Interface.php b/CRM/Core/PrevNextCache/Interface.php
new file mode 100644
index 000000000000..6c355050e757
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Interface.php
@@ -0,0 +1,133 @@
+ ['foo', 'String']]
+ * @return bool
+ * @see CRM_Core_DAO::composeQuery
+ */
+ public function fillWithSql($cacheKey, $sql, $sqlParams = []);
+
+ /**
+ * Store the contents of an array in the cache.
+ *
+ * @param string $cacheKey
+ * @param array $rows
+ * A list of cache records. Each record should have keys:
+ * - entity_id1
+ * - data
+ * @return bool
+ */
+ public function fillWithArray($cacheKey, $rows);
+
+ /**
+ * Save checkbox selections.
+ *
+ * @param string $cacheKey
+ * @param string $action
+ * Ex: 'select', 'unselect'.
+ * @param array|int|NULL $ids
+ * A list of contact IDs to (un)select.
+ * To unselect all contact IDs, use NULL.
+ */
+ public function markSelection($cacheKey, $action, $ids = NULL);
+
+ /**
+ * Get the selections.
+ *
+ * @param string $cacheKey
+ * Cache key.
+ * @param string $action
+ * One of the following:
+ * - 'get' - get only selection records
+ * - 'getall' - get all the records of the specified cache key
+ *
+ * @return array|NULL
+ */
+ public function getSelection($cacheKey, $action = 'get');
+
+ /**
+ * Get the previous and next keys.
+ *
+ * @param string $cacheKey
+ * @param int $id1
+ *
+ * @return array
+ * List of neighbors.
+ * [
+ * 'foundEntry' => 1,
+ * 'prev' => ['id1' => 123, 'data'=>'foo'],
+ * 'next' => ['id1' => 456, 'data'=>'foo'],
+ * ]
+ */
+ public function getPositions($cacheKey, $id1);
+
+ /**
+ * Delete an item from the prevnext cache table based on the entity.
+ *
+ * @param int $id
+ * @param string $cacheKey
+ */
+ public function deleteItem($id = NULL, $cacheKey = NULL);
+
+ /**
+ * Get count of matching rows.
+ *
+ * @param string $cacheKey
+ * @return int
+ */
+ public function getCount($cacheKey);
+
+ /**
+ * Fetch a list of contacts from the prev/next cache for displaying a search results page
+ *
+ * @param string $cacheKey
+ * @param int $offset
+ * @param int $rowCount
+ * @return array
+ * List of contact IDs (entity_id1).
+ */
+ public function fetch($cacheKey, $offset, $rowCount);
+
+}
diff --git a/CRM/Core/PrevNextCache/Redis.php b/CRM/Core/PrevNextCache/Redis.php
new file mode 100644
index 000000000000..a08d9ba0c614
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Redis.php
@@ -0,0 +1,255 @@
+redis = CRM_Utils_Cache_Redis::connect($settings);
+ $this->prefix = isset($settings['prefix']) ? $settings['prefix'] : '';
+ $this->prefix .= \CRM_Utils_Cache::DELIMITER . 'prevnext' . \CRM_Utils_Cache::DELIMITER;
+ }
+
+ public function fillWithSql($cacheKey, $sql, $sqlParams = []) {
+ $dao = CRM_Core_DAO::executeQuery($sql, $sqlParams, FALSE, NULL, FALSE, TRUE, TRUE);
+ if (is_a($dao, 'DB_Error')) {
+ throw new CRM_Core_Exception($dao->message);
+ }
+
+ list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
+
+ while ($dao->fetch()) {
+ list (, $entity_id, $data) = array_values($dao->toArray());
+ $maxScore++;
+ $this->redis->zAdd($allKey, $maxScore, $entity_id);
+ $this->redis->hSet($dataKey, $entity_id, $data);
+ }
+
+ return TRUE;
+ }
+
+ public function fillWithArray($cacheKey, $rows) {
+ list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
+
+ foreach ($rows as $row) {
+ $maxScore++;
+ $this->redis->zAdd($allKey, $maxScore, $row['entity_id1']);
+ $this->redis->hSet($dataKey, $row['entity_id1'], $row['data']);
+ }
+
+ return TRUE;
+ }
+
+ public function fetch($cacheKey, $offset, $rowCount) {
+ $allKey = $this->key($cacheKey, 'all');
+ return $this->redis->zRange($allKey, $offset, $offset + $rowCount - 1);
+ }
+
+ public function markSelection($cacheKey, $action, $ids = NULL) {
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+
+ if ($action === 'select') {
+ foreach ((array) $ids as $id) {
+ $score = $this->redis->zScore($allKey, $id);
+ $this->redis->zAdd($selKey, $score, $id);
+ }
+ }
+ elseif ($action === 'unselect' && $ids === NULL) {
+ $this->redis->delete($selKey);
+ $this->redis->setTimeout($selKey, self::TTL);
+ }
+ elseif ($action === 'unselect' && $ids !== NULL) {
+ foreach ((array) $ids as $id) {
+ $this->redis->zDelete($selKey, $id);
+ }
+ }
+ }
+
+ public function getSelection($cacheKey, $action = 'get') {
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+
+ if ($action === 'get') {
+ $result = [];
+ foreach ($this->redis->zRange($selKey, 0, -1) as $entity_id) {
+ $result[$entity_id] = 1;
+ }
+ return [$cacheKey => $result];
+ }
+ elseif ($action === 'getall') {
+ $result = [];
+ foreach ($this->redis->zRange($allKey, 0, -1) as $entity_id) {
+ $result[$entity_id] = 1;
+ }
+ return [$cacheKey => $result];
+ }
+ else {
+ throw new \CRM_Core_Exception("Unrecognized action: $action");
+ }
+ }
+
+ public function getPositions($cacheKey, $id1) {
+ $allKey = $this->key($cacheKey, 'all');
+ $dataKey = $this->key($cacheKey, 'data');
+
+ $rank = $this->redis->zRank($allKey, $id1);
+ if (!is_int($rank) || $rank < 0) {
+ return ['foundEntry' => 0];
+ }
+
+ $pos = ['foundEntry' => 1];
+
+ if ($rank > 0) {
+ $pos['prev'] = [];
+ foreach ($this->redis->zRange($allKey, $rank - 1, $rank - 1) as $value) {
+ $pos['prev']['id1'] = $value;
+ }
+ $pos['prev']['data'] = $this->redis->hGet($dataKey, $pos['prev']['id1']);
+ }
+
+ $count = $this->getCount($cacheKey);
+ if ($count > $rank + 1) {
+ $pos['next'] = [];
+ foreach ($this->redis->zRange($allKey, $rank + 1, $rank + 1) as $value) {
+ $pos['next']['id1'] = $value;
+ }
+ $pos['next']['data'] = $this->redis->hGet($dataKey, $pos['next']['id1']);
+ }
+
+ return $pos;
+ }
+
+ public function deleteItem($id = NULL, $cacheKey = NULL) {
+ if ($id === NULL && $cacheKey !== NULL) {
+ // Delete by cacheKey.
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+ $dataKey = $this->key($cacheKey, 'data');
+ $this->redis->delete($allKey, $selKey, $dataKey);
+ }
+ elseif ($id === NULL && $cacheKey === NULL) {
+ // Delete everything.
+ $keys = $this->redis->keys($this->prefix . '*');
+ $this->redis->del($keys);
+ }
+ elseif ($id !== NULL && $cacheKey !== NULL) {
+ // Delete a specific contact, within a specific cache.
+ $this->redis->zDelete($this->key($cacheKey, 'all'), $id);
+ $this->redis->zDelete($this->key($cacheKey, 'sel'), $id);
+ $this->redis->hDel($this->key($cacheKey, 'data'), $id);
+ }
+ elseif ($id !== NULL && $cacheKey === NULL) {
+ // Delete a specific contact, across all prevnext caches.
+ $allKeys = $this->redis->keys($this->key('*', 'all'));
+ foreach ($allKeys as $allKey) {
+ $parts = explode(\CRM_Utils_Cache::DELIMITER, $allKey);
+ array_pop($parts);
+ $tmpCacheKey = array_pop($parts);
+ $this->deleteItem($id, $tmpCacheKey);
+ }
+ }
+ else {
+ throw new CRM_Core_Exception("Not implemented: Redis::deleteItem");
+ }
+ }
+
+ public function getCount($cacheKey) {
+ $allKey = $this->key($cacheKey, 'all');
+ return $this->redis->zSize($allKey);
+ }
+
+ /**
+ * Construct the full path to a cache item.
+ *
+ * @param string $cacheKey
+ * Identifier for this saved search.
+ * Ex: 'abcd1234abcd1234'.
+ * @param string $item
+ * Ex: 'list', 'rel', 'data'.
+ * @return string
+ * Ex: 'dmaster/prevnext/abcd1234abcd1234/list'
+ */
+ private function key($cacheKey, $item) {
+ return $this->prefix . $cacheKey . \CRM_Utils_Cache::DELIMITER . $item;
+ }
+
+ /**
+ * Initialize any data-structures or timeouts for the cache-key.
+ *
+ * This is non-destructive -- if data already exists, it's preserved.
+ *
+ * @return array
+ * 0 => string $allItemsCacheKey,
+ * 1 => string $dataItemsCacheKey,
+ * 2 => string $selectedItemsCacheKey,
+ * 3 => int $maxExistingScore
+ */
+ private function initCacheKey($cacheKey) {
+ $allKey = $this->key($cacheKey, 'all');
+ $selKey = $this->key($cacheKey, 'sel');
+ $dataKey = $this->key($cacheKey, 'data');
+
+ $this->redis->setTimeout($allKey, self::TTL);
+ $this->redis->setTimeout($dataKey, self::TTL);
+ $this->redis->setTimeout($selKey, self::TTL);
+
+ $maxScore = 0;
+ foreach ($this->redis->zRange($allKey, -1, -1, TRUE) as $lastElem => $lastScore) {
+ $maxScore = $lastScore;
+ }
+ return [$allKey, $dataKey, $selKey, $maxScore];
+ }
+
+}
diff --git a/CRM/Core/PrevNextCache/Sql.php b/CRM/Core/PrevNextCache/Sql.php
new file mode 100644
index 000000000000..10fed3637e24
--- /dev/null
+++ b/CRM/Core/PrevNextCache/Sql.php
@@ -0,0 +1,275 @@
+ ['foo', 'String']]
+ * @return bool
+ * @throws CRM_Core_Exception
+ * @see CRM_Core_DAO::composeQuery
+ */
+ public function fillWithSql($cacheKey, $sql, $sqlParams = []) {
+ $insertSQL = "
+INSERT INTO civicrm_prevnext_cache (cacheKey, entity_id1, data)
+";
+ $result = CRM_Core_DAO::executeQuery($insertSQL . $sql, $sqlParams, FALSE, NULL, FALSE, TRUE, TRUE);
+ if (is_a($result, 'DB_Error')) {
+ throw new CRM_Core_Exception($result->message);
+ }
+ return TRUE;
+ }
+
+ public function fillWithArray($cacheKey, $rows) {
+ if (empty($rows)) {
+ return;
+ }
+
+ $insert = CRM_Utils_SQL_Insert::into('civicrm_prevnext_cache')
+ ->columns([
+ 'entity_id1',
+ 'cacheKey',
+ 'data',
+ ]);
+
+ foreach ($rows as &$row) {
+ $insert->row($row + ['cacheKey' => $cacheKey]);
+ }
+
+ CRM_Core_DAO::executeQuery($insert->toSQL());
+ return TRUE;
+ }
+
+ /**
+ * Save checkbox selections.
+ *
+ * @param string $cacheKey
+ * @param string $action
+ * Ex: 'select', 'unselect'.
+ * @param array|int|NULL $ids
+ * A list of contact IDs to (un)select.
+ * To unselect all contact IDs, use NULL.
+ */
+ public function markSelection($cacheKey, $action, $ids = NULL) {
+ if (!$cacheKey) {
+ return;
+ }
+ $params = [];
+
+ if ($ids && $cacheKey && $action) {
+ if (is_array($ids)) {
+ $cIdFilter = "(" . implode(',', $ids) . ")";
+ $whereClause = "
+WHERE cacheKey = %1
+AND (entity_id1 IN {$cIdFilter} OR entity_id2 IN {$cIdFilter})
+";
+ }
+ else {
+ $whereClause = "
+WHERE cacheKey = %1
+AND (entity_id1 = %2 OR entity_id2 = %2)
+";
+ $params[2] = ["{$ids}", 'Integer'];
+ }
+ if ($action == 'select') {
+ $whereClause .= "AND is_selected = 0";
+ $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 1 {$whereClause}";
+ $params[1] = [$cacheKey, 'String'];
+ }
+ elseif ($action == 'unselect') {
+ $whereClause .= "AND is_selected = 1";
+ $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 0 {$whereClause}";
+ $params[1] = [$cacheKey, 'String'];
+ }
+ // default action is reseting
+ }
+ elseif (!$ids && $cacheKey && $action == 'unselect') {
+ $sql = "
+UPDATE civicrm_prevnext_cache
+SET is_selected = 0
+WHERE cacheKey = %1 AND is_selected = 1
+";
+ $params[1] = [$cacheKey, 'String'];
+ }
+ CRM_Core_DAO::executeQuery($sql, $params);
+ }
+
+ /**
+ * Get the selections.
+ *
+ * @param string $cacheKey
+ * Cache key.
+ * @param string $action
+ * One of the following:
+ * - 'get' - get only selection records
+ * - 'getall' - get all the records of the specified cache key
+ *
+ * @return array|NULL
+ */
+ public function getSelection($cacheKey, $action = 'get') {
+ if (!$cacheKey) {
+ return NULL;
+ }
+ $params = [];
+
+ if ($cacheKey && ($action == 'get' || $action == 'getall')) {
+ $actionGet = ($action == "get") ? " AND is_selected = 1 " : "";
+ $sql = "
+SELECT entity_id1 FROM civicrm_prevnext_cache
+WHERE cacheKey = %1
+ $actionGet
+ORDER BY id
+";
+ $params[1] = [$cacheKey, 'String'];
+
+ $contactIds = [$cacheKey => []];
+ $cIdDao = CRM_Core_DAO::executeQuery($sql, $params);
+ while ($cIdDao->fetch()) {
+ $contactIds[$cacheKey][$cIdDao->entity_id1] = 1;
+ }
+ return $contactIds;
+ }
+ }
+
+ /**
+ * Get the previous and next keys.
+ *
+ * @param string $cacheKey
+ * @param int $id1
+ *
+ * @return array
+ */
+ public function getPositions($cacheKey, $id1) {
+ $mergeId = CRM_Core_DAO::singleValueQuery(
+ "SELECT id FROM civicrm_prevnext_cache WHERE cacheKey = %2 AND entity_id1 = %1",
+ [
+ 1 => [$id1, 'Integer'],
+ 2 => [$cacheKey, 'String'],
+ ]
+ );
+
+ $pos = ['foundEntry' => 0];
+ if ($mergeId) {
+ $pos['foundEntry'] = 1;
+
+ $sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn ";
+ $wherePrev = " WHERE pn.id < %1 AND pn.cacheKey = %2 ORDER BY ID DESC LIMIT 1";
+ $whereNext = " WHERE pn.id > %1 AND pn.cacheKey = %2 ORDER BY ID ASC LIMIT 1";
+ $p = [
+ 1 => [$mergeId, 'Integer'],
+ 2 => [$cacheKey, 'String'],
+ ];
+
+ $dao = CRM_Core_DAO::executeQuery($sql . $wherePrev, $p);
+ if ($dao->fetch()) {
+ $pos['prev']['id1'] = $dao->entity_id1;
+ $pos['prev']['mergeId'] = $dao->id;
+ $pos['prev']['data'] = $dao->data;
+ }
+
+ $dao = CRM_Core_DAO::executeQuery($sql . $whereNext, $p);
+ if ($dao->fetch()) {
+ $pos['next']['id1'] = $dao->entity_id1;
+ $pos['next']['mergeId'] = $dao->id;
+ $pos['next']['data'] = $dao->data;
+ }
+ }
+ return $pos;
+
+ }
+
+ /**
+ * Delete an item from the prevnext cache table based on the entity.
+ *
+ * @param int $id
+ * @param string $cacheKey
+ */
+ public function deleteItem($id = NULL, $cacheKey = NULL) {
+ $sql = "DELETE FROM civicrm_prevnext_cache WHERE (1)";
+ $params = [];
+
+ if (is_numeric($id)) {
+ $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
+ $params[2] = [$id, 'Integer'];
+ }
+
+ if (isset($cacheKey)) {
+ $sql .= " AND cacheKey = %3";
+ $params[3] = [$cacheKey, 'String'];
+ }
+ CRM_Core_DAO::executeQuery($sql, $params);
+ }
+
+ /**
+ * Get count of matching rows.
+ *
+ * @param string $cacheKey
+ * @return int
+ */
+ public function getCount($cacheKey) {
+ $query = "SELECT COUNT(*) FROM civicrm_prevnext_cache pn WHERE pn.cacheKey = %1";
+ $params = [1 => [$cacheKey, 'String']];
+ return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
+ }
+
+ /**
+ * Fetch a list of contacts from the prev/next cache for displaying a search results page
+ *
+ * @param string $cacheKey
+ * @param int $offset
+ * @param int $rowCount
+ * @return array
+ * List of contact IDs.
+ */
+ public function fetch($cacheKey, $offset, $rowCount) {
+ $cids = [];
+ $dao = CRM_Utils_SQL_Select::from('civicrm_prevnext_cache pnc')
+ ->where('pnc.cacheKey = @cacheKey', ['cacheKey' => $cacheKey])
+ ->select('pnc.entity_id1 as cid')
+ ->orderBy('pnc.id')
+ ->limit($rowCount, $offset)
+ ->execute();
+ while ($dao->fetch()) {
+ $cids[] = $dao->cid;
+ }
+ return $cids;
+ }
+
+}
diff --git a/CRM/Core/PseudoConstant.php b/CRM/Core/PseudoConstant.php
index 419664441890..28984e107d1c 100644
--- a/CRM/Core/PseudoConstant.php
+++ b/CRM/Core/PseudoConstant.php
@@ -1,9 +1,9 @@
FALSE,
- 'localize' => FALSE,
+ 'localize' => $localizeDefault,
'onlyActive' => ($context == 'validate' || $context == 'get') ? FALSE : TRUE,
'fresh' => FALSE,
'context' => $context,
- );
+ ];
$entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getCanonicalClassName($daoName));
// Custom fields are not in the schema
@@ -224,14 +220,12 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
if ($options && $flip) {
$options = array_flip($options);
}
- $customField->free();
return $options;
}
// Core field: load schema
$dao = new $daoName();
$fieldSpec = $dao->getFieldSpec($fieldName);
- $dao->free();
// Ensure we have the canonical name for this field
$fieldName = CRM_Utils_Array::value('name', $fieldSpec, $fieldName);
@@ -253,11 +247,11 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
}
// Merge params with schema defaults
- $params += array(
- 'condition' => CRM_Utils_Array::value('condition', $pseudoconstant, array()),
+ $params += [
+ 'condition' => CRM_Utils_Array::value('condition', $pseudoconstant, []),
'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant),
'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant),
- );
+ ];
if ($context == 'abbreviate') {
switch ($fieldName) {
@@ -317,11 +311,10 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
// Get list of fields for the option table
$dao = new $daoName();
$availableFields = array_keys($dao->fieldKeys());
- $dao->free();
$select = "SELECT %1 AS id, %2 AS label";
$from = "FROM %3";
- $wheres = array();
+ $wheres = [];
$order = "ORDER BY %2";
// Use machine name in certain contexts
@@ -340,7 +333,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
}
// onlyActive param will automatically filter on common flags
if (!empty($params['onlyActive'])) {
- foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
+ foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
if (in_array($flag, $availableFields)) {
$wheres[] = "$flag = $val";
}
@@ -350,14 +343,14 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
if (in_array('domain_id', $availableFields)) {
$wheres[] = 'domain_id = ' . CRM_Core_Config::domainID();
}
- $queryParams = array(
- 1 => array($params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- 2 => array($params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- );
+ $queryParams = [
+ 1 => [$params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ 2 => [$params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ ];
// Add orderColumn param
if (!empty($params['orderColumn'])) {
- $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES);
+ $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES];
$order = "ORDER BY %4";
}
// Support no sorting if $params[orderColumn] is FALSE
@@ -369,7 +362,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
$order = "ORDER BY weight";
}
- $output = array();
+ $output = [];
$query = "$select $from";
if ($wheres) {
$query .= " WHERE " . implode($wheres, ' AND ');
@@ -379,15 +372,11 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
while ($dao->fetch()) {
$output[$dao->id] = $dao->label;
}
- $dao->free();
// Localize results
if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') {
- $I18nParams = array();
- if ($pseudoconstant['table'] == 'civicrm_country') {
- $I18nParams['context'] = 'country';
- }
- if ($pseudoconstant['table'] == 'civicrm_state_province') {
- $I18nParams['context'] = 'province';
+ $I18nParams = [];
+ if (isset($fieldSpec['localize_context'])) {
+ $I18nParams['context'] = $fieldSpec['localize_context'];
}
$i18n = CRM_Core_I18n::singleton();
$i18n->localizeArray($output, $I18nParams);
@@ -405,7 +394,7 @@ public static function get($daoName, $fieldName, $params = array(), $context = N
// Return "Yes" and "No" for boolean fields
elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) {
- $output = $context == 'validate' ? array(0, 1) : CRM_Core_SelectValues::boolean();
+ $output = $context == 'validate' ? [0, 1] : CRM_Core_SelectValues::boolean();
CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
return $flip ? array_flip($output) : $output;
}
@@ -503,7 +492,7 @@ public static function getOptionEditUrl($fieldSpec) {
}
/**
- * DEPRECATED generic populate method.
+ * @deprecated generic populate method.
* All pseudoconstant functions that use this method are also @deprecated
*
* The static array $var is populated from the db
@@ -541,10 +530,10 @@ public static function populate(
$key = 'id',
$force = NULL
) {
- $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
+ $cacheKey = CRM_Core_BAO_Cache::cleanKey("CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}");
$cache = CRM_Utils_Cache::singleton();
$var = $cache->get($cacheKey);
- if ($var && empty($force)) {
+ if ($var !== NULL && empty($force)) {
return $var;
}
@@ -573,7 +562,7 @@ public static function populate(
}
$object->find();
- $var = array();
+ $var = [];
while ($object->fetch()) {
$var[$object->$key] = $object->$retrieve;
}
@@ -585,7 +574,6 @@ public static function populate(
* Flush given pseudoconstant so it can be reread from db.
* nex time it's requested.
*
- *
* @param bool|string $name pseudoconstant to be flushed
*/
public static function flush($name = 'cache') {
@@ -594,6 +582,9 @@ public static function flush($name = 'cache') {
}
if ($name == 'cache') {
CRM_Core_OptionGroup::flushAll();
+ if (isset(\Civi::$statics[__CLASS__])) {
+ unset(\Civi::$statics[__CLASS__]);
+ }
}
}
@@ -621,7 +612,7 @@ public static function &activityType() {
$index .= '_' . (int) $onlyComponentActivities;
if (NULL === self::$activityType) {
- self::$activityType = array();
+ self::$activityType = [];
}
if (!isset(self::$activityType[$index]) || $reset) {
@@ -634,7 +625,7 @@ public static function &activityType() {
$componentClause = " v.component_id IS NOT NULL";
}
- $componentIds = array();
+ $componentIds = [];
$compInfo = CRM_Core_Component::getEnabledComponents();
// build filter for listing activity types only if their
@@ -692,7 +683,7 @@ public static function &stateProvince($id = FALSE, $limit = TRUE) {
if ($limit) {
$countryIsoCodes = self::countryIsoCode();
$limitCodes = CRM_Core_BAO_Country::provinceLimit();
- $limitIds = array();
+ $limitIds = [];
foreach ($limitCodes as $code) {
$limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
}
@@ -709,9 +700,9 @@ public static function &stateProvince($id = FALSE, $limit = TRUE) {
$tsLocale = CRM_Core_I18n::getLocale();
if ($tsLocale != '' and $tsLocale != 'en_US') {
$i18n = CRM_Core_I18n::singleton();
- $i18n->localizeArray(self::$stateProvince, array(
+ $i18n->localizeArray(self::$stateProvince, [
'context' => 'province',
- ));
+ ]);
self::$stateProvince = CRM_Utils_Array::asort(self::$stateProvince);
}
}
@@ -746,12 +737,12 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
$query = "SELECT abbreviation
FROM civicrm_state_province
WHERE id = %1";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$id,
'Integer',
- ),
- );
+ ],
+ ];
self::$stateProvinceAbbreviation[$id] = CRM_Core_DAO::singleValueQuery($query, $params);
}
return self::$stateProvinceAbbreviation[$id];
@@ -762,7 +753,7 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
if ($limit) {
$countryIsoCodes = self::countryIsoCode();
$limitCodes = CRM_Core_BAO_Country::provinceLimit();
- $limitIds = array();
+ $limitIds = [];
foreach ($limitCodes as $code) {
$tmpArray = array_keys($countryIsoCodes, $code);
@@ -780,6 +771,32 @@ public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
return self::$stateProvinceAbbreviation;
}
+ /**
+ * Get all the State/Province abbreviations from the database for the specified country.
+ *
+ * @param int $countryID
+ *
+ * @return array
+ * array of all State/Province abbreviations for the given country.
+ */
+ public static function stateProvinceAbbreviationForCountry($countryID) {
+ if (!isset(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID])) {
+ \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID] = [];
+ }
+ self::populate(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
+ return \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID];
+ }
+
+ /**
+ * Get all the State/Province abbreviations from the database for the default country.
+ *
+ * @return array
+ * array of all State/Province abbreviations for the given country.
+ */
+ public static function stateProvinceAbbreviationForDefaultCountry() {
+ return CRM_Core_PseudoConstant::stateProvinceAbbreviationForCountry(Civi::settings()->get('defaultContactCountry'));
+ }
+
/**
* Get all the countries from database.
*
@@ -801,7 +818,7 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
if (($id && !CRM_Utils_Array::value($id, self::$country)) || !self::$country || !$id) {
$config = CRM_Core_Config::singleton();
- $limitCodes = array();
+ $limitCodes = [];
if ($applyLimit) {
// limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
@@ -809,9 +826,9 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
// K/P: We need to fix this, i dont think it works with new setting files
$limitCodes = CRM_Core_BAO_Country::countryLimit();
if (!is_array($limitCodes)) {
- $limitCodes = array(
+ $limitCodes = [
$config->countryLimit => 1,
- );
+ ];
}
$limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
@@ -840,9 +857,9 @@ public static function country($id = FALSE, $applyLimit = TRUE) {
$tsLocale = CRM_Core_I18n::getLocale();
if ($tsLocale != '' and $tsLocale != 'en_US') {
$i18n = CRM_Core_I18n::singleton();
- $i18n->localizeArray(self::$country, array(
+ $i18n->localizeArray(self::$country, [
'context' => 'country',
- ));
+ ]);
self::$country = CRM_Utils_Array::asort(self::$country);
}
}
@@ -908,6 +925,11 @@ public static function &countryIsoCode($id = FALSE) {
* array reference of all groups.
*/
public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
+ if ($groupType === 'validate') {
+ // validate gets passed through from getoptions. Handle in the deprecated
+ // fn rather than change the new pattern.
+ $groupType = NULL;
+ }
$condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
$groupKey = ($groupType ? $groupType : 'null') . !empty($excludeHidden);
@@ -1011,7 +1033,7 @@ public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $exc
public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
$cacheKey = $valueColumnName . '::' . $isActive;
if (!CRM_Utils_Array::value($cacheKey, self::$relationshipType) || $reset) {
- self::$relationshipType[$cacheKey] = array();
+ self::$relationshipType[$cacheKey] = [];
//now we have name/label columns CRM-3336
$column_a_b = "{$valueColumnName}_a_b";
@@ -1026,7 +1048,7 @@ public static function &relationshipType($valueColumnName = 'label', $reset = FA
$relationshipTypeDAO->find();
while ($relationshipTypeDAO->fetch()) {
- self::$relationshipType[$cacheKey][$relationshipTypeDAO->id] = array(
+ self::$relationshipType[$cacheKey][$relationshipTypeDAO->id] = [
'id' => $relationshipTypeDAO->id,
$column_a_b => $relationshipTypeDAO->$column_a_b,
$column_b_a => $relationshipTypeDAO->$column_b_a,
@@ -1034,7 +1056,7 @@ public static function &relationshipType($valueColumnName = 'label', $reset = FA
'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
- );
+ ];
}
}
@@ -1052,275 +1074,13 @@ public static function &relationshipType($valueColumnName = 'label', $reset = FA
*/
public static function ¤cyCode() {
if (!self::$currencyCode) {
- self::$currencyCode = array(
- 'AFN',
- 'ALL',
- 'DZD',
- 'USD',
- 'EUR',
- 'AOA',
- 'XCD',
- 'XCD',
- 'ARS',
- 'AMD',
- 'AWG',
- 'AUD',
- 'EUR',
- 'AZM',
- 'BSD',
- 'BHD',
- 'BDT',
- 'BBD',
- 'BYR',
- 'EUR',
- 'BZD',
- 'XOF',
- 'BMD',
- 'INR',
- 'BTN',
- 'BOB',
- 'BOV',
- 'BAM',
- 'BWP',
- 'NOK',
- 'BRL',
- 'USD',
- 'BND',
- 'BGN',
- 'XOF',
- 'BIF',
- 'KHR',
- 'XAF',
- 'CAD',
- 'CVE',
- 'KYD',
- 'XAF',
- 'XAF',
- 'CLP',
- 'CLF',
- 'CNY',
- 'AUD',
- 'AUD',
- 'COP',
- 'COU',
- 'KMF',
- 'XAF',
- 'CDF',
- 'NZD',
- 'CRC',
- 'XOF',
- 'HRK',
- 'CUP',
- 'CYP',
- 'CZK',
- 'DKK',
- 'DJF',
- 'XCD',
- 'DOP',
- 'USD',
- 'EGP',
- 'SVC',
- 'USD',
- 'XAF',
- 'ERN',
- 'EEK',
- 'ETB',
- 'FKP',
- 'DKK',
- 'FJD',
- 'EUR',
- 'EUR',
- 'EUR',
- 'XPF',
- 'EUR',
- 'XAF',
- 'GMD',
- 'GEL',
- 'EUR',
- 'GHC',
- 'GIP',
- 'EUR',
- 'DKK',
- 'XCD',
- 'EUR',
- 'USD',
- 'GTQ',
- 'GNF',
- 'GWP',
- 'XOF',
- 'GYD',
- 'HTG',
- 'USD',
- 'AUD',
- 'EUR',
- 'HNL',
- 'HKD',
- 'HUF',
- 'ISK',
- 'INR',
- 'IDR',
- 'XDR',
- 'IRR',
- 'IQD',
- 'EUR',
- 'ILS',
- 'EUR',
- 'JMD',
- 'JPY',
- 'JOD',
- 'KZT',
- 'KES',
- 'AUD',
- 'KPW',
- 'KRW',
- 'KWD',
- 'KGS',
- 'LAK',
- 'LVL',
- 'LBP',
- 'ZAR',
- 'LSL',
- 'LRD',
- 'LYD',
- 'CHF',
- 'LTL',
- 'EUR',
- 'MOP',
- 'MKD',
- 'MGA',
- 'MWK',
- 'MYR',
- 'MVR',
- 'XOF',
- 'MTL',
- 'USD',
- 'EUR',
- 'MRO',
- 'MUR',
- 'EUR',
- 'MXN',
- 'MXV',
- 'USD',
- 'MDL',
- 'EUR',
- 'MNT',
- 'XCD',
- 'MAD',
- 'MZM',
- 'MMK',
- 'ZAR',
- 'NAD',
- 'AUD',
- 'NPR',
- 'EUR',
- 'ANG',
- 'XPF',
- 'NZD',
- 'NIO',
- 'XOF',
- 'NGN',
- 'NZD',
- 'AUD',
- 'USD',
- 'NOK',
- 'OMR',
- 'PKR',
- 'USD',
- 'PAB',
- 'USD',
- 'PGK',
- 'PYG',
- 'PEN',
- 'PHP',
- 'NZD',
- 'PLN',
- 'EUR',
- 'USD',
- 'QAR',
- 'EUR',
- 'ROL',
- 'RON',
- 'RUB',
- 'RWF',
- 'SHP',
- 'XCD',
- 'XCD',
- 'EUR',
- 'XCD',
- 'WST',
- 'EUR',
- 'STD',
- 'SAR',
- 'XOF',
- 'CSD',
- 'EUR',
- 'SCR',
- 'SLL',
- 'SGD',
- 'SKK',
- 'SIT',
- 'SBD',
- 'SOS',
- 'ZAR',
- 'EUR',
- 'LKR',
- 'SDD',
- 'SRD',
- 'NOK',
- 'SZL',
- 'SEK',
- 'CHF',
- 'CHW',
- 'CHE',
- 'SYP',
- 'TWD',
- 'TJS',
- 'TZS',
- 'THB',
- 'USD',
- 'XOF',
- 'NZD',
- 'TOP',
- 'TTD',
- 'TND',
- 'TRY',
- 'TRL',
- 'TMM',
- 'USD',
- 'AUD',
- 'UGX',
- 'UAH',
- 'AED',
- 'GBP',
- 'USD',
- 'USS',
- 'USN',
- 'USD',
- 'UYU',
- 'UZS',
- 'VUV',
- 'VEB',
- 'VND',
- 'USD',
- 'USD',
- 'XPF',
- 'MAD',
- 'YER',
- 'ZMK',
- 'ZWD',
- 'XAU',
- 'XBA',
- 'XBB',
- 'XBC',
- 'XBD',
- 'XPD',
- 'XPT',
- 'XAG',
- 'XFU',
- 'XFO',
- 'XTS',
- 'XXX',
- );
+
+ $query = "SELECT name FROM civicrm_currency";
+ $dao = CRM_Core_DAO::executeQuery($query);
+ $currencyCode = [];
+ while ($dao->fetch()) {
+ self::$currencyCode[] = $dao->name;
+ }
}
return self::$currencyCode;
}
@@ -1462,10 +1222,10 @@ public static function &worldRegion($id = FALSE) {
*/
public static function &activityStatus($column = 'label') {
if (NULL === self::$activityStatus) {
- self::$activityStatus = array();
+ self::$activityStatus = [];
}
if (!array_key_exists($column, self::$activityStatus)) {
- self::$activityStatus[$column] = array();
+ self::$activityStatus[$column] = [];
self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
}
@@ -1488,7 +1248,7 @@ public static function &activityStatus($column = 'label') {
*/
public static function &visibility($column = 'label') {
if (!isset(self::$visibility)) {
- self::$visibility = array();
+ self::$visibility = [];
}
if (!isset(self::$visibility[$column])) {
@@ -1509,7 +1269,7 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
$cacheKey = "{$countryID}_{$field}";
if (!$_cache) {
- $_cache = array();
+ $_cache = [];
}
if (!empty($_cache[$cacheKey])) {
@@ -1521,16 +1281,16 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
FROM civicrm_state_province
WHERE country_id = %1
ORDER BY name";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$countryID,
'Integer',
- ),
- );
+ ],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$dao->id] = $dao->name;
}
@@ -1540,9 +1300,9 @@ public static function &stateProvinceForCountry($countryID, $field = 'name') {
$tsLocale = CRM_Core_I18n::getLocale();
if ($tsLocale != '' and $tsLocale != 'en_US') {
$i18n = CRM_Core_I18n::singleton();
- $i18n->localizeArray($result, array(
+ $i18n->localizeArray($result, [
'context' => 'province',
- ));
+ ]);
$result = CRM_Utils_Array::asort($result);
}
@@ -1570,7 +1330,7 @@ public static function &countyForState($stateID) {
$dao = CRM_Core_DAO::executeQuery($query);
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
}
@@ -1581,7 +1341,7 @@ public static function &countyForState($stateID) {
$cacheKey = "{$stateID}_name";
if (!$_cache) {
- $_cache = array();
+ $_cache = [];
}
if (!empty($_cache[$cacheKey])) {
@@ -1593,16 +1353,16 @@ public static function &countyForState($stateID) {
FROM civicrm_county
WHERE state_province_id = %1
ORDER BY name";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
$stateID,
'Integer',
- ),
- );
+ ],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$result[$dao->id] = $dao->name;
}
@@ -1630,7 +1390,7 @@ public static function countryIDForStateID($stateID) {
FROM civicrm_state_province
WHERE id = %1
";
- $params = array(1 => array($stateID, 'Integer'));
+ $params = [1 => [$stateID, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -1650,6 +1410,10 @@ public static function countryIDForStateID($stateID) {
* array reference of all greetings.
*/
public static function greeting($filter, $columnName = 'label') {
+ if (!isset(Civi::$statics[__CLASS__]['greeting'])) {
+ Civi::$statics[__CLASS__]['greeting'] = [];
+ }
+
$index = $filter['greeting_type'] . '_' . $columnName;
// also add contactType to the array
@@ -1658,11 +1422,7 @@ public static function greeting($filter, $columnName = 'label') {
$index .= '_' . $contactType;
}
- if (NULL === self::$greeting) {
- self::$greeting = array();
- }
-
- if (!CRM_Utils_Array::value($index, self::$greeting)) {
+ if (!CRM_Utils_Array::value($index, Civi::$statics[__CLASS__]['greeting'])) {
$filterCondition = NULL;
if ($contactType) {
$filterVal = 'v.filter =';
@@ -1682,40 +1442,10 @@ public static function greeting($filter, $columnName = 'label') {
$filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
}
- self::$greeting[$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
- }
-
- return self::$greeting[$index];
- }
-
- /**
- * Construct array of default greeting values for contact type.
- *
- *
- * @return array
- * array reference of default greetings.
- */
- public static function &greetingDefaults() {
- if (!self::$greetingDefaults) {
- $defaultGreetings = array();
- $contactTypes = self::get('CRM_Contact_DAO_Contact', 'contact_type', array(
- 'keyColumn' => 'id',
- 'labelColumn' => 'name',
- ));
-
- foreach ($contactTypes as $filter => $contactType) {
- $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
-
- foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
- $tokenVal = CRM_Core_OptionGroup::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
- $defaultGreetings[$contactType][$greeting] = $tokenVal;
- }
- }
-
- self::$greetingDefaults = $defaultGreetings;
+ Civi::$statics[__CLASS__]['greeting'][$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
}
- return self::$greetingDefaults;
+ return Civi::$statics[__CLASS__]['greeting'][$index];
}
/**
@@ -1732,7 +1462,7 @@ public static function &greetingDefaults() {
*/
public static function &getExtensions() {
if (!self::$extensions) {
- self::$extensions = array();
+ self::$extensions = [];
$sql = '
SELECT full_name, label
FROM civicrm_extension
@@ -1787,7 +1517,6 @@ public static function getModuleExtensions($fresh = FALSE) {
return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
}
-
/**
* Get all tax rates.
*
@@ -1798,13 +1527,13 @@ public static function getModuleExtensions($fresh = FALSE) {
*/
public static function getTaxRates() {
if (!isset(Civi::$statics[__CLASS__]['taxRates'])) {
- Civi::$statics[__CLASS__]['taxRates'] = array();
- $option = civicrm_api3('option_value', 'get', array(
+ Civi::$statics[__CLASS__]['taxRates'] = [];
+ $option = civicrm_api3('option_value', 'get', [
'sequential' => 1,
'option_group_id' => 'account_relationship',
'name' => 'Sales Tax Account is',
- ));
- $value = array();
+ ]);
+ $value = [];
if ($option['count'] !== 0) {
if ($option['count'] > 1) {
foreach ($option['values'] as $opt) {
@@ -1814,7 +1543,7 @@ public static function getTaxRates() {
else {
$value[] = $option['values'][0]['value'];
}
- $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
+ $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
}
else {
$where = '';
@@ -1835,4 +1564,17 @@ public static function getTaxRates() {
return Civi::$statics[__CLASS__]['taxRates'];
}
+ /**
+ * Get participant status class options.
+ *
+ * @return array
+ */
+ public static function emailOnHoldOptions() {
+ return [
+ '0' => ts('No'),
+ '1' => ts('On Hold Bounce'),
+ '2' => ts('On Hold Opt Out'),
+ ];
+ }
+
}
diff --git a/CRM/Core/QuickForm/Action.php b/CRM/Core/QuickForm/Action.php
index e8b88b0f587a..c36855e66717 100644
--- a/CRM/Core/QuickForm/Action.php
+++ b/CRM/Core/QuickForm/Action.php
@@ -1,9 +1,9 @@
_QFResponseType == 'json') {
- $response = array('content' => $html);
+ $response = ['content' => $html];
if (!empty($page->ajaxResponse)) {
$response += $page->ajaxResponse;
}
@@ -169,7 +169,7 @@ public function renderForm(&$page) {
$content,
"{$page->_name}.pdf",
FALSE,
- array('paper_size' => 'a3', 'orientation' => 'landscape')
+ ['paper_size' => 'a3', 'orientation' => 'landscape']
);
}
else {
diff --git a/CRM/Core/QuickForm/Action/Done.php b/CRM/Core/QuickForm/Action/Done.php
index 234b25379b69..9e7fdae42577 100644
--- a/CRM/Core/QuickForm/Action/Done.php
+++ b/CRM/Core/QuickForm/Action/Done.php
@@ -1,9 +1,9 @@
getAttribute('action');
+ // prevent URLs that end in ? from causing redirects
+ $action = rtrim($action, '?');
+ // FIXME: this should be passed through CRM_Utils_System::url()
$url = $action . (FALSE === strpos($action, '?') ? '?' : '&') . $current->getButtonName('display') . '=true' . '&qfKey=' . $page->get('qfKey');
CRM_Utils_System::redirect($url);
diff --git a/CRM/Core/QuickForm/Action/Next.php b/CRM/Core/QuickForm/Action/Next.php
index 90767f9f4e87..e44698ec82cd 100644
--- a/CRM/Core/QuickForm/Action/Next.php
+++ b/CRM/Core/QuickForm/Action/Next.php
@@ -1,9 +1,9 @@
moveUploadedFile($this->_uploadDir, $newName);
if (!$status) {
- CRM_Core_Error::statusBounce(ts('We could not move the uploaded file %1 to the upload directory %2. Please verify that the \'Temporary Files\' setting points to a valid path which is writable by your web server.', array(
- 1 => $value['name'],
- 2 => $this->_uploadDir,
- )));
+ CRM_Core_Error::statusBounce(ts('We could not move the uploaded file %1 to the upload directory %2. Please verify that the \'Temporary Files\' setting points to a valid path which is writable by your web server.', [
+ 1 => $value['name'],
+ 2 => $this->_uploadDir,
+ ]));
}
if (!empty($data['values'][$pageName][$uploadName]['name'])) {
@unlink($this->_uploadDir . $data['values'][$pageName][$uploadName]);
}
- $value = array(
+ $value = [
'name' => $this->_uploadDir . $newName,
'type' => $value['type'],
- );
+ ];
//CRM-19460 handle brackets if present in $uploadName, similar things we do it for all other inputs.
$value = $element->_prepareValue($value, TRUE);
$data['values'][$pageName] = HTML_QuickForm::arrayMerge($data['values'][$pageName], $value);
diff --git a/CRM/Core/QuickForm/GroupMultiSelect.php b/CRM/Core/QuickForm/GroupMultiSelect.php
index 8da81e66cf78..35a959ad942b 100644
--- a/CRM/Core/QuickForm/GroupMultiSelect.php
+++ b/CRM/Core/QuickForm/GroupMultiSelect.php
@@ -1,7 +1,7 @@
_options as $option) {
- $_labelAttributes = array('style', 'class', 'onmouseover', 'onmouseout');
- $labelAttributes = array();
+ $_labelAttributes = ['style', 'class', 'onmouseover', 'onmouseout'];
+ $labelAttributes = [];
foreach ($_labelAttributes as $attr) {
if (isset($option['attr'][$attr])) {
$labelAttributes[$attr] = $option['attr'][$attr];
@@ -92,19 +93,19 @@ public function toHtml() {
$strHtmlRemove = '';
// build the select all button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 1);");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 1);"];
$this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes);
$attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
$strHtmlAll = "" . PHP_EOL;
// build the select none button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 0);");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 0);"];
$this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes);
$attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
$strHtmlNone = "" . PHP_EOL;
// build the toggle selection button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 2);");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('" . $this->getName() . "', 2);"];
$this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes);
$attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
$strHtmlToggle = "" . PHP_EOL;
@@ -116,26 +117,26 @@ public function toHtml() {
// ... or a dual multi-select
// set name of Select From Box
- $this->_attributesUnselected = array(
+ $this->_attributesUnselected = [
'name' => '__' . $selectName,
'ondblclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add')",
- );
+ ];
$this->_attributesUnselected = array_merge($this->_attributes, $this->_attributesUnselected);
$attrUnselected = $this->_getAttrString($this->_attributesUnselected);
// set name of Select To Box
- $this->_attributesSelected = array(
+ $this->_attributesSelected = [
'name' => '_' . $selectName,
'ondblclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove')",
- );
+ ];
$this->_attributesSelected = array_merge($this->_attributes, $this->_attributesSelected);
$attrSelected = $this->_getAttrString($this->_attributesSelected);
// set name of Select hidden Box
- $this->_attributesHidden = array(
+ $this->_attributesHidden = [
'name' => $selectName,
'style' => 'overflow: hidden; visibility: hidden; width: 1px; height: 0;',
- );
+ ];
$this->_attributesHidden = array_merge($this->_attributes, $this->_attributesHidden);
$attrHidden = $this->_getAttrString($this->_attributesHidden);
@@ -145,11 +146,11 @@ public function toHtml() {
$arrHtmlSelected = array_fill(0, $append, ' ');
}
else {
- $arrHtmlSelected = array();
+ $arrHtmlSelected = [];
}
$options = count($this->_options);
- $arrHtmlUnselected = array();
+ $arrHtmlUnselected = [];
if ($options > 0) {
$arrHtmlHidden = array_fill(0, $options, ' ');
@@ -176,7 +177,7 @@ public function toHtml() {
}
}
else {
- $arrHtmlHidden = array();
+ $arrHtmlHidden = [];
}
// The 'unselected' multi-select which appears on the left
@@ -207,43 +208,43 @@ public function toHtml() {
$strHtmlHidden .= '';
// build the remove button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove'); return false;"];
$this->_removeButtonAttributes = array_merge($this->_removeButtonAttributes, $attributes);
$attrStrRemove = $this->_getAttrString($this->_removeButtonAttributes);
$strHtmlRemove = "" . PHP_EOL;
// build the add button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add'); return false;"];
$this->_addButtonAttributes = array_merge($this->_addButtonAttributes, $attributes);
$attrStrAdd = $this->_getAttrString($this->_addButtonAttributes);
$strHtmlAdd = "" . PHP_EOL;
// build the select all button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'all'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'all'); return false;"];
$this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes);
$attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
$strHtmlAll = "" . PHP_EOL;
// build the select none button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'none'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'none'); return false;"];
$this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes);
$attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
$strHtmlNone = "" . PHP_EOL;
// build the toggle button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'toggle'); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}(this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'toggle'); return false;"];
$this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes);
$attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
$strHtmlToggle = "" . PHP_EOL;
// build the move up button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}moveUp(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}moveUp(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;"];
$this->_upButtonAttributes = array_merge($this->_upButtonAttributes, $attributes);
$attrStrUp = $this->_getAttrString($this->_upButtonAttributes);
$strHtmlMoveUp = "" . PHP_EOL;
// build the move down button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}moveDown(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;");
+ $attributes = ['onclick' => "{$this->_jsPrefix}moveDown(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;"];
$this->_downButtonAttributes = array_merge($this->_downButtonAttributes, $attributes);
$attrStrDown = $this->_getAttrString($this->_downButtonAttributes);
$strHtmlMoveDown = "" . PHP_EOL;
@@ -271,7 +272,7 @@ public function toHtml() {
$strHtml = preg_replace('/\s*.*\s*/i', '', $strHtml);
}
- $placeHolders = array(
+ $placeHolders = [
'{stylesheet}',
'{javascript}',
'{class}',
@@ -284,8 +285,8 @@ public function toHtml() {
'{toggle}',
'{moveup}',
'{movedown}',
- );
- $htmlElements = array(
+ ];
+ $htmlElements = [
$this->getElementCss(FALSE),
$this->getElementJs(FALSE),
$this->_tableAttributes,
@@ -298,7 +299,7 @@ public function toHtml() {
$strHtmlToggle,
$strHtmlMoveUp,
$strHtmlMoveDown,
- );
+ ];
$strHtml = str_replace($placeHolders, $htmlElements, $strHtml);
diff --git a/CRM/Core/QuickForm/NestedAdvMultiSelect.php b/CRM/Core/QuickForm/NestedAdvMultiSelect.php
index fb691c339469..791ef9ef2477 100644
--- a/CRM/Core/QuickForm/NestedAdvMultiSelect.php
+++ b/CRM/Core/QuickForm/NestedAdvMultiSelect.php
@@ -1,7 +1,7 @@
$val) {
$arr[$key] = $val;
}
diff --git a/CRM/Core/Reference/Basic.php b/CRM/Core/Reference/Basic.php
index 797d5832ab9d..a3e1fe73f8a7 100644
--- a/CRM/Core/Reference/Basic.php
+++ b/CRM/Core/Reference/Basic.php
@@ -83,9 +83,9 @@ public function findReferences($targetDao) {
if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists($this->getReferenceTable(), 'id')) {
$select = '*';
}
- $params = array(
- 1 => array($targetDao->$targetColumn, 'String'),
- );
+ $params = [
+ 1 => [$targetDao->$targetColumn, 'String'],
+ ];
$sql = <<getReferenceTable()}
@@ -104,22 +104,22 @@ public function findReferences($targetDao) {
*/
public function getReferenceCount($targetDao) {
$targetColumn = $this->getTargetKey();
- $params = array(
- 1 => array($targetDao->$targetColumn, 'String'),
- );
+ $params = [
+ 1 => [$targetDao->$targetColumn, 'String'],
+ ];
$sql = <<getReferenceTable()}
WHERE {$this->getReferenceKey()} = %1
EOS;
- return array(
- 'name' => implode(':', array('sql', $this->getReferenceTable(), $this->getReferenceKey())),
+ return [
+ 'name' => implode(':', ['sql', $this->getReferenceTable(), $this->getReferenceKey()]),
'type' => get_class($this),
'table' => $this->getReferenceTable(),
'key' => $this->getReferenceKey(),
'count' => CRM_Core_DAO::singleValueQuery($sql, $params),
- );
+ ];
}
}
diff --git a/CRM/Core/Reference/Dynamic.php b/CRM/Core/Reference/Dynamic.php
index 64fc790ebc34..6c5ba398ca1e 100644
--- a/CRM/Core/Reference/Dynamic.php
+++ b/CRM/Core/Reference/Dynamic.php
@@ -28,12 +28,12 @@ public function findReferences($targetDao) {
$refColumn = $this->getReferenceKey();
$targetColumn = $this->getTargetKey();
- $params = array(
- 1 => array($targetDao->$targetColumn, 'String'),
+ $params = [
+ 1 => [$targetDao->$targetColumn, 'String'],
// If anyone complains about $targetDao::getTableName(), then could use
// "{get_class($targetDao)}::getTableName();"
- 2 => array($targetDao::getTableName(), 'String'),
- );
+ 2 => [$targetDao::getTableName(), 'String'],
+ ];
$sql = <<getTargetKey();
- $params = array(
- 1 => array($targetDao->$targetColumn, 'String'),
+ $params = [
+ 1 => [$targetDao->$targetColumn, 'String'],
// If anyone complains about $targetDao::getTableName(), then could use
// "{get_class($targetDao)}::getTableName();"
- 2 => array($targetDao::getTableName(), 'String'),
- );
+ 2 => [$targetDao::getTableName(), 'String'],
+ ];
$sql = <<getTypeColumn()} = %2
EOS;
- return array(
- 'name' => implode(':', array('sql', $this->getReferenceTable(), $this->getReferenceKey())),
+ return [
+ 'name' => implode(':', ['sql', $this->getReferenceTable(), $this->getReferenceKey()]),
'type' => get_class($this),
'table' => $this->getReferenceTable(),
'key' => $this->getReferenceKey(),
'count' => CRM_Core_DAO::singleValueQuery($sql, $params),
- );
+ ];
}
}
diff --git a/CRM/Core/Reference/Interface.php b/CRM/Core/Reference/Interface.php
index 09e0a0ba6dbf..f1bcaff6d26e 100644
--- a/CRM/Core/Reference/Interface.php
+++ b/CRM/Core/Reference/Interface.php
@@ -4,6 +4,7 @@
* Interface CRM_Core_Reference_Interface
*/
interface CRM_Core_Reference_Interface {
+
public function getReferenceTable();
public function getReferenceKey();
diff --git a/CRM/Core/Region.php b/CRM/Core/Region.php
index 77b3e6065b2a..a9f9e13b71ae 100644
--- a/CRM/Core/Region.php
+++ b/CRM/Core/Region.php
@@ -26,21 +26,21 @@ public static function &instance($name, $autocreate = TRUE) {
*
* @var string
*/
- var $_name;
+ public $_name;
/**
* List of snippets to inject within region
*
* @var array; e.g. $this->_snippets[3]['type'] = 'template';
*/
- var $_snippets;
+ public $_snippets;
/**
* Whether the snippets array has been sorted
*
* @var boolean
*/
- var $_isSorted;
+ public $_isSorted;
/**
* @param string $name
@@ -51,15 +51,15 @@ public function __construct($name) {
civicrm_smarty_register_string_resource();
$this->_name = $name;
- $this->_snippets = array();
+ $this->_snippets = [];
// Placeholder which represents any of the default content generated by the main Smarty template
- $this->add(array(
+ $this->add([
'name' => 'default',
'type' => 'markup',
'markup' => '',
'weight' => 0,
- ));
+ ]);
$this->_isSorted = TRUE;
}
@@ -103,12 +103,12 @@ public function __construct($name) {
* @return array
*/
public function add($snippet) {
- static $types = array('markup', 'template', 'callback', 'scriptUrl', 'script', 'jquery', 'style', 'styleUrl');
- $defaults = array(
+ static $types = ['markup', 'template', 'callback', 'scriptUrl', 'script', 'jquery', 'style', 'styleUrl'];
+ $defaults = [
'region' => $this->_name,
'weight' => 1,
'disabled' => FALSE,
- );
+ ];
$snippet += $defaults;
if (!isset($snippet['type'])) {
foreach ($types as $type) {
@@ -166,7 +166,7 @@ public function render($default, $allowCmsOverride = TRUE) {
$cms = CRM_Core_Config::singleton()->userSystem;
if (!$this->_isSorted) {
- uasort($this->_snippets, array('CRM_Core_Region', '_cmpSnippet'));
+ uasort($this->_snippets, ['CRM_Core_Region', '_cmpSnippet']);
$this->_isSorted = TRUE;
}
@@ -223,7 +223,7 @@ public function render($default, $allowCmsOverride = TRUE) {
default:
require_once 'CRM/Core/Error.php';
CRM_Core_Error::fatal(ts('Snippet type %1 is unrecognized',
- array(1 => $snippet['type'])));
+ [1 => $snippet['type']]));
}
}
return $html;
diff --git a/CRM/Core/Report/Excel.php b/CRM/Core/Report/Excel.php
index a2a35da94678..b4b38c2fa29b 100644
--- a/CRM/Core/Report/Excel.php
+++ b/CRM/Core/Report/Excel.php
@@ -1,9 +1,9 @@
bool)
*/
- protected $addedCoreResources = array();
+ protected $addedCoreResources = [];
/**
* @var array ($regionName => bool)
*/
- protected $addedCoreStyles = array();
+ protected $addedCoreStyles = [];
/**
* @var string a value to append to JS/CSS URLs to coerce cache resets
@@ -110,18 +111,12 @@ class CRM_Core_Resources {
* New copy of the manager.
* @return CRM_Core_Resources
*/
- static public function singleton(CRM_Core_Resources $instance = NULL) {
+ public static function singleton(CRM_Core_Resources $instance = NULL) {
if ($instance !== NULL) {
self::$_singleton = $instance;
}
if (self::$_singleton === NULL) {
- $sys = CRM_Extension_System::singleton();
- $cache = Civi::cache('js_strings');
- self::$_singleton = new CRM_Core_Resources(
- $sys->getMapper(),
- $cache,
- CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
- );
+ self::$_singleton = Civi::service('resources');
}
return self::$_singleton;
}
@@ -163,13 +158,13 @@ public function __construct($extMapper, $cache, $cacheCodeKey = NULL) {
*/
public function addPermissions($permNames) {
$permNames = (array) $permNames;
- $perms = array();
+ $perms = [];
foreach ($permNames as $permName) {
$perms[$permName] = CRM_Core_Permission::check($permName);
}
- return $this->addSetting(array(
+ return $this->addSetting([
'permissions' => $perms,
- ));
+ ]);
}
/**
@@ -211,13 +206,13 @@ public function addScriptFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $regi
* @return CRM_Core_Resources
*/
public function addScriptUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
- CRM_Core_Region::instance($region)->add(array(
- 'name' => $url,
- 'type' => 'scriptUrl',
- 'scriptUrl' => $url,
- 'weight' => $weight,
- 'region' => $region,
- ));
+ CRM_Core_Region::instance($region)->add([
+ 'name' => $url,
+ 'type' => 'scriptUrl',
+ 'scriptUrl' => $url,
+ 'weight' => $weight,
+ 'region' => $region,
+ ]);
return $this;
}
@@ -233,13 +228,13 @@ public function addScriptUrl($url, $weight = self::DEFAULT_WEIGHT, $region = sel
* @return CRM_Core_Resources
*/
public function addScript($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
- CRM_Core_Region::instance($region)->add(array(
+ CRM_Core_Region::instance($region)->add([
// 'name' => automatic
- 'type' => 'script',
- 'script' => $code,
- 'weight' => $weight,
- 'region' => $region,
- ));
+ 'type' => 'script',
+ 'script' => $code,
+ 'weight' => $weight,
+ 'region' => $region,
+ ]);
return $this;
}
@@ -260,9 +255,9 @@ public function addScript($code, $weight = self::DEFAULT_WEIGHT, $region = self:
* @return CRM_Core_Resources
*/
public function addVars($nameSpace, $vars) {
- $existing = CRM_Utils_Array::value($nameSpace, CRM_Utils_Array::value('vars', $this->settings), array());
+ $existing = CRM_Utils_Array::value($nameSpace, CRM_Utils_Array::value('vars', $this->settings), []);
$vars = $this->mergeSettings($existing, $vars);
- $this->addSetting(array('vars' => array($nameSpace => $vars)));
+ $this->addSetting(['vars' => [$nameSpace => $vars]]);
return $this;
}
@@ -279,12 +274,12 @@ public function addSetting($settings) {
if (!$this->addedSettings) {
$region = self::isAjaxMode() ? 'ajax-snippet' : 'html-header';
$resources = $this;
- CRM_Core_Region::instance($region)->add(array(
+ CRM_Core_Region::instance($region)->add([
'callback' => function (&$snippet, &$html) use ($resources) {
$html .= "\n" . $resources->renderSetting();
},
'weight' => -100000,
- ));
+ ]);
$this->addedSettings = TRUE;
}
return $this;
@@ -298,7 +293,7 @@ public function addSetting($settings) {
*/
public function addSettingsFactory($callable) {
// Make sure our callback has been registered
- $this->addSetting(array());
+ $this->addSetting([]);
$this->settingsFactories[] = $callable;
return $this;
}
@@ -381,18 +376,18 @@ public function renderSetting() {
*/
public function addString($text, $domain = 'civicrm') {
foreach ((array) $text as $str) {
- $translated = ts($str, array(
- 'domain' => ($domain == 'civicrm') ? NULL : array($domain, NULL),
+ $translated = ts($str, [
+ 'domain' => ($domain == 'civicrm') ? NULL : [$domain, NULL],
'raw' => TRUE,
- ));
+ ]);
// We only need to push this string to client if the translation
// is actually different from the original
if ($translated != $str) {
$bucket = $domain == 'civicrm' ? 'strings' : 'strings::' . $domain;
- $this->addSetting(array(
- $bucket => array($str => $translated),
- ));
+ $this->addSetting([
+ $bucket => [$str => $translated],
+ ]);
}
}
return $this;
@@ -427,13 +422,13 @@ public function addStyleFile($ext, $file, $weight = self::DEFAULT_WEIGHT, $regio
* @return CRM_Core_Resources
*/
public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
- CRM_Core_Region::instance($region)->add(array(
- 'name' => $url,
- 'type' => 'styleUrl',
- 'styleUrl' => $url,
- 'weight' => $weight,
- 'region' => $region,
- ));
+ CRM_Core_Region::instance($region)->add([
+ 'name' => $url,
+ 'type' => 'styleUrl',
+ 'styleUrl' => $url,
+ 'weight' => $weight,
+ 'region' => $region,
+ ]);
return $this;
}
@@ -449,13 +444,13 @@ public function addStyleUrl($url, $weight = self::DEFAULT_WEIGHT, $region = self
* @return CRM_Core_Resources
*/
public function addStyle($code, $weight = self::DEFAULT_WEIGHT, $region = self::DEFAULT_REGION) {
- CRM_Core_Region::instance($region)->add(array(
+ CRM_Core_Region::instance($region)->add([
// 'name' => automatic
- 'type' => 'style',
- 'style' => $code,
- 'weight' => $weight,
- 'region' => $region,
- ));
+ 'type' => 'style',
+ 'style' => $code,
+ 'weight' => $weight,
+ 'region' => $region,
+ ]);
return $this;
}
@@ -526,8 +521,11 @@ public function getUrl($ext, $file = NULL, $addCacheCode = FALSE) {
public function glob($ext, $patterns, $flags = NULL) {
$path = $this->getPath($ext);
$patterns = (array) $patterns;
- $files = array();
+ $files = [];
foreach ($patterns as $pattern) {
+ if (preg_match(';^(assetBuilder|ext)://;', $pattern)) {
+ $files[] = $pattern;
+ }
if (CRM_Utils_File::isAbsolute($pattern)) {
// Absolute path.
$files = array_merge($files, (array) glob($pattern, $flags));
@@ -537,7 +535,8 @@ public function glob($ext, $patterns, $flags = NULL) {
$files = array_merge($files, (array) glob("$path/$pattern", $flags));
}
}
- sort($files); // Deterministic order.
+ // Deterministic order.
+ sort($files);
$files = array_unique($files);
return array_map(function ($file) use ($path) {
return CRM_Utils_File::relativize($file, "$path/");
@@ -594,26 +593,24 @@ public function addCoreResources($region = 'html-header') {
if (is_array($item)) {
$this->addSetting($item);
}
- elseif (substr($item, -2) == 'js') {
+ elseif (strpos($item, '.css')) {
+ $this->isFullyFormedUrl($item) ? $this->addStyleUrl($item, -100, $region) : $this->addStyleFile('civicrm', $item, -100, $region);
+ }
+ elseif ($this->isFullyFormedUrl($item)) {
+ $this->addScriptUrl($item, $jsWeight++, $region);
+ }
+ else {
// Don't bother looking for ts() calls in packages, there aren't any
$translate = (substr($item, 0, 3) == 'js/');
$this->addScriptFile('civicrm', $item, $jsWeight++, $region, $translate);
}
- else {
- $this->addStyleFile('civicrm', $item, -100, $region);
- }
}
-
- $tsLocale = CRM_Core_I18n::getLocale();
- // Dynamic localization script
- $this->addScriptUrl(CRM_Utils_System::url('civicrm/ajax/l10n-js/' . $tsLocale, array('r' => $this->getCacheCode())), $jsWeight++, $region);
-
// Add global settings
- $settings = array(
- 'config' => array(
+ $settings = [
+ 'config' => [
'isFrontend' => $config->userFrameworkFrontend,
- ),
- );
+ ],
+ ];
// Disable profile creation if user lacks permission
if (!CRM_Core_Permission::check('edit all contacts') && !CRM_Core_Permission::check('add contacts')) {
$settings['config']['entityRef']['contactCreate'] = FALSE;
@@ -678,16 +675,17 @@ public function getStrings() {
public static function outputLocalizationJS() {
CRM_Core_Page_AJAX::setJsHeaders();
$config = CRM_Core_Config::singleton();
- $vars = array(
+ $vars = [
'moneyFormat' => json_encode(CRM_Utils_Money::format(1234.56)),
'contactSearch' => json_encode($config->includeEmailInName ? ts('Start typing a name or email...') : ts('Start typing a name...')),
'otherSearch' => json_encode(ts('Enter search term...')),
- 'entityRef' => array(
- 'contactCreate' => CRM_Core_BAO_UFGroup::getCreateLinks(),
- 'filters' => self::getEntityRefFilters(),
- ),
+ 'entityRef' => self::getEntityRefMetadata(),
'ajaxPopupsEnabled' => self::singleton()->ajaxPopupsEnabled,
- );
+ 'allowAlertAutodismissal' => (bool) Civi::settings()->get('allow_alert_autodismissal'),
+ 'resourceCacheCode' => self::singleton()->getCacheCode(),
+ 'locale' => CRM_Core_I18n::getLocale(),
+ 'cid' => (int) CRM_Core_Session::getLoggedInContactID(),
+ ];
print CRM_Core_Smarty::singleton()->fetchWith('CRM/common/l10n.js.tpl', $vars);
CRM_Utils_System::civiExit();
}
@@ -705,7 +703,7 @@ public function coreResourceList($region) {
// Scripts needed by everyone, everywhere
// FIXME: This is too long; list needs finer-grained segmentation
- $items = array(
+ $items = [
"bower_components/jquery/dist/jquery.min.js",
"bower_components/jquery-ui/jquery-ui.min.js",
"bower_components/jquery-ui/themes/smoothness/jquery-ui.min.css",
@@ -722,29 +720,66 @@ public function coreResourceList($region) {
"bower_components/jquery-validation/dist/jquery.validate.min.js",
"packages/jquery/plugins/jquery.ui.datepicker.validation.min.js",
"js/Common.js",
+ "js/crm.datepicker.js",
"js/crm.ajax.js",
"js/wysiwyg/crm.wysiwyg.js",
+ ];
+
+ // Dynamic localization script
+ $items[] = $this->addCacheCode(
+ CRM_Utils_System::url('civicrm/ajax/l10n-js/' . CRM_Core_I18n::getLocale(),
+ ['cid' => CRM_Core_Session::getLoggedInContactID()], FALSE, NULL, FALSE)
);
+
// add wysiwyg editor
$editor = Civi::settings()->get('editor_id');
if ($editor == "CKEditor") {
CRM_Admin_Page_CKEditorConfig::setConfigDefault();
- $items[] = array(
- 'config' => array(
+ $items[] = [
+ 'config' => [
'wysisygScriptLocation' => Civi::paths()->getUrl("[civicrm.root]/js/wysiwyg/crm.ckeditor.js"),
'CKEditorCustomConfig' => CRM_Admin_Page_CKEditorConfig::getConfigUrl(),
- ),
- );
+ ],
+ ];
}
// These scripts are only needed by back-office users
if (CRM_Core_Permission::check('access CiviCRM')) {
$items[] = "packages/jquery/plugins/jquery.tableHeader.js";
- $items[] = "packages/jquery/plugins/jquery.menu.min.js";
- $items[] = "css/civicrmNavigation.css";
$items[] = "packages/jquery/plugins/jquery.notify.min.js";
}
+ $contactID = CRM_Core_Session::getLoggedInContactID();
+
+ // Menubar
+ $position = 'none';
+ if (
+ $contactID && !$config->userFrameworkFrontend
+ && CRM_Core_Permission::check('access CiviCRM')
+ && !@constant('CIVICRM_DISABLE_DEFAULT_MENU')
+ && !CRM_Core_Config::isUpgradeMode()
+ ) {
+ $position = Civi::settings()->get('menubar_position') ?: 'over-cms-menu';
+ }
+ if ($position !== 'none') {
+ $items[] = 'bower_components/smartmenus/dist/jquery.smartmenus.min.js';
+ $items[] = 'bower_components/smartmenus/dist/addons/keyboard/jquery.smartmenus.keyboard.min.js';
+ $items[] = 'js/crm.menubar.js';
+ $items[] = Civi::service('asset_builder')->getUrl('crm-menubar.css', [
+ 'color' => Civi::settings()->get('menubar_color'),
+ 'height' => 40,
+ 'breakpoint' => 768,
+ 'opacity' => .88,
+ ]);
+ $items[] = [
+ 'menubar' => [
+ 'position' => $position,
+ 'qfKey' => CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE),
+ 'cacheCode' => CRM_Core_BAO_Navigation::getCacheKey($contactID),
+ ],
+ ];
+ }
+
// JS for multilingual installations
if (!empty($config->languageLimit) && count($config->languageLimit) > 1 && CRM_Core_Permission::check('translate CiviCRM')) {
$items[] = "js/crm.multilingual.js";
@@ -761,7 +796,7 @@ public function coreResourceList($region) {
// Search for i18n file in order of specificity (try fr-CA, then fr)
list($lang) = explode('_', $tsLocale);
$path = "bower_components/jquery-ui/ui/i18n";
- foreach (array(str_replace('_', '-', $tsLocale), $lang) as $language) {
+ foreach ([str_replace('_', '-', $tsLocale), $lang] as $language) {
$localizationFile = "$path/datepicker-{$language}.js";
if ($this->getPath('civicrm', $localizationFile)) {
$items[] = $localizationFile;
@@ -781,93 +816,104 @@ public function coreResourceList($region) {
* is this page request an ajax snippet?
*/
public static function isAjaxMode() {
- if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), array(
- CRM_Core_Smarty::PRINT_SNIPPET,
- CRM_Core_Smarty::PRINT_NOFORM,
- CRM_Core_Smarty::PRINT_JSON,
- ))
+ if (in_array(CRM_Utils_Array::value('snippet', $_REQUEST), [
+ CRM_Core_Smarty::PRINT_SNIPPET,
+ CRM_Core_Smarty::PRINT_NOFORM,
+ CRM_Core_Smarty::PRINT_JSON,
+ ])
) {
return TRUE;
}
- return strpos(CRM_Utils_System::getUrlPath(), 'civicrm/ajax') === 0;
+ list($arg0, $arg1) = array_pad(explode('/', CRM_Utils_System::getUrlPath()), 2, '');
+ return ($arg0 === 'civicrm' && in_array($arg1, ['ajax', 'angularprofiles', 'asset']));
+ }
+
+ /**
+ * @param \Civi\Core\Event\GenericHookEvent $e
+ * @see \CRM_Utils_Hook::buildAsset()
+ */
+ public static function renderMenubarStylesheet(GenericHookEvent $e) {
+ if ($e->asset !== 'crm-menubar.css') {
+ return;
+ }
+ $e->mimeType = 'text/css';
+ $e->content = '';
+ $config = CRM_Core_Config::singleton();
+ $cms = strtolower($config->userFramework);
+ $cms = $cms === 'drupal' ? 'drupal7' : $cms;
+ $items = [
+ 'bower_components/smartmenus/dist/css/sm-core-css.css',
+ 'css/crm-menubar.css',
+ "css/menubar-$cms.css",
+ ];
+ foreach ($items as $item) {
+ $e->content .= file_get_contents(self::singleton()->getPath('civicrm', $item));
+ }
+ $color = $e->params['color'];
+ if (!CRM_Utils_Rule::color($color)) {
+ $color = Civi::settings()->getDefault('menubar_color');
+ }
+ $vars = [
+ 'resourceBase' => rtrim($config->resourceBase, '/'),
+ 'menubarHeight' => $e->params['height'] . 'px',
+ 'breakMin' => $e->params['breakpoint'] . 'px',
+ 'breakMax' => ($e->params['breakpoint'] - 1) . 'px',
+ 'menubarColor' => $color,
+ 'menuItemColor' => 'rgba(' . implode(', ', CRM_Utils_Color::getRgb($color)) . ", {$e->params['opacity']})",
+ 'highlightColor' => CRM_Utils_Color::getHighlight($color),
+ 'textColor' => CRM_Utils_Color::getContrast($color, '#333', '#ddd'),
+ ];
+ $vars['highlightTextColor'] = CRM_Utils_Color::getContrast($vars['highlightColor'], '#333', '#ddd');
+ foreach ($vars as $var => $val) {
+ $e->content = str_replace('$' . $var, $val, $e->content);
+ }
}
/**
* Provide a list of available entityRef filters.
- * @todo: move component filters into their respective components (e.g. CiviEvent)
*
* @return array
*/
- public static function getEntityRefFilters() {
- $filters = array();
+ public static function getEntityRefMetadata() {
+ $data = [
+ 'filters' => [],
+ 'links' => [],
+ ];
$config = CRM_Core_Config::singleton();
- if (in_array('CiviEvent', $config->enableComponents)) {
- $filters['event'] = array(
- array('key' => 'event_type_id', 'value' => ts('Event Type')),
- array(
- 'key' => 'start_date',
- 'value' => ts('Start Date'),
- 'options' => array(
- array('key' => '{">":"now"}', 'value' => ts('Upcoming')),
- array(
- 'key' => '{"BETWEEN":["now - 3 month","now"]}',
- 'value' => ts('Past 3 Months'),
- ),
- array(
- 'key' => '{"BETWEEN":["now - 6 month","now"]}',
- 'value' => ts('Past 6 Months'),
- ),
- array(
- 'key' => '{"BETWEEN":["now - 1 year","now"]}',
- 'value' => ts('Past Year'),
- ),
- ),
- ),
- );
- }
-
- $filters['activity'] = array(
- array('key' => 'activity_type_id', 'value' => ts('Activity Type')),
- array('key' => 'status_id', 'value' => ts('Activity Status')),
- );
-
- $filters['contact'] = array(
- array('key' => 'contact_type', 'value' => ts('Contact Type')),
- array('key' => 'group', 'value' => ts('Group'), 'entity' => 'group_contact'),
- array('key' => 'tag', 'value' => ts('Tag'), 'entity' => 'entity_tag'),
- array('key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'address'),
- array('key' => 'country', 'value' => ts('Country'), 'entity' => 'address'),
- array('key' => 'gender_id', 'value' => ts('Gender')),
- array('key' => 'is_deceased', 'value' => ts('Deceased')),
- array('key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'),
- array('key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'),
- array('key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'),
- );
+ $disabledComponents = [];
+ $dao = CRM_Core_DAO::executeQuery("SELECT name, namespace FROM civicrm_component");
+ while ($dao->fetch()) {
+ if (!in_array($dao->name, $config->enableComponents)) {
+ $disabledComponents[$dao->name] = $dao->namespace;
+ }
+ }
- if (in_array('CiviCase', $config->enableComponents)) {
- $filters['case'] = array(
- array(
- 'key' => 'case_id.case_type_id',
- 'value' => ts('Case Type'),
- 'entity' => 'Case',
- ),
- array(
- 'key' => 'case_id.status_id',
- 'value' => ts('Case Status'),
- 'entity' => 'Case',
- ),
- );
- foreach ($filters['contact'] as $filter) {
- $filter += array('entity' => 'contact');
- $filter['key'] = 'contact_id.' . $filter['key'];
- $filters['case'][] = $filter;
+ foreach (CRM_Core_DAO_AllCoreTables::daoToClass() as $entity => $daoName) {
+ // Skip DAOs of disabled components
+ foreach ($disabledComponents as $nameSpace) {
+ if (strpos($daoName, $nameSpace) === 0) {
+ continue 2;
+ }
+ }
+ $baoName = str_replace('_DAO_', '_BAO_', $daoName);
+ if (class_exists($baoName)) {
+ $filters = $baoName::getEntityRefFilters();
+ if ($filters) {
+ $data['filters'][$entity] = $filters;
+ }
+ if (is_callable([$baoName, 'getEntityRefCreateLinks'])) {
+ $createLinks = $baoName::getEntityRefCreateLinks();
+ if ($createLinks) {
+ $data['links'][$entity] = $createLinks;
+ }
+ }
}
}
- CRM_Utils_Hook::entityRefFilters($filters);
+ CRM_Utils_Hook::entityRefFilters($data['filters']);
- return $filters;
+ return $data;
}
/**
@@ -896,4 +942,15 @@ public function addCacheCode($url) {
return $url . $operator . 'r=' . $this->cacheCode;
}
+ /**
+ * Checks if the given URL is fully-formed
+ *
+ * @param string $url
+ *
+ * @return bool
+ */
+ public static function isFullyFormedUrl($url) {
+ return (substr($url, 0, 4) === 'http') || (substr($url, 0, 1) === '/');
+ }
+
}
diff --git a/CRM/Core/Resources/Strings.php b/CRM/Core/Resources/Strings.php
index b7398eab7f77..451d02dda28a 100644
--- a/CRM/Core/Resources/Strings.php
+++ b/CRM/Core/Resources/Strings.php
@@ -1,9 +1,9 @@
cache->get($bucket); // array($file => array(...strings...))
+ // array($file => array(...strings...))
+ $stringsByFile = $this->cache->get($bucket);
if (!$stringsByFile) {
- $stringsByFile = array();
+ $stringsByFile = [];
}
if (!isset($stringsByFile[$file])) {
if ($file && is_readable($file)) {
$stringsByFile[$file] = $this->extract($file, $format);
}
else {
- $stringsByFile[$file] = array();
+ $stringsByFile[$file] = [];
}
$this->cache->set($bucket, $stringsByFile);
}
diff --git a/CRM/Core/ScheduledJob.php b/CRM/Core/ScheduledJob.php
index 55aa94dc2c22..87ec71d94f27 100644
--- a/CRM/Core/ScheduledJob.php
+++ b/CRM/Core/ScheduledJob.php
@@ -1,9 +1,9 @@
apiParams = array('version' => $this->version);
+ $this->apiParams = ['version' => $this->version];
if (!empty($this->parameters)) {
$lines = explode("\n", $this->parameters);
@@ -91,9 +91,9 @@ public function saveLastRun($date = NULL) {
*/
public function clearScheduledRunDate() {
CRM_Core_DAO::executeQuery('UPDATE civicrm_job SET scheduled_run_date = NULL WHERE id = %1',
- array(
- '1' => array($this->id, 'Integer'),
- ));
+ [
+ '1' => [$this->id, 'Integer'],
+ ]);
}
/**
diff --git a/CRM/Core/SelectValues.php b/CRM/Core/SelectValues.php
index ece069395cb3..18af287821b7 100644
--- a/CRM/Core/SelectValues.php
+++ b/CRM/Core/SelectValues.php
@@ -1,9 +1,9 @@
ts('Yes'),
0 => ts('No'),
- );
+ ];
}
/**
@@ -55,11 +55,11 @@ public static function boolean() {
* @return array
*/
public static function pmf() {
- return array(
+ return [
'Both' => ts('Both'),
'HTML' => ts('HTML'),
'Text' => ts('Text'),
- );
+ ];
}
/**
@@ -68,14 +68,14 @@ public static function pmf() {
* @return array
*/
public static function privacy() {
- return array(
+ return [
'do_not_phone' => ts('Do not phone'),
'do_not_email' => ts('Do not email'),
'do_not_mail' => ts('Do not mail'),
'do_not_sms' => ts('Do not sms'),
'do_not_trade' => ts('Do not trade'),
'is_opt_out' => ts('No bulk emails (User Opt Out)'),
- );
+ ];
}
/**
@@ -98,11 +98,11 @@ public static function contactType() {
* @return array
*/
public static function unitList($unitType = NULL) {
- $unitList = array(
+ $unitList = [
'day' => ts('day'),
'month' => ts('month'),
'year' => ts('year'),
- );
+ ];
if ($unitType == 'duration') {
$unitList['lifetime'] = ts('lifetime');
}
@@ -124,10 +124,10 @@ public static function membershipTypeUnitList() {
* @return array
*/
public static function periodType() {
- return array(
+ return [
'rolling' => ts('Rolling'),
'fixed' => ts('Fixed'),
- );
+ ];
}
/**
@@ -136,12 +136,12 @@ public static function periodType() {
* @return array
*/
public static function emailSelectMethods() {
- return array(
+ return [
'automatic' => ts("Automatic"),
'location-only' => ts("Only send to email addresses assigned to the specified location"),
'location-prefer' => ts("Prefer email addresses assigned to the specified location"),
'location-exclude' => ts("Exclude email addresses assigned to the specified location"),
- );
+ ];
}
/**
@@ -150,10 +150,10 @@ public static function emailSelectMethods() {
* @return array
*/
public static function memberVisibility() {
- return array(
+ return [
'Public' => ts('Public'),
'Admin' => ts('Admin'),
- );
+ ];
}
/**
@@ -162,11 +162,11 @@ public static function memberVisibility() {
* @return array
*/
public static function memberAutoRenew() {
- return array(
+ return [
ts('No auto-renew option'),
ts('Give option, but not required'),
ts('Auto-renew required'),
- );
+ ];
}
/**
@@ -175,11 +175,11 @@ public static function memberAutoRenew() {
* @return array
*/
public static function eventDate() {
- return array(
+ return [
'start_date' => ts('start date'),
'end_date' => ts('end date'),
'join_date' => ts('member since'),
- );
+ ];
}
/**
@@ -188,7 +188,7 @@ public static function eventDate() {
* @return array
*/
public static function customHtmlType() {
- return array(
+ return [
'Text' => ts('Single-line input field (text or numeric)'),
'TextArea' => ts('Multi-line text box (textarea)'),
'Select' => ts('Drop-down (select list)'),
@@ -203,10 +203,9 @@ public static function customHtmlType() {
'RichTextEditor' => ts('Rich Text Editor'),
'Autocomplete-Select' => ts('Autocomplete-Select'),
'Multi-Select' => ts('Multi-Select'),
- 'AdvMulti-Select' => ts('AdvMulti-Select'),
'Link' => ts('Link'),
'ContactReference' => ts('Autocomplete-Select'),
- );
+ ];
}
/**
@@ -216,7 +215,7 @@ public static function customHtmlType() {
*
*/
public static function customGroupExtends() {
- $customGroupExtends = array(
+ $customGroupExtends = [
'Activity' => ts('Activities'),
'Relationship' => ts('Relationships'),
'Contribution' => ts('Contributions'),
@@ -232,9 +231,9 @@ public static function customGroupExtends() {
'Grant' => ts('Grants'),
'Address' => ts('Addresses'),
'Campaign' => ts('Campaigns'),
- );
+ ];
$contactTypes = self::contactType();
- $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
+ $contactTypes = !empty($contactTypes) ? ['Contact' => 'Contacts'] + $contactTypes : [];
$extendObjs = CRM_Core_OptionGroup::values('cg_extend_objects');
$customGroupExtends = array_merge($contactTypes, $customGroupExtends, $extendObjs);
return $customGroupExtends;
@@ -246,11 +245,11 @@ public static function customGroupExtends() {
* @return array
*/
public static function customGroupStyle() {
- return array(
+ return [
'Tab' => ts('Tab'),
'Inline' => ts('Inline'),
'Tab with table' => ts('Tab with table'),
- );
+ ];
}
/**
@@ -259,16 +258,16 @@ public static function customGroupStyle() {
* @return array
*/
public static function ufGroupTypes() {
- $ufGroupType = array(
+ $ufGroupType = [
'Profile' => ts('Standalone Form or Directory'),
'Search Profile' => ts('Search Views'),
- );
+ ];
if (CRM_Core_Config::singleton()->userSystem->supports_form_extensions) {
- $ufGroupType += array(
+ $ufGroupType += [
'User Registration' => ts('Drupal User Registration'),
'User Account' => ts('View/Edit Drupal User Account'),
- );
+ ];
}
return $ufGroupType;
}
@@ -279,11 +278,11 @@ public static function ufGroupTypes() {
* @return array
*/
public static function groupContactStatus() {
- return array(
+ return [
'Added' => ts('Added'),
'Removed' => ts('Removed'),
'Pending' => ts('Pending'),
- );
+ ];
}
/**
@@ -292,10 +291,10 @@ public static function groupContactStatus() {
* @return array
*/
public static function groupType() {
- return array(
+ return [
'query' => ts('Dynamic'),
'static' => ts('Static'),
- );
+ ];
}
/**
@@ -307,17 +306,17 @@ public static function groupType() {
* date format (QF format)
* @param null $minOffset
* @param null $maxOffset
- *
+ * @param string $context
* @return array
* the date array
*/
public static function date($type = NULL, $format = NULL, $minOffset = NULL, $maxOffset = NULL, $context = 'display') {
// These options are deprecated. Definitely not used in datepicker. Possibly not even in jcalendar+addDateTime.
- $date = array(
+ $date = [
'addEmptyOption' => TRUE,
'emptyOptionText' => ts('- select -'),
'emptyOptionValue' => '',
- );
+ ];
if ($format) {
$date['format'] = $format;
@@ -367,11 +366,11 @@ public static function date($type = NULL, $format = NULL, $minOffset = NULL, $ma
* @return array
*/
public static function ufVisibility() {
- return array(
+ return [
'User and User Admin Only' => ts('User and User Admin Only'),
'Public Pages' => ts('Expose Publicly'),
'Public Pages and Listings' => ts('Expose Publicly and for Listings'),
- );
+ ];
}
/**
@@ -380,10 +379,10 @@ public static function ufVisibility() {
* @return array
*/
public static function groupVisibility() {
- return array(
+ return [
'User and User Admin Only' => ts('User and User Admin Only'),
'Public Pages' => ts('Public Pages'),
- );
+ ];
}
/**
@@ -392,7 +391,7 @@ public static function groupVisibility() {
* @return array
*/
public static function mailingComponents() {
- return array(
+ return [
'Header' => ts('Header'),
'Footer' => ts('Footer'),
'Reply' => ts('Reply Auto-responder'),
@@ -401,7 +400,7 @@ public static function mailingComponents() {
'Welcome' => ts('Welcome Message'),
'Unsubscribe' => ts('Unsubscribe Message'),
'Resubscribe' => ts('Resubscribe Message'),
- );
+ ];
}
/**
@@ -410,7 +409,7 @@ public static function mailingComponents() {
* @return array
*/
public function getHours() {
- $hours = array();
+ $hours = [];
for ($i = 0; $i <= 6; $i++) {
$hours[$i] = $i;
}
@@ -423,7 +422,7 @@ public function getHours() {
* @return array
*/
public function getMinutes() {
- $minutes = array();
+ $minutes = [];
for ($i = 0; $i < 60; $i = $i + 15) {
$minutes[$i] = $i;
}
@@ -439,7 +438,7 @@ public function getMinutes() {
public static function mapProvider() {
static $map = NULL;
if (!$map) {
- $map = array('' => '- select -') + CRM_Utils_System::getPluginList('templates/CRM/Contact/Form/Task/Map', ".tpl");
+ $map = ['' => '- select -'] + CRM_Utils_System::getPluginList('templates/CRM/Contact/Form/Task/Map', ".tpl");
}
return $map;
}
@@ -453,7 +452,7 @@ public static function mapProvider() {
public static function geoProvider() {
static $geo = NULL;
if (!$geo) {
- $geo = array('' => '- select -') + CRM_Utils_System::getPluginList('CRM/Utils/Geocode');
+ $geo = ['' => '- select -'] + CRM_Utils_System::getPluginList('CRM/Utils/Geocode');
}
return $geo;
}
@@ -467,7 +466,7 @@ public static function geoProvider() {
public static function addressProvider() {
static $addr = NULL;
if (!$addr) {
- $addr = CRM_Utils_System::getPluginList('CRM/Utils/Address', '.php', array('BatchUpdate'));
+ $addr = array_merge(['' => '- select -'], CRM_Utils_System::getPluginList('CRM/Utils/Address', '.php', ['BatchUpdate']));
}
return $addr;
}
@@ -478,7 +477,7 @@ public static function addressProvider() {
* @return array
*/
public static function mailingTokens() {
- return array(
+ return [
'{action.unsubscribe}' => ts('Unsubscribe via email'),
'{action.unsubscribeUrl}' => ts('Unsubscribe via web page'),
'{action.resubscribe}' => ts('Resubscribe via email'),
@@ -495,7 +494,7 @@ public static function mailingTokens() {
'{mailing.name}' => ts('Mailing name'),
'{mailing.group}' => ts('Mailing group'),
'{mailing.viewUrl}' => ts('Mailing permalink'),
- );
+ ];
}
/**
@@ -504,12 +503,12 @@ public static function mailingTokens() {
* @return array
*/
public static function activityTokens() {
- return array(
+ return [
'{activity.activity_id}' => ts('Activity ID'),
'{activity.subject}' => ts('Activity Subject'),
'{activity.details}' => ts('Activity Details'),
'{activity.activity_date_time}' => ts('Activity Date Time'),
- );
+ ];
}
/**
@@ -518,7 +517,7 @@ public static function activityTokens() {
* @return array
*/
public static function membershipTokens() {
- return array(
+ return [
'{membership.id}' => ts('Membership ID'),
'{membership.status}' => ts('Membership Status'),
'{membership.type}' => ts('Membership Type'),
@@ -526,7 +525,7 @@ public static function membershipTokens() {
'{membership.join_date}' => ts('Membership Join Date'),
'{membership.end_date}' => ts('Membership End Date'),
'{membership.fee}' => ts('Membership Fee'),
- );
+ ];
}
/**
@@ -535,7 +534,7 @@ public static function membershipTokens() {
* @return array
*/
public static function eventTokens() {
- return array(
+ return [
'{event.event_id}' => ts('Event ID'),
'{event.title}' => ts('Event Title'),
'{event.start_date}' => ts('Event Start Date'),
@@ -550,7 +549,7 @@ public static function eventTokens() {
'{event.info_url}' => ts('Event Info URL'),
'{event.registration_url}' => ts('Event Registration URL'),
'{event.balance}' => ts('Event Balance'),
- );
+ ];
}
/**
@@ -559,7 +558,7 @@ public static function eventTokens() {
* @return array
*/
public static function contributionTokens() {
- return array_merge(array(
+ return array_merge([
'{contribution.contribution_id}' => ts('Contribution ID'),
'{contribution.total_amount}' => ts('Total Amount'),
'{contribution.fee_amount}' => ts('Fee Amount'),
@@ -583,7 +582,7 @@ public static function contributionTokens() {
//'{contribution.address_id}' => ts('Address ID'),
'{contribution.check_number}' => ts('Check Number'),
'{contribution.campaign}' => ts('Contribution Campaign'),
- ), CRM_Utils_Token::getCustomFieldTokens('contribution', TRUE));
+ ], CRM_Utils_Token::getCustomFieldTokens('contribution', TRUE));
}
/**
@@ -594,17 +593,17 @@ public static function contributionTokens() {
public static function contactTokens() {
static $tokens = NULL;
if (!$tokens) {
- $additionalFields = array(
- 'checksum' => array('title' => ts('Checksum')),
- 'contact_id' => array('title' => ts('Internal Contact ID')),
- );
+ $additionalFields = [
+ 'checksum' => ['title' => ts('Checksum')],
+ 'contact_id' => ['title' => ts('Internal Contact ID')],
+ ];
$exportFields = array_merge(CRM_Contact_BAO_Contact::exportableFields(), $additionalFields);
$values = array_merge(array_keys($exportFields));
unset($values[0]);
//FIXME:skipping some tokens for time being.
- $skipTokens = array(
+ $skipTokens = [
'is_bulkmail',
'group',
'tag',
@@ -615,9 +614,9 @@ public static function contactTokens() {
'legal_identifier',
'contact_sub_type',
'user_unique_id',
- );
+ ];
- $customFields = CRM_Core_BAO_CustomField::getFields(array('Individual', 'Address'));
+ $customFields = CRM_Core_BAO_CustomField::getFields(['Individual', 'Address']);
$legacyTokenNames = array_flip(CRM_Utils_Token::legacyContactTokens());
foreach ($values as $val) {
@@ -640,7 +639,7 @@ public static function contactTokens() {
}
// Get all the hook tokens too
- $hookTokens = array();
+ $hookTokens = [];
CRM_Utils_Hook::tokens($hookTokens);
foreach ($hookTokens as $tokenValues) {
foreach ($tokenValues as $key => $value) {
@@ -675,7 +674,7 @@ public static function participantTokens() {
unset($values[0]);
// skipping some tokens for time being.
- $skipTokens = array(
+ $skipTokens = [
'event_id',
'participant_is_pay_later',
'participant_is_test',
@@ -684,7 +683,7 @@ public static function participantTokens() {
'participant_campaign_id',
'participant_status',
'participant_discount_name',
- );
+ ];
$customFields = CRM_Core_BAO_CustomField::getFields('Participant');
@@ -729,7 +728,7 @@ public static function caseTokens($caseTypeId = NULL) {
* @return array
*/
public static function getDatePluginInputFormats() {
- $dateInputFormats = array(
+ $dateInputFormats = [
"mm/dd/yy" => ts('mm/dd/yyyy (12/31/2009)'),
"dd/mm/yy" => ts('dd/mm/yyyy (31/12/2009)'),
"yy-mm-dd" => ts('yyyy-mm-dd (2009-12-31)'),
@@ -745,7 +744,7 @@ public static function getDatePluginInputFormats() {
"yy-mm" => ts('yyyy-mm (2009-12)'),
'M yy' => ts('M yyyy (Dec 2009)'),
"yy" => ts('yyyy (2009)'),
- );
+ ];
/*
Year greater than 2000 get wrong result for following format
@@ -769,10 +768,10 @@ public static function getDatePluginInputFormats() {
* @return array
*/
public static function getTimeFormats() {
- return array(
+ return [
'1' => ts('12 Hours'),
'2' => ts('24 Hours'),
- );
+ ];
}
/**
@@ -784,7 +783,7 @@ public static function getTimeFormats() {
* @return array
*/
public static function getNumericOptions($start = 0, $end = 10) {
- $numericOptions = array();
+ $numericOptions = [];
for ($i = $start; $i <= $end; $i++) {
$numericOptions[$i] = $i;
}
@@ -797,10 +796,10 @@ public static function getNumericOptions($start = 0, $end = 10) {
* @return array
*/
public static function getBarcodeTypes() {
- return array(
+ return [
'barcode' => ts('Linear (1D)'),
'qrcode' => ts('QR code'),
- );
+ ];
}
/**
@@ -809,11 +808,11 @@ public static function getBarcodeTypes() {
* @return array
*/
public static function getDedupeRuleTypes() {
- return array(
+ return [
'Unsupervised' => ts('Unsupervised'),
'Supervised' => ts('Supervised'),
'General' => ts('General'),
- );
+ ];
}
/**
@@ -822,10 +821,10 @@ public static function getDedupeRuleTypes() {
* @return array
*/
public static function getCampaignGroupTypes() {
- return array(
+ return [
'Include' => ts('Include'),
'Exclude' => ts('Exclude'),
- );
+ ];
}
/**
@@ -834,12 +833,12 @@ public static function getCampaignGroupTypes() {
* @return array
*/
public static function getSubscriptionHistoryMethods() {
- return array(
+ return [
'Admin' => ts('Admin'),
'Email' => ts('Email'),
'Web' => ts('Web'),
'API' => ts('API'),
- );
+ ];
}
/**
@@ -848,12 +847,12 @@ public static function getSubscriptionHistoryMethods() {
* @return array
*/
public static function getPremiumUnits() {
- return array(
+ return [
'day' => ts('Day'),
'week' => ts('Week'),
'month' => ts('Month'),
'year' => ts('Year'),
- );
+ ];
}
/**
@@ -862,13 +861,13 @@ public static function getPremiumUnits() {
* @return array
*/
public static function getExtensionTypes() {
- return array(
+ return [
'payment' => ts('Payment'),
'search' => ts('Search'),
'report' => ts('Report'),
'module' => ts('Module'),
'sms' => ts('SMS'),
- );
+ ];
}
/**
@@ -877,7 +876,7 @@ public static function getExtensionTypes() {
* @return array
*/
public static function getJobFrequency() {
- return array(
+ return [
// CRM-17669
'Yearly' => ts('Yearly'),
'Quarter' => ts('Quarterly'),
@@ -887,7 +886,7 @@ public static function getJobFrequency() {
'Daily' => ts('Daily'),
'Hourly' => ts('Hourly'),
'Always' => ts('Every time cron job is run'),
- );
+ ];
}
/**
@@ -896,7 +895,7 @@ public static function getJobFrequency() {
* @return array
*/
public static function getSearchBuilderOperators($fieldType = NULL) {
- $builderOperators = array(
+ return [
'=' => '=',
'!=' => '≠',
'>' => '>',
@@ -912,18 +911,7 @@ public static function getSearchBuilderOperators($fieldType = NULL) {
'IS NOT EMPTY' => ts('Not Empty'),
'IS NULL' => ts('Is Null'),
'IS NOT NULL' => ts('Not Null'),
- );
- if ($fieldType) {
- switch ($fieldType) {
- case CRM_Utils_Type::T_STRING:
- unset($builderOperators['>']);
- unset($builderOperators['<']);
- unset($builderOperators['>=']);
- unset($builderOperators['<=']);
- break;
- }
- }
- return $builderOperators;
+ ];
}
/**
@@ -932,30 +920,29 @@ public static function getSearchBuilderOperators($fieldType = NULL) {
* @return array
*/
public static function getProfileGroupType() {
- $profileGroupType = array(
+ $profileGroupType = [
'Activity' => ts('Activities'),
'Contribution' => ts('Contributions'),
'Membership' => ts('Memberships'),
'Participant' => ts('Participants'),
- );
+ ];
$contactTypes = self::contactType();
- $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
+ $contactTypes = !empty($contactTypes) ? ['Contact' => 'Contacts'] + $contactTypes : [];
$profileGroupType = array_merge($contactTypes, $profileGroupType);
return $profileGroupType;
}
-
/**
* Word replacement match type.
*
* @return array
*/
public static function getWordReplacementMatchType() {
- return array(
+ return [
'exactMatch' => ts('Exact Match'),
'wildcardMatch' => ts('Wildcard Match'),
- );
+ ];
}
/**
@@ -964,11 +951,11 @@ public static function getWordReplacementMatchType() {
* @return array
*/
public static function getMailingGroupTypes() {
- return array(
+ return [
'Include' => ts('Include'),
'Exclude' => ts('Exclude'),
'Base' => ts('Base'),
- );
+ ];
}
/**
@@ -977,35 +964,35 @@ public static function getMailingGroupTypes() {
* @return array
*/
public static function getMailingJobStatus() {
- return array(
+ return [
'Scheduled' => ts('Scheduled'),
'Running' => ts('Running'),
'Complete' => ts('Complete'),
'Paused' => ts('Paused'),
'Canceled' => ts('Canceled'),
- );
+ ];
}
/**
* @return array
*/
public static function billingMode() {
- return array(
+ return [
CRM_Core_Payment::BILLING_MODE_FORM => 'form',
CRM_Core_Payment::BILLING_MODE_BUTTON => 'button',
CRM_Core_Payment::BILLING_MODE_NOTIFY => 'notify',
- );
+ ];
}
/**
* @return array
*/
public static function contributeMode() {
- return array(
+ return [
CRM_Core_Payment::BILLING_MODE_FORM => 'direct',
CRM_Core_Payment::BILLING_MODE_BUTTON => 'directIPN',
CRM_Core_Payment::BILLING_MODE_NOTIFY => 'notify',
- );
+ ];
}
/**
@@ -1019,13 +1006,13 @@ public static function getRecurringFrequencyUnits($count = 1) {
// @todo this used to refer to the 'recur_frequency_unit' option_values which
// is for recurring payments and probably not good to re-use for recurring entities.
// If something other than a hard-coded list is desired, add a new option_group.
- return array(
- 'hour' => ts('hour', array('plural' => 'hours', 'count' => $count)),
- 'day' => ts('day', array('plural' => 'days', 'count' => $count)),
- 'week' => ts('week', array('plural' => 'weeks', 'count' => $count)),
- 'month' => ts('month', array('plural' => 'months', 'count' => $count)),
- 'year' => ts('year', array('plural' => 'years', 'count' => $count)),
- );
+ return [
+ 'hour' => ts('hour', ['plural' => 'hours', 'count' => $count]),
+ 'day' => ts('day', ['plural' => 'days', 'count' => $count]),
+ 'week' => ts('week', ['plural' => 'weeks', 'count' => $count]),
+ 'month' => ts('month', ['plural' => 'months', 'count' => $count]),
+ 'year' => ts('year', ['plural' => 'years', 'count' => $count]),
+ ];
}
/**
@@ -1034,7 +1021,7 @@ public static function getRecurringFrequencyUnits($count = 1) {
* @return array
*/
public static function getRelativeDateTerms() {
- return array(
+ return [
'previous' => ts('Previous'),
'previous_2' => ts('Previous 2'),
'previous_before' => ts('Prior to Previous'),
@@ -1050,7 +1037,7 @@ public static function getRelativeDateTerms() {
'starting' => ts('Upcoming'),
'less' => ts('To End of'),
'next' => ts('Next'),
- );
+ ];
}
/**
@@ -1059,14 +1046,14 @@ public static function getRelativeDateTerms() {
* @return array
*/
public static function getRelativeDateUnits() {
- return array(
+ return [
'year' => ts('Years'),
'fiscal_year' => ts('Fiscal Years'),
'quarter' => ts('Quarters'),
'month' => ts('Months'),
'week' => ts('Weeks'),
'day' => ts('Days'),
- );
+ ];
}
/**
@@ -1075,12 +1062,12 @@ public static function getRelativeDateUnits() {
* @return array
*/
public static function documentFormat() {
- return array(
+ return [
'pdf' => ts('Portable Document Format (.pdf)'),
'docx' => ts('MS Word (.docx)'),
'odt' => ts('Open Office (.odt)'),
'html' => ts('Webpage (.html)'),
- );
+ ];
}
/**
@@ -1089,10 +1076,10 @@ public static function documentFormat() {
* @return array
*/
public static function documentApplicationType() {
- return array(
+ return [
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'odt' => 'application/vnd.oasis.opendocument.text',
- );
+ ];
}
/**
@@ -1101,11 +1088,74 @@ public static function documentApplicationType() {
* @return array
*/
public static function activityTextOptions() {
- return array(
+ return [
2 => ts('Details Only'),
3 => ts('Subject Only'),
6 => ts('Both'),
- );
+ ];
+ }
+
+ /**
+ * Relationship permissions
+ *
+ * @return array
+ */
+ public static function getPermissionedRelationshipOptions() {
+ return [
+ CRM_Contact_BAO_Relationship::NONE => ts('None'),
+ CRM_Contact_BAO_Relationship::VIEW => ts('View only'),
+ CRM_Contact_BAO_Relationship::EDIT => ts('View and update'),
+ ];
+ }
+
+ /**
+ * Get option values for dashboard entries (used for 'how many events to display on dashboard').
+ *
+ * @return array
+ * Dashboard entries options - in practice [-1 => 'Show All', 10 => 10, 20 => 20, ... 100 => 100].
+ */
+ public static function getDashboardEntriesCount() {
+ $optionValues = [];
+ $optionValues[-1] = ts('show all');
+ for ($i = 10; $i <= 100; $i += 10) {
+ $optionValues[$i] = $i;
+ }
+ return $optionValues;
+ }
+
+ /**
+ * Dropdown options for quicksearch in the menu
+ *
+ * @return array
+ */
+ public static function quicksearchOptions() {
+ $includeEmail = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']);
+ $options = [
+ 'sort_name' => $includeEmail ? ts('Name/Email') : ts('Name'),
+ 'contact_id' => ts('Contact ID'),
+ 'external_identifier' => ts('External ID'),
+ 'first_name' => ts('First Name'),
+ 'last_name' => ts('Last Name'),
+ 'email' => ts('Email'),
+ 'phone_numeric' => ts('Phone'),
+ 'street_address' => ts('Street Address'),
+ 'city' => ts('City'),
+ 'postal_code' => ts('Postal Code'),
+ 'job_title' => ts('Job Title'),
+ ];
+ $custom = civicrm_api3('CustomField', 'get', [
+ 'return' => ['name', 'label', 'custom_group_id.title'],
+ 'custom_group_id.extends' => ['IN' => ['Contact', 'Individual', 'Organization', 'Household']],
+ 'data_type' => ['NOT IN' => ['ContactReference', 'Date', 'File']],
+ 'custom_group_id.is_active' => 1,
+ 'is_active' => 1,
+ 'is_searchable' => 1,
+ 'options' => ['sort' => ['custom_group_id.weight', 'weight'], 'limit' => 0],
+ ]);
+ foreach ($custom['values'] as $field) {
+ $options['custom_' . $field['name']] = $field['custom_group_id.title'] . ': ' . $field['label'];
+ }
+ return $options;
}
}
diff --git a/CRM/Core/Selector/API.php b/CRM/Core/Selector/API.php
index 2f38c2d65331..b49cd2c20f12 100644
--- a/CRM/Core/Selector/API.php
+++ b/CRM/Core/Selector/API.php
@@ -1,9 +1,9 @@
getColumnHeaders(NULL);
if (!isset($this->_order)) {
- $this->_order = array();
+ $this->_order = [];
$start = 2;
$firstElementNotFound = TRUE;
if (!empty($columnHeaders)) {
diff --git a/CRM/Core/Selector/Controller.php b/CRM/Core/Selector/Controller.php
index 7de6ad443ac3..a64a7eabeb68 100644
--- a/CRM/Core/Selector/Controller.php
+++ b/CRM/Core/Selector/Controller.php
@@ -1,9 +1,9 @@
_sortID .= '_u';
}
- $params = array(
+ $params = [
'pageID' => $this->_pageID,
- );
+ ];
// let the constructor initialize this, should happen only once
if (!isset(self::$_template)) {
@@ -339,8 +340,8 @@ public function run() {
// output requires paging/sorting capability
$rows = self::getRows($this);
CRM_Utils_Hook::searchColumns($contextName, $columnHeaders, $rows, $this);
- $reorderedHeaders = array();
- $noWeightHeaders = array();
+ $reorderedHeaders = [];
+ $noWeightHeaders = [];
foreach ($columnHeaders as $key => $columnHeader) {
// So far only contribution selector sets weight, so just use key if not.
// Extension writers will need to fix other getColumnHeaders (or add a wrapper)
diff --git a/CRM/Core/Session.php b/CRM/Core/Session.php
index 8514c5a80dd1..8aa67bf9ca92 100644
--- a/CRM/Core/Session.php
+++ b/CRM/Core/Session.php
@@ -1,9 +1,9 @@
userSystem->is_drupal && function_exists('drupal_session_start')) {
+ if (CRM_Core_Config::singleton()->userSystem->is_drupal && function_exists('drupal_session_start')) {
// https://issues.civicrm.org/jira/browse/CRM-14356
if (!(isset($GLOBALS['lazy_session']) && $GLOBALS['lazy_session'] == TRUE)) {
drupal_session_start();
}
- $_SESSION = array();
+ $_SESSION = [];
}
else {
session_start();
@@ -137,7 +137,7 @@ public function initialize($isRead = FALSE) {
if (!isset($this->_session[$this->_key]) ||
!is_array($this->_session[$this->_key])
) {
- $this->_session[$this->_key] = array();
+ $this->_session[$this->_key] = [];
}
}
@@ -151,11 +151,11 @@ public function reset($all = 1) {
$this->initialize();
// to make certain we clear it, first initialize it to empty
- $this->_session[$this->_key] = array();
+ $this->_session[$this->_key] = [];
unset($this->_session[$this->_key]);
}
else {
- $this->_session = array();
+ $this->_session = [];
}
}
@@ -176,7 +176,7 @@ public function createScope($prefix, $isRead = FALSE) {
}
if (empty($this->_session[$this->_key][$prefix])) {
- $this->_session[$this->_key][$prefix] = array();
+ $this->_session[$this->_key][$prefix] = [];
}
}
@@ -286,7 +286,7 @@ public function getVars(&$vars, $prefix = '') {
$values = &$this->_session[$this->_key];
}
else {
- $values = CRM_Core_BAO_Cache::getItem('CiviCRM Session', "CiviCRM_{$prefix}");
+ $values = Civi::cache('session')->get("CiviCRM_{$prefix}");
}
if ($values) {
@@ -466,16 +466,20 @@ public function getStatus($reset = FALSE) {
* defaults to 10 seconds for most messages, 5 if it has a title but no body,
* or 0 for errors or messages containing links
*/
- public static function setStatus($text, $title = '', $type = 'alert', $options = array()) {
+ public static function setStatus($text, $title = '', $type = 'alert', $options = []) {
// make sure session is initialized, CRM-8120
$session = self::singleton();
$session->initialize();
+ // Sanitize any HTML we're displaying. This helps prevent reflected XSS in error messages.
+ $text = CRM_Utils_String::purifyHTML($text);
+ $title = CRM_Utils_String::purifyHTML($title);
+
// default options
- $options += array('unique' => TRUE);
+ $options += ['unique' => TRUE];
if (!isset(self::$_singleton->_session[self::$_singleton->_key]['status'])) {
- self::$_singleton->_session[self::$_singleton->_key]['status'] = array();
+ self::$_singleton->_session[self::$_singleton->_key]['status'] = [];
}
if ($text || $title) {
if ($options['unique']) {
@@ -486,12 +490,12 @@ public static function setStatus($text, $title = '', $type = 'alert', $options =
}
}
unset($options['unique']);
- self::$_singleton->_session[self::$_singleton->_key]['status'][] = array(
+ self::$_singleton->_session[self::$_singleton->_key]['status'][] = [
'text' => $text,
'title' => $title,
'type' => $type,
'options' => $options ? $options : NULL,
- );
+ ];
}
}
@@ -502,7 +506,7 @@ public static function setStatus($text, $title = '', $type = 'alert', $options =
*/
public static function registerAndRetrieveSessionObjects($names) {
if (!is_array($names)) {
- $names = array($names);
+ $names = [$names];
}
if (!self::$_managedNames) {
@@ -558,7 +562,7 @@ public function getLoggedInContactDisplayName() {
if (!$userContactID) {
return '';
}
- return civicrm_api3('Contact', 'getvalue', array('id' => $userContactID, 'return' => 'display_name'));
+ return civicrm_api3('Contact', 'getvalue', ['id' => $userContactID, 'return' => 'display_name']);
}
/**
diff --git a/CRM/Core/ShowHideBlocks.php b/CRM/Core/ShowHideBlocks.php
index f0ef493e4589..ca66329ca81c 100644
--- a/CRM/Core/ShowHideBlocks.php
+++ b/CRM/Core/ShowHideBlocks.php
@@ -1,9 +1,9 @@
_show = $show;
}
else {
- $this->_show = array();
+ $this->_show = [];
}
if (!empty($hide)) {
$this->_hide = $hide;
}
else {
- $this->_hide = array();
+ $this->_hide = [];
}
}
@@ -178,11 +179,11 @@ public static function linkHtml($name, $href, $text, $js) {
* @return array
*/
public static function links(&$form, $prefix, $showLinkText, $hideLinkText, $assign = TRUE) {
- $showCode = "cj('#id_{$prefix}').show(); cj('#id_{$prefix}_show').hide();";
- $hideCode = "cj('#id_{$prefix}').hide(); cj('#id_{$prefix}_show').show(); return false;";
+ $showCode = "if(event.preventDefault) event.preventDefault(); else event.returnValue = false; cj('#id_{$prefix}').show(); cj('#id_{$prefix}_show').hide();";
+ $hideCode = "if(event.preventDefault) event.preventDefault(); else event.returnValue = false; cj('#id_{$prefix}').hide(); cj('#id_{$prefix}_show').show();";
self::setIcons();
- $values = array();
+ $values = [];
$values['show'] = self::linkHtml("${prefix}_show", "#${prefix}_hide", self::$_showIcon . $showLinkText, "onclick=\"$showCode\"");
$values['hide'] = self::linkHtml("${prefix}_hide", "#${prefix}", self::$_hideIcon . $hideLinkText, "onclick=\"$hideCode\"");
@@ -215,7 +216,7 @@ public static function links(&$form, $prefix, $showLinkText, $hideLinkText, $ass
* The hide block string.
*/
public function linksForArray(&$form, $index, $maxIndex, $prefix, $showLinkText, $hideLinkText, $elementType = NULL, $hideLink = NULL) {
- $showHidePrefix = str_replace(array("]", "["), array("", "_"), $prefix);
+ $showHidePrefix = str_replace(["]", "["], ["", "_"], $prefix);
$showHidePrefix = "id_" . $showHidePrefix;
if ($index == $maxIndex) {
$showCode = $hideCode = "return false;";
@@ -240,18 +241,18 @@ public function linksForArray(&$form, $index, $maxIndex, $prefix, $showLinkText,
self::setIcons();
if ($elementType) {
$form->addElement('link', "${prefix}[${index}][show]", NULL, "#${prefix}_${index}", self::$_showIcon . $showLinkText,
- array('onclick' => "cj('#${prefix}_${index}_show').hide(); cj('#${prefix}_${index}').show();" . $showCode)
+ ['onclick' => "cj('#${prefix}_${index}_show').hide(); cj('#${prefix}_${index}').show();" . $showCode]
);
$form->addElement('link', "${prefix}[${index}][hide]", NULL, "#${prefix}_${index}", self::$_hideIcon . $hideLinkText,
- array('onclick' => "cj('#${prefix}_${index}').hide(); cj('#${prefix}_${index}_show').show();" . $hideCode)
+ ['onclick' => "cj('#${prefix}_${index}').hide(); cj('#${prefix}_${index}_show').show();" . $hideCode]
);
}
else {
$form->addElement('link', "${prefix}[${index}][show]", NULL, "#${prefix}_${index}", self::$_showIcon . $showLinkText,
- array('onclick' => "cj('#{$showHidePrefix}_{$index}_show').hide(); cj('#{$showHidePrefix}_{$index}').show();" . $showCode)
+ ['onclick' => "cj('#{$showHidePrefix}_{$index}_show').hide(); cj('#{$showHidePrefix}_{$index}').show();" . $showCode]
);
$form->addElement('link', "${prefix}[${index}][hide]", NULL, "#${prefix}_${index}", self::$_hideIcon . $hideLinkText,
- array('onclick' => "cj('#{$showHidePrefix}_{$index}').hide(); cj('#{$showHidePrefix}_{$index}_show').show();" . $hideCode)
+ ['onclick' => "cj('#{$showHidePrefix}_{$index}').hide(); cj('#{$showHidePrefix}_{$index}_show').show();" . $hideCode]
);
}
}
diff --git a/CRM/Core/Smarty.php b/CRM/Core/Smarty.php
index 258f1abb472d..06b05313e3c3 100644
--- a/CRM/Core/Smarty.php
+++ b/CRM/Core/Smarty.php
@@ -1,9 +1,9 @@
mixed $value) a list of variables ot save temporarily
*/
- private $backupFrames = array();
+ private $backupFrames = [];
/**
* Class constructor.
@@ -90,7 +90,7 @@ private function initialize() {
$config = CRM_Core_Config::singleton();
if (isset($config->customTemplateDir) && $config->customTemplateDir) {
- $this->template_dir = array_merge(array($config->customTemplateDir),
+ $this->template_dir = array_merge([$config->customTemplateDir],
$config->templateDir
);
}
@@ -134,10 +134,10 @@ private function initialize() {
$pluginsDir = __DIR__ . DIRECTORY_SEPARATOR . 'Smarty' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR;
if ($customPluginsDir) {
- $this->plugins_dir = array($customPluginsDir, $smartyDir . 'plugins', $pluginsDir);
+ $this->plugins_dir = [$customPluginsDir, $smartyDir . 'plugins', $pluginsDir];
}
else {
- $this->plugins_dir = array($smartyDir . 'plugins', $pluginsDir);
+ $this->plugins_dir = [$smartyDir . 'plugins', $pluginsDir];
}
// add the session and the config here
@@ -151,10 +151,10 @@ private function initialize() {
// CRM-7163 hack: we don’t display langSwitch on upgrades anyway
if (!CRM_Core_Config::isUpgradeMode()) {
- $this->assign('langSwitch', CRM_Core_I18n::languages(TRUE));
+ $this->assign('langSwitch', CRM_Core_I18n::uiLanguages());
}
- $this->register_function('crmURL', array('CRM_Utils_System', 'crmURL'));
+ $this->register_function('crmURL', ['CRM_Utils_System', 'crmURL']);
$this->load_filter('pre', 'resetExtScope');
$this->assign('crmPermissions', new CRM_Core_Smarty_Permissions());
@@ -259,7 +259,7 @@ public function addTemplateDir($path) {
array_unshift($this->template_dir, $path);
}
else {
- $this->template_dir = array($path, $this->template_dir);
+ $this->template_dir = [$path, $this->template_dir];
}
}
@@ -283,7 +283,7 @@ public function addTemplateDir($path) {
*/
public function pushScope($vars) {
$oldVars = $this->get_template_vars();
- $backupFrame = array();
+ $backupFrame = [];
foreach ($vars as $key => $value) {
$backupFrame[$key] = isset($oldVars[$key]) ? $oldVars[$key] : NULL;
}
diff --git a/CRM/Core/Smarty/Permissions.php b/CRM/Core/Smarty/Permissions.php
index 9e2f35b00629..47229be3949a 100644
--- a/CRM/Core/Smarty/Permissions.php
+++ b/CRM/Core/Smarty/Permissions.php
@@ -4,6 +4,7 @@
* Class CRM_Core_Smarty_Permissions
*/
class CRM_Core_Smarty_Permissions {
+
/**
* non-static adapter for CRM_Core_Permission::check
* @param $offset
diff --git a/CRM/Core/Smarty/plugins/block.crmButton.php b/CRM/Core/Smarty/plugins/block.crmButton.php
index 91b747854c25..30074e9b098e 100644
--- a/CRM/Core/Smarty/plugins/block.crmButton.php
+++ b/CRM/Core/Smarty/plugins/block.crmButton.php
@@ -1,9 +1,9 @@
FALSE));
+ $params['href'] = CRM_Utils_System::crmURL($params + ['h' => FALSE]);
}
// Always add class 'button' - fixme probably should be crm-button
$params['class'] = empty($params['class']) ? 'button' : 'button ' . $params['class'];
diff --git a/CRM/Core/Smarty/plugins/block.edit.php b/CRM/Core/Smarty/plugins/block.edit.php
index e847debc1cf1..ae66c2bcaaf9 100644
--- a/CRM/Core/Smarty/plugins/block.edit.php
+++ b/CRM/Core/Smarty/plugins/block.edit.php
@@ -1,9 +1,9 @@
* @author Michal Mach
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*/
diff --git a/CRM/Core/Smarty/plugins/block.htxt.php b/CRM/Core/Smarty/plugins/block.htxt.php
index 0107d8d792da..be78a1d86f05 100644
--- a/CRM/Core/Smarty/plugins/block.htxt.php
+++ b/CRM/Core/Smarty/plugins/block.htxt.php
@@ -1,9 +1,9 @@
_tpl_vars['id']) {
+ if ($params['id'] == $smarty->_tpl_vars['id']) {
+ $smarty->assign('override_help_text', !empty($params['override']));
return $text;
}
else {
diff --git a/CRM/Core/Smarty/plugins/block.localize.php b/CRM/Core/Smarty/plugins/block.localize.php
index 6070a3c4a697..151356f72c18 100644
--- a/CRM/Core/Smarty/plugins/block.localize.php
+++ b/CRM/Core/Smarty/plugins/block.localize.php
@@ -1,9 +1,9 @@
_tpl_vars['locales'] as $locale) {
$line = $text;
if ($params['field']) {
diff --git a/CRM/Core/Smarty/plugins/block.serialize.php b/CRM/Core/Smarty/plugins/block.serialize.php
index d2559683fc02..3c00752fa6d9 100644
--- a/CRM/Core/Smarty/plugins/block.serialize.php
+++ b/CRM/Core/Smarty/plugins/block.serialize.php
@@ -1,9 +1,9 @@
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*/
diff --git a/CRM/Core/Smarty/plugins/block.ts.php b/CRM/Core/Smarty/plugins/block.ts.php
index 4dda02f5104d..051fc4bbea35 100644
--- a/CRM/Core/Smarty/plugins/block.ts.php
+++ b/CRM/Core/Smarty/plugins/block.ts.php
@@ -1,9 +1,9 @@
* @author Michal Mach
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*/
diff --git a/CRM/Core/Smarty/plugins/function.crmAPI.php b/CRM/Core/Smarty/plugins/function.crmAPI.php
index c8bd8889375c..38fd03892825 100644
--- a/CRM/Core/Smarty/plugins/function.crmAPI.php
+++ b/CRM/Core/Smarty/plugins/function.crmAPI.php
@@ -1,9 +1,9 @@
trigger_error("assign: missing 'entity' parameter");
return "crmAPI: missing 'entity' parameter";
}
- $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal'));
+ $errorScope = CRM_Core_TemporaryErrorScope::create(['CRM_Utils_REST', 'fatal']);
$entity = $params['entity'];
$action = CRM_Utils_Array::value('action', $params, 'get');
$params['sequential'] = CRM_Utils_Array::value('sequential', $params, 1);
@@ -55,7 +55,6 @@ function smarty_function_crmAPI($params, &$smarty) {
unset($errorScope);
if ($result === FALSE) {
$smarty->trigger_error("Unknown error");
- return;
}
if (!empty($result['is_error'])) {
diff --git a/CRM/Core/Smarty/plugins/function.crmAttributes.php b/CRM/Core/Smarty/plugins/function.crmAttributes.php
index 100936b5bb4a..91a40c24caa6 100644
--- a/CRM/Core/Smarty/plugins/function.crmAttributes.php
+++ b/CRM/Core/Smarty/plugins/function.crmAttributes.php
@@ -1,9 +1,9 @@
constant('CRM_Core_Action::' . $params['action']),
'entity_table' => $params['table'],
'entity_id' => $params['id'],
- ));
+ ]);
if ($link) {
return sprintf('%s',
diff --git a/CRM/Core/Smarty/plugins/function.crmDBTpl.php b/CRM/Core/Smarty/plugins/function.crmDBTpl.php
index 3ee41bda847e..ccffdee63a0e 100644
--- a/CRM/Core/Smarty/plugins/function.crmDBTpl.php
+++ b/CRM/Core/Smarty/plugins/function.crmDBTpl.php
@@ -1,9 +1,9 @@
userFrameworkFrontend) {
- $buildNavigation = FALSE;
- }
- if ($buildNavigation) {
- $session = CRM_Core_Session::singleton();
- $contactID = $session->get('userID');
- if ($contactID) {
- // These params force the browser to refresh the js file when switching user, domain, or language
- // We don't put them as a query string because some browsers will refuse to cache a page with a ? in the url
- // @see CRM_Admin_Page_AJAX::getNavigationMenu
- $lang = CRM_Core_I18n::getLocale();
- $domain = CRM_Core_Config::domainID();
- $key = CRM_Core_BAO_Navigation::getCacheKey($contactID);
- $src = CRM_Utils_System::url("civicrm/ajax/menujs/$contactID/$lang/$domain/$key");
- // CRM-15493 QFkey needed for quicksearch bar - must be unique on each page refresh so adding it directly to markup
- $qfKey = CRM_Core_Key::get('CRM_Contact_Controller_Search', TRUE);
- return '';
- }
- }
- return '';
-}
diff --git a/CRM/Core/Smarty/plugins/function.crmResPath.php b/CRM/Core/Smarty/plugins/function.crmResPath.php
index 139d4300a04e..5ae70638920c 100644
--- a/CRM/Core/Smarty/plugins/function.crmResPath.php
+++ b/CRM/Core/Smarty/plugins/function.crmResPath.php
@@ -1,9 +1,9 @@
CRM_Core_Resources::DEFAULT_WEIGHT,
'region' => CRM_Core_Resources::DEFAULT_REGION,
'ext' => 'civicrm',
- );
+ ];
if (array_key_exists('file', $params)) {
Civi::resources()->addScriptFile($params['ext'], $params['file'], $params['weight'], $params['region']);
diff --git a/CRM/Core/Smarty/plugins/function.crmSetting.php b/CRM/Core/Smarty/plugins/function.crmSetting.php
index 1c704844f28e..ffe9cd023652 100644
--- a/CRM/Core/Smarty/plugins/function.crmSetting.php
+++ b/CRM/Core/Smarty/plugins/function.crmSetting.php
@@ -1,9 +1,9 @@
trigger_error("Unknown error");
return NULL;
}
diff --git a/CRM/Core/Smarty/plugins/function.crmSigner.php b/CRM/Core/Smarty/plugins/function.crmSigner.php
index d9736ae44aad..b0c65185a913 100644
--- a/CRM/Core/Smarty/plugins/function.crmSigner.php
+++ b/CRM/Core/Smarty/plugins/function.crmSigner.php
@@ -1,9 +1,9 @@
get_template_vars();
@@ -83,7 +83,7 @@ function smarty_function_help($params, &$smarty) {
}
// Escape for html
- $title = htmlspecialchars(ts('%1 Help', array(1 => $name)));
+ $title = htmlspecialchars(ts('%1 Help', [1 => $name]));
// Escape for html and js
$name = htmlspecialchars(json_encode($name), ENT_QUOTES);
@@ -92,5 +92,5 @@ function smarty_function_help($params, &$smarty) {
foreach ($params as &$param) {
$param = is_bool($param) || is_numeric($param) ? (int) $param : (string) $param;
}
- return '';
+ return '';
}
diff --git a/CRM/Core/Smarty/plugins/function.isValueChange.php b/CRM/Core/Smarty/plugins/function.isValueChange.php
index 07ba0a688b6a..8c3116ea9b69 100644
--- a/CRM/Core/Smarty/plugins/function.isValueChange.php
+++ b/CRM/Core/Smarty/plugins/function.isValueChange.php
@@ -1,9 +1,9 @@
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*/
@@ -53,7 +53,7 @@
* @return NULL
*/
function smarty_function_isValueChange($params, &$smarty) {
- static $values = array();
+ static $values = [];
if (empty($params['key'])) {
$smarty->trigger_error("Missing required parameter, 'key', in isValueChange plugin.");
diff --git a/CRM/Core/Smarty/plugins/function.sectionTotal.php b/CRM/Core/Smarty/plugins/function.sectionTotal.php
index 222471218255..fee8b7d3811a 100644
--- a/CRM/Core/Smarty/plugins/function.sectionTotal.php
+++ b/CRM/Core/Smarty/plugins/function.sectionTotal.php
@@ -1,9 +1,9 @@
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*/
@@ -62,7 +62,7 @@ function smarty_function_sectionTotal($params, &$smarty) {
* Note: This array is created and assigned to the template in CRM_Report_Form::sectionTotals()
*/
- static $sectionValues = array();
+ static $sectionValues = [];
// move back in the stack, if necessary
if (count($sectionValues) > $params['depth']) {
diff --git a/CRM/Core/Smarty/plugins/function.simpleActivityContacts.php b/CRM/Core/Smarty/plugins/function.simpleActivityContacts.php
index 38e17dd41964..cb3ecf363a7d 100644
--- a/CRM/Core/Smarty/plugins/function.simpleActivityContacts.php
+++ b/CRM/Core/Smarty/plugins/function.simpleActivityContacts.php
@@ -38,28 +38,28 @@ function smarty_function_simpleActivityContacts($params, &$smarty) {
require_once 'api/api.php';
require_once 'api/v3/utils.php';
- $activity = civicrm_api('activity', 'getsingle', array(
+ $activity = civicrm_api('activity', 'getsingle', [
'version' => 3,
'id' => $params['activity_id'],
'return.target_contact_id' => 1,
'return.assignee_contact_id' => 1,
- ));
+ ]);
- $baseContactParams = array('version' => 3);
+ $baseContactParams = ['version' => 3];
foreach (explode(',', $params['return']) as $field) {
$baseContactParams['return.' . $field] = 1;
}
- foreach (array(
- 'target',
- 'assignee',
- ) as $role) {
- $contact = array();
+ foreach ([
+ 'target',
+ 'assignee',
+ ] as $role) {
+ $contact = [];
if (!empty($activity[$role . '_contact_id'])) {
$contact_id = array_shift($activity[$role . '_contact_id']);
- $contact = civicrm_api('contact', 'getsingle', $baseContactParams + array(
- 'contact_id' => $contact_id,
- ));
+ $contact = civicrm_api('contact', 'getsingle', $baseContactParams + [
+ 'contact_id' => $contact_id,
+ ]);
}
$smarty->assign($params[$role . '_var'], $contact);
}
diff --git a/CRM/Core/Smarty/plugins/modifier.colorContrast.php b/CRM/Core/Smarty/plugins/modifier.colorContrast.php
index 5e7c8b178fe3..dae7690154da 100644
--- a/CRM/Core/Smarty/plugins/modifier.colorContrast.php
+++ b/CRM/Core/Smarty/plugins/modifier.colorContrast.php
@@ -1,9 +1,9 @@
register_resource('string', array(
- 'civicrm_smarty_resource_string_get_template',
- 'civicrm_smarty_resource_string_get_timestamp',
- 'civicrm_smarty_resource_string_get_secure',
- 'civicrm_smarty_resource_string_get_trusted',
- )
- );
+ $template->register_resource('string', [
+ 'civicrm_smarty_resource_string_get_template',
+ 'civicrm_smarty_resource_string_get_timestamp',
+ 'civicrm_smarty_resource_string_get_secure',
+ 'civicrm_smarty_resource_string_get_trusted',
+ ]);
}
diff --git a/CRM/Core/State.php b/CRM/Core/State.php
index 2c6194b1acd8..919f7f11b50a 100644
--- a/CRM/Core/State.php
+++ b/CRM/Core/State.php
@@ -1,9 +1,9 @@
_controller = &$controller;
$this->_action = $action;
- $this->_states = array();
+ $this->_states = [];
}
/**
@@ -262,7 +262,7 @@ public function addSequentialPages(&$pages) {
$this->_pages = &$pages;
$numPages = count($pages);
- $this->_pageNames = array();
+ $this->_pageNames = [];
foreach ($pages as $tempName => $value) {
if (!empty($value['className'])) {
$this->_pageNames[] = $tempName;
diff --git a/CRM/Core/TableHierarchy.php b/CRM/Core/TableHierarchy.php
index 43ad03333ec3..49a0955554ca 100644
--- a/CRM/Core/TableHierarchy.php
+++ b/CRM/Core/TableHierarchy.php
@@ -1,9 +1,9 @@
'01',
'civicrm_address' => '09',
'civicrm_county' => '10',
@@ -75,7 +75,7 @@ class CRM_Core_TableHierarchy {
'civicrm_mailing_event_opened' => '41',
'civicrm_mailing_event_reply' => '42',
'civicrm_mailing_event_trackable_url_open' => '43',
- );
+ ];
/**
* @return array
diff --git a/CRM/Core/Task.php b/CRM/Core/Task.php
new file mode 100644
index 000000000000..96724ea89fad
--- /dev/null
+++ b/CRM/Core/Task.php
@@ -0,0 +1,204 @@
+ The Task title,
+ * 'class' => The Task Form class name,
+ * 'result => Boolean. FIXME: Not sure what this is for
+ * ]
+ */
+ public static function tasks() {
+ CRM_Utils_Hook::searchTasks(static::$objectType, self::$_tasks);
+ asort(self::$_tasks);
+
+ return self::$_tasks;
+ }
+
+ /**
+ * These tasks are the core set of tasks that the user can perform
+ * on a contact / group of contacts
+ *
+ * @return array
+ * the set of tasks for a group of contacts
+ */
+ public static function taskTitles() {
+ static::tasks();
+
+ $titles = [];
+ foreach (self::$_tasks as $id => $value) {
+ $titles[$id] = $value['title'];
+ }
+
+ if (!CRM_Utils_Mail::validOutBoundMail()) {
+ unset($titles[self::TASK_EMAIL]);
+ unset($titles[self::CREATE_MAILING]);
+ }
+
+ // Users who do not have 'access deleted contacts' should NOT have the 'Delete Permanently' option in search result tasks
+ if (!CRM_Core_Permission::check('access deleted contacts') ||
+ !CRM_Core_Permission::check('delete contacts')
+ ) {
+ unset($titles[self::DELETE_PERMANENTLY]);
+ }
+ return $titles;
+ }
+
+ /**
+ * Show tasks selectively based on the permission level
+ * of the user
+ * This function should be overridden by the child class which would normally call parent::corePermissionedTaskTitles
+ *
+ * @param int $permission
+ * @param array $params
+ * "ssID: Saved Search ID": If !empty we are in saved search context
+ *
+ * @return array
+ * set of tasks that are valid for the user
+ */
+ public static function permissionedTaskTitles($permission, $params) {
+ return self::corePermissionedTaskTitles(self::tasks(), $permission, $params);
+ }
+
+ /**
+ * Show tasks selectively based on the permission level
+ * of the user
+ * This function should be called by permissionedTaskTitles in children
+ *
+ * @param array $tasks The array of tasks generated by permissionedTaskTitles
+ * @param int $permission
+ * @param array $params
+ * "ssID: Saved Search ID": If !empty we are in saved search context
+ *
+ * @return array
+ * set of tasks that are valid for the user
+ */
+ public static function corePermissionedTaskTitles($tasks, $permission, $params) {
+ // Only offer the "Update Smart Group" task if a smart group/saved search is already in play and we have edit permissions
+ if (!empty($params['ssID']) && ($permission == CRM_Core_Permission::EDIT)) {
+ $tasks[self::SAVE_SEARCH_UPDATE] = self::$_tasks[self::SAVE_SEARCH_UPDATE]['title'];
+ }
+ else {
+ unset($tasks[self::SAVE_SEARCH_UPDATE]);
+ }
+
+ asort($tasks);
+ return $tasks;
+ }
+
+ /**
+ * These tasks are the core set of tasks that the user can perform
+ * on participants
+ *
+ * @param int $value
+ *
+ * @return array
+ * the set of tasks for a group of participants
+ */
+ public static function getTask($value) {
+ static::tasks();
+
+ if (!CRM_Utils_Array::value($value, self::$_tasks)) {
+ // Children can specify a default task (eg. print), pick another if it is not valid.
+ $value = key(self::$_tasks);
+ }
+ return [
+ CRM_Utils_Array::value('class', self::$_tasks[$value]),
+ CRM_Utils_Array::value('result', self::$_tasks[$value]),
+ ];
+ }
+
+ /**
+ * Function to return the task information on basis of provided task's form name
+ *
+ * @param string $className
+ *
+ * @return array [ 0 => Task ID, 1 => Task Title ]
+ */
+ public static function getTaskAndTitleByClass($className) {
+ static::tasks();
+
+ foreach (self::$_tasks as $task => $value) {
+ if ((!empty($value['url']) || $task == self::TASK_EXPORT)
+ && ((is_array($value['class']) && in_array($className, $value['class']))
+ || ($value['class'] == $className))) {
+ return [$task, CRM_Utils_Array::value('title', $value)];
+ }
+ }
+ return [];
+ }
+
+}
diff --git a/CRM/Core/TemporaryErrorScope.php b/CRM/Core/TemporaryErrorScope.php
index 7f7849608366..d8853b8ef8cd 100644
--- a/CRM/Core/TemporaryErrorScope.php
+++ b/CRM/Core/TemporaryErrorScope.php
@@ -22,20 +22,20 @@
* safe to temporarily switch to exception
*/
class CRM_Core_TemporaryErrorScope {
- static $oldFrames;
+ public static $oldFrames;
/**
* @return CRM_Core_TemporaryErrorScope
*/
public static function useException() {
- return self::create(array('CRM_Core_Error', 'exceptionHandler'), 1);
+ return self::create(['CRM_Core_Error', 'exceptionHandler'], 1);
}
/**
* @return CRM_Core_TemporaryErrorScope
*/
public static function ignoreException() {
- return self::create(array('CRM_Core_Error', 'nullHandler'));
+ return self::create(['CRM_Core_Error', 'nullHandler']);
}
/**
@@ -45,11 +45,11 @@ public static function ignoreException() {
* @return CRM_Core_TemporaryErrorScope
*/
public static function create($callback, $modeException = NULL) {
- $newFrame = array(
+ $newFrame = [
'_PEAR_default_error_mode' => PEAR_ERROR_CALLBACK,
'_PEAR_default_error_options' => $callback,
'modeException' => $modeException,
- );
+ ];
return new CRM_Core_TemporaryErrorScope($newFrame);
}
@@ -70,11 +70,11 @@ public function __destruct() {
* Read the active error-handler settings
*/
public static function getActive() {
- return array(
+ return [
'_PEAR_default_error_mode' => $GLOBALS['_PEAR_default_error_mode'],
'_PEAR_default_error_options' => $GLOBALS['_PEAR_default_error_options'],
'modeException' => CRM_Core_Error::$modeException,
- );
+ ];
}
/**
diff --git a/CRM/Core/TestEntity.php b/CRM/Core/TestEntity.php
new file mode 100644
index 000000000000..ee288dea1a68
--- /dev/null
+++ b/CRM/Core/TestEntity.php
@@ -0,0 +1,58 @@
+ (c) 2007
* $Id$
*
@@ -95,6 +95,7 @@ class CRM_Core_Transaction {
/**
* Whether commit() has been called on this instance
* of CRM_Core_Transaction
+ * @var bool
*/
private $_pseudoCommitted = FALSE;
@@ -147,7 +148,7 @@ public function commit() {
/**
* @param $flag
*/
- static public function rollbackIfFalse($flag) {
+ public static function rollbackIfFalse($flag) {
$frame = \Civi\Core\Transaction\Manager::singleton()->getFrame();
if ($flag === FALSE && $frame !== NULL) {
$frame->setRollbackOnly();
@@ -203,7 +204,7 @@ public function run($callable) {
* callstack will not wind-down normally -- e.g. before
* a call to exit().
*/
- static public function forceRollbackIfEnabled() {
+ public static function forceRollbackIfEnabled() {
if (\Civi\Core\Transaction\Manager::singleton()->getFrame() !== NULL) {
\Civi\Core\Transaction\Manager::singleton()->forceRollback();
}
@@ -212,7 +213,7 @@ static public function forceRollbackIfEnabled() {
/**
* @return bool
*/
- static public function willCommit() {
+ public static function willCommit() {
$frame = \Civi\Core\Transaction\Manager::singleton()->getFrame();
return ($frame === NULL) ? TRUE : !$frame->isRollbackOnly();
}
@@ -220,7 +221,7 @@ static public function willCommit() {
/**
* Determine whether there is a pending transaction.
*/
- static public function isActive() {
+ public static function isActive() {
$frame = \Civi\Core\Transaction\Manager::singleton()->getFrame();
return ($frame !== NULL);
}
@@ -246,7 +247,7 @@ static public function isActive() {
* See php manual call_user_func_array for details.
* @param int $id
*/
- static public function addCallback($phase, $callback, $params = NULL, $id = NULL) {
+ public static function addCallback($phase, $callback, $params = NULL, $id = NULL) {
$frame = \Civi\Core\Transaction\Manager::singleton()->getBaseFrame();
$frame->addCallback($phase, $callback, $params, $id);
}
diff --git a/CRM/Core/xml/Menu/Activity.xml b/CRM/Core/xml/Menu/Activity.xml
index b45321992021..774be6105d79 100644
--- a/CRM/Core/xml/Menu/Activity.xml
+++ b/CRM/Core/xml/Menu/Activity.xml
@@ -7,7 +7,7 @@
CRM_Activity_Form_Activityaccess CiviCRMattachUpload=1
- action=add&context=standalone
+ action=add,context=standalonecivicrm/activity/view
diff --git a/CRM/Core/xml/Menu/Admin.xml b/CRM/Core/xml/Menu/Admin.xml
index f6dcf0c614c2..d23a10910bee 100644
--- a/CRM/Core/xml/Menu/Admin.xml
+++ b/CRM/Core/xml/Menu/Admin.xml
@@ -262,7 +262,7 @@
CRM_Admin_Page_MessageTemplatesCommunicationsadmin/small/template.png
- edit message templates
+ edit message templates;edit user-driven message templates;edit system workflow message templates30
@@ -270,7 +270,7 @@
Message TemplatesAdd/Edit Message TemplatesCRM_Admin_Form_MessageTemplates
- edit message templates
+ edit message templates;edit user-driven message templates;edit system workflow message templates262
@@ -563,7 +563,7 @@
civicrm/admin/setting/preferences/eventCiviEvent Component Settings
- CRM_Admin_Form_Preferences_Event
+ CRM_Admin_Form_Genericcivicrm/admin/setting/preferences/mailing
@@ -633,9 +633,9 @@
9000
- civicrm/ajax/menujs
- CRM_Admin_Page_AJAX::getNavigationMenu
- access CiviCRM
+ civicrm/ajax/navmenu
+ CRM_Admin_Page_AJAX::navMenu
+ access CiviCRMcivicrm/ajax/menutree
@@ -711,7 +711,7 @@
civicrm/sms/sendNew Mass SMSCRM_SMS_Controller_Send
- administer CiviCRM
+ send SMS1610
diff --git a/CRM/Core/xml/Menu/Contact.xml b/CRM/Core/xml/Menu/Contact.xml
index 092a67924b44..26bf51d30c0f 100644
--- a/CRM/Core/xml/Menu/Contact.xml
+++ b/CRM/Core/xml/Menu/Contact.xml
@@ -401,6 +401,7 @@
action=addActivitiesCRM_Contact_Form_Task_SMS
+ send SMScivicrm/ajax/contactrelationships
diff --git a/CRM/Core/xml/Menu/Misc.xml b/CRM/Core/xml/Menu/Misc.xml
index ba07d574c215..b043a121704e 100644
--- a/CRM/Core/xml/Menu/Misc.xml
+++ b/CRM/Core/xml/Menu/Misc.xml
@@ -17,6 +17,11 @@
Export Contacts0
+
+ civicrm/export/standalone
+ Export
+ CRM_Export_Controller_Standalone
+ civicrm/admin/options/acl_roleACL Roles
@@ -198,7 +203,7 @@
civicrm/recurringentity/previewCRM_Core_Page_RecurringEntityPreview
- access CiviCRM,access CiviEvent
+ access CiviCRMConfirm dates
diff --git a/CRM/Custom/Form/ChangeFieldType.php b/CRM/Custom/Form/ChangeFieldType.php
index 95c2eec22a0b..7e89f123826b 100644
--- a/CRM/Custom/Form/ChangeFieldType.php
+++ b/CRM/Custom/Form/ChangeFieldType.php
@@ -1,9 +1,9 @@
_values = array();
- $params = array('id' => $this->_id);
+ $this->_values = [];
+ $params = ['id' => $this->_id];
CRM_Core_BAO_CustomField::retrieve($params, $this->_values);
$this->_htmlTypeTransitions = self::fieldTypeTransitions(CRM_Utils_Array::value('data_type', $this->_values),
@@ -85,7 +87,7 @@ public function preProcess() {
$session->pushUserContext($url);
CRM_Utils_System::setTitle(ts('Change Field Type: %1',
- array(1 => $this->_values['label'])
+ [1 => $this->_values['label']]
));
}
@@ -99,7 +101,7 @@ public function buildQuickForm() {
$srcHtmlType = $this->add('select',
'src_html_type',
ts('Current HTML Type'),
- array($this->_values['html_type'] => $this->_values['html_type']),
+ [$this->_values['html_type'] => $this->_values['html_type']],
TRUE
);
@@ -111,25 +113,24 @@ public function buildQuickForm() {
$dstHtmlType = $this->add('select',
'dst_html_type',
ts('New HTML Type'),
- array(
+ [
'' => ts('- select -'),
- ) + $this->_htmlTypeTransitions,
+ ] + $this->_htmlTypeTransitions,
TRUE
);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Change Field Type'),
- 'isDefault' => TRUE,
- 'js' => array('onclick' => 'return checkCustomDataField();'),
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Change Field Type'),
+ 'isDefault' => TRUE,
+ 'js' => ['onclick' => 'return checkCustomDataField();'],
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -145,18 +146,17 @@ public function postProcess() {
'table_name'
);
- $singleValueOps = array(
+ $singleValueOps = [
'Text',
'Select',
'Radio',
'Autocomplete-Select',
- );
+ ];
- $mutliValueOps = array(
+ $mutliValueOps = [
'CheckBox',
'Multi-Select',
- 'AdvMulti-Select',
- );
+ ];
$srcHtmlType = $this->_values['html_type'];
$dstHtmlType = $params['dst_html_type'];
@@ -165,24 +165,21 @@ public function postProcess() {
$customField->id = $this->_id;
$customField->find(TRUE);
- if ($dstHtmlType == 'Text' && in_array($srcHtmlType, array(
- 'Select',
- 'Radio',
- 'Autocomplete-Select',
- ))
- ) {
+ if ($dstHtmlType == 'Text' && in_array($srcHtmlType, [
+ 'Select',
+ 'Radio',
+ 'Autocomplete-Select',
+ ])) {
$customField->option_group_id = "NULL";
CRM_Core_BAO_CustomField::checkOptionGroup($this->_values['option_group_id']);
}
if (in_array($srcHtmlType, $mutliValueOps) &&
- in_array($dstHtmlType, $singleValueOps)
- ) {
+ in_array($dstHtmlType, $singleValueOps)) {
$this->flattenToFirstValue($tableName, $this->_values['column_name']);
}
elseif (in_array($srcHtmlType, $singleValueOps) &&
- in_array($dstHtmlType, $mutliValueOps)
- ) {
+ in_array($dstHtmlType, $mutliValueOps)) {
$this->firstValueToFlatten($tableName, $this->_values['column_name']);
}
@@ -193,7 +190,7 @@ public function postProcess() {
CRM_Core_BAO_Cache::deleteGroup('contact fields');
CRM_Core_Session::setStatus(ts('Input type of custom field \'%1\' has been successfully changed to \'%2\'.',
- array(1 => $this->_values['label'], 2 => $dstHtmlType)
+ [1 => $this->_values['label'], 2 => $dstHtmlType]
), ts('Field Type Changed'), 'success');
}
@@ -210,18 +207,17 @@ public static function fieldTypeTransitions($dataType, $htmlType) {
return NULL;
}
- $singleValueOps = array(
+ $singleValueOps = [
'Text' => 'Text',
'Select' => 'Select',
'Radio' => 'Radio',
'Autocomplete-Select' => 'Autocomplete-Select',
- );
+ ];
- $mutliValueOps = array(
+ $mutliValueOps = [
'CheckBox' => 'CheckBox',
'Multi-Select' => 'Multi-Select',
- 'AdvMulti-Select' => 'AdvMulti-Select',
- );
+ ];
switch ($dataType) {
case 'String':
@@ -250,10 +246,10 @@ public static function fieldTypeTransitions($dataType, $htmlType) {
break;
case 'Memo':
- $ops = array(
+ $ops = [
'TextArea' => 'TextArea',
'RichTextEditor' => 'RichTextEditor',
- );
+ ];
if (in_array($htmlType, array_keys($ops))) {
unset($ops[$htmlType]);
return $ops;
@@ -280,10 +276,10 @@ public function firstValueToFlatten($table, $column) {
continue;
}
$value = CRM_Core_DAO::VALUE_SEPARATOR . $dao->{$column} . CRM_Core_DAO::VALUE_SEPARATOR;
- $params = array(
- 1 => array((string) $value, 'String'),
- 2 => array($dao->id, 'Integer'),
- );
+ $params = [
+ 1 => [(string) $value, 'String'],
+ 2 => [$dao->id, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($updateSql, $params);
}
}
@@ -301,10 +297,10 @@ public function flattenToFirstValue($table, $column) {
$dao = CRM_Core_DAO::executeQuery($selectSql);
while ($dao->fetch()) {
$values = self::explode($dao->{$column});
- $params = array(
- 1 => array((string) array_shift($values), 'String'),
- 2 => array($dao->id, 'Integer'),
- );
+ $params = [
+ 1 => [(string) array_shift($values), 'String'],
+ 2 => [$dao->id, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($updateSql, $params);
}
}
@@ -316,7 +312,7 @@ public function flattenToFirstValue($table, $column) {
*/
public static function explode($str) {
if (empty($str) || $str == CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::VALUE_SEPARATOR) {
- return array();
+ return [];
}
else {
return explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($str, CRM_Core_DAO::VALUE_SEPARATOR));
diff --git a/CRM/Custom/Form/CustomData.php b/CRM/Custom/Form/CustomData.php
index 83eaacb5c771..3cc0d279c8f4 100644
--- a/CRM/Custom/Form/CustomData.php
+++ b/CRM/Custom/Form/CustomData.php
@@ -1,9 +1,9 @@
getDefaultEntity() must be defined for the form class for this to work.
+ *
+ * If the postProcess form cannot use the api & instead uses a BAO function it will need.
+ * $params['custom'] = CRM_Core_BAO_CustomField::postProcess($submitted, $this->_id, $this->getDefaultEntity());
+ *
+ * @param CRM_Core_Form $form
+ * @param null|string $subType values stored in civicrm_custom_group.extends_entity_column_value
+ * e.g Student for contact type
+ * @param null|string $subName value in civicrm_custom_group.extends_entity_column_id
+ * @param null|int $groupCount number of entities that could have custom data
+ *
+ * @throws \CRM_Core_Exception
+ */
+ public static function addToForm(&$form, $subType = NULL, $subName = NULL, $groupCount = 1) {
+ $entityName = $form->getDefaultEntity();
+ $entityID = $form->getEntityId();
+ // FIXME: If the form has been converted to use entityFormTrait then getEntitySubTypeId() will exist.
+ // However, if it is only partially converted (ie. we've switched customdata to use CRM_Custom_Form_CustomData)
+ // it won't, so we check if we have a subtype before calling the function.
+ $entitySubType = NULL;
+ if ($subType) {
+ $entitySubType = $form->getEntitySubTypeId($subType);
+ }
+
+ if ($form->getAction() == CRM_Core_Action::VIEW) {
+ // Viewing custom data (Use with {include file="CRM/Custom/Page/CustomDataView.tpl"} in template)
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree($entityName, NULL, $entityID, 0, $entitySubType);
+ CRM_Core_BAO_CustomGroup::buildCustomDataView($form, $groupTree, FALSE, NULL, NULL, NULL, $entityID);
+ }
+ else {
+ // Editing custom data (Use with {include file="CRM/common/customDataBlock.tpl"} in template)
+ if (!empty($_POST['hidden_custom'])) {
+ self::preProcess($form, $subName, $entitySubType, $groupCount, $entityName, $entityID);
+ self::buildQuickForm($form);
+ self::setDefaultValues($form);
+ }
+ }
+ // need to assign custom data type and subtype to the template
+ $form->assign('customDataType', $entityName);
+ $form->assign('customDataSubType', $entitySubType);
+ $form->assign('entityID', $entityID);
+ }
+
/**
* @param CRM_Core_Form $form
* @param null|string $subName
@@ -46,6 +90,8 @@ class CRM_Custom_Form_CustomData {
* @param string $type
* @param null|int $entityID
* @param null $onlySubType
+ *
+ * @throws \CRM_Core_Exception
*/
public static function preProcess(
&$form, $subName = NULL, $subType = NULL,
@@ -127,7 +173,7 @@ public static function preProcess(
* @return array
*/
public static function setDefaultValues(&$form) {
- $defaults = array();
+ $defaults = [];
CRM_Core_BAO_CustomGroup::setDefaults($form->_groupTree, $defaults, FALSE, FALSE, $form->get('action'));
return $defaults;
}
@@ -186,11 +232,11 @@ public static function setGroupTree(&$form, $subType, $gid, $onlySubType = NULL,
foreach ($keys as $key) {
$form->_groupTree[$key] = $groupTree[$key];
}
- return array($form, $groupTree);
+ return [$form, $groupTree];
}
else {
$form->_groupTree = $groupTree;
- return array($form, $groupTree);
+ return [$form, $groupTree];
}
}
diff --git a/CRM/Custom/Form/CustomDataByType.php b/CRM/Custom/Form/CustomDataByType.php
index 811daa557351..c88a29fb1622 100644
--- a/CRM/Custom/Form/CustomDataByType.php
+++ b/CRM/Custom/Form/CustomDataByType.php
@@ -1,9 +1,9 @@
_entityId = CRM_Utils_Request::retrieve('entityID', 'Positive');
$this->_groupID = CRM_Utils_Request::retrieve('groupID', 'Positive');
$this->_onlySubtype = CRM_Utils_Request::retrieve('onlySubtype', 'Boolean');
+ $this->_action = CRM_Utils_Request::retrieve('action', 'Alphanumeric');
$this->assign('cdType', FALSE);
$this->assign('cgCount', $this->_groupCount);
@@ -70,7 +71,7 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
CRM_Core_BAO_CustomGroup::setDefaults($this->_groupTree, $defaults, FALSE, FALSE, $this->get('action'));
return $defaults;
}
diff --git a/CRM/Custom/Form/DeleteField.php b/CRM/Custom/Form/DeleteField.php
index d9031b9797e7..364f44fe9d74 100644
--- a/CRM/Custom/Form/DeleteField.php
+++ b/CRM/Custom/Form/DeleteField.php
@@ -1,9 +1,9 @@
_id = $this->get('id');
- $defaults = array();
- $params = array('id' => $this->_id);
+ $defaults = [];
+ $params = ['id' => $this->_id];
CRM_Core_BAO_CustomField::retrieve($params, $defaults);
$this->_title = CRM_Utils_Array::value('label', $defaults);
-
- CRM_Utils_System::setTitle(ts('Delete %1', array(1 => $this->_title)));
+ $this->assign('title', $this->_title);
+ CRM_Utils_System::setTitle(ts('Delete %1', [1 => $this->_title]));
}
/**
@@ -77,18 +77,17 @@ public function preProcess() {
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete Custom Field'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete Custom Field'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -104,7 +103,7 @@ public function postProcess() {
CRM_Core_BAO_CustomField::deleteField($field);
// also delete any profiles associted with this custom field
- CRM_Core_Session::setStatus(ts('The custom field \'%1\' has been deleted.', array(1 => $field->label)), '', 'success');
+ CRM_Core_Session::setStatus(ts('The custom field \'%1\' has been deleted.', [1 => $field->label]), '', 'success');
}
diff --git a/CRM/Custom/Form/DeleteGroup.php b/CRM/Custom/Form/DeleteGroup.php
index c763befdd1f7..fa7f356c0f9d 100644
--- a/CRM/Custom/Form/DeleteGroup.php
+++ b/CRM/Custom/Form/DeleteGroup.php
@@ -1,9 +1,9 @@
_id = $this->get('id');
- $defaults = array();
- $params = array('id' => $this->_id);
+ $defaults = [];
+ $params = ['id' => $this->_id];
CRM_Core_BAO_CustomGroup::retrieve($params, $defaults);
$this->_title = $defaults['title'];
@@ -71,7 +71,7 @@ public function preProcess() {
$customField->custom_group_id = $this->_id;
if ($customField->find(TRUE)) {
- CRM_Core_Session::setStatus(ts("The Group '%1' cannot be deleted! You must Delete all custom fields in this group prior to deleting the group.", array(1 => $this->_title)), ts('Deletion Error'), 'error');
+ CRM_Core_Session::setStatus(ts("The Group '%1' cannot be deleted! You must Delete all custom fields in this group prior to deleting the group.", [1 => $this->_title]), ts('Deletion Error'), 'error');
$url = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1");
CRM_Utils_System::redirect($url);
return TRUE;
@@ -88,18 +88,17 @@ public function preProcess() {
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete Custom Group'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete Custom Group'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -114,7 +113,7 @@ public function postProcess() {
$wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_CustomGroup', $this->_id);
CRM_Core_BAO_CustomGroup::deleteGroup($group);
- CRM_Core_Session::setStatus(ts("The Group '%1' has been deleted.", array(1 => $group->title)), '', 'success');
+ CRM_Core_Session::setStatus(ts("The Group '%1' has been deleted.", [1 => $group->title]), '', 'success');
}
}
diff --git a/CRM/Custom/Form/Field.php b/CRM/Custom/Form/Field.php
index 602e87d12910..14d407950af5 100644
--- a/CRM/Custom/Form/Field.php
+++ b/CRM/Custom/Form/Field.php
@@ -1,9 +1,9 @@
_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $this->_values = array();
+ $this->_values = [];
//get the values form db if update.
if ($this->_id) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Core_BAO_CustomField::retrieve($params, $this->_values);
// note_length is an alias for the text_length field
$this->_values['note_length'] = CRM_Utils_Array::value('text_length', $this->_values);
@@ -128,40 +129,39 @@ public function preProcess() {
}
if (self::$_dataToLabels == NULL) {
- self::$_dataToLabels = array(
- array(
+ self::$_dataToLabels = [
+ [
'Text' => ts('Text'),
'Select' => ts('Select'),
'Radio' => ts('Radio'),
'CheckBox' => ts('CheckBox'),
'Multi-Select' => ts('Multi-Select'),
- 'AdvMulti-Select' => ts('Adv Multi-Select (obsolete)'),
'Autocomplete-Select' => ts('Autocomplete-Select'),
- ),
- array(
+ ],
+ [
'Text' => ts('Text'),
'Select' => ts('Select'),
'Radio' => ts('Radio'),
- ),
- array(
+ ],
+ [
'Text' => ts('Text'),
'Select' => ts('Select'),
'Radio' => ts('Radio'),
- ),
- array(
+ ],
+ [
'Text' => ts('Text'),
'Select' => ts('Select'),
'Radio' => ts('Radio'),
- ),
- array('TextArea' => ts('TextArea'), 'RichTextEditor' => ts('Rich Text Editor')),
- array('Date' => ts('Select Date')),
- array('Radio' => ts('Radio')),
- array('StateProvince' => ts('Select State/Province'), 'Multi-Select' => ts('Multi-Select State/Province')),
- array('Country' => ts('Select Country'), 'Multi-Select' => ts('Multi-Select Country')),
- array('File' => ts('Select File')),
- array('Link' => ts('Link')),
- array('ContactReference' => ts('Autocomplete-Select')),
- );
+ ],
+ ['TextArea' => ts('TextArea'), 'RichTextEditor' => ts('Rich Text Editor')],
+ ['Date' => ts('Select Date')],
+ ['Radio' => ts('Radio')],
+ ['StateProvince' => ts('Select State/Province'), 'Multi-Select' => ts('Multi-Select State/Province')],
+ ['Country' => ts('Select Country'), 'Multi-Select' => ts('Multi-Select Country')],
+ ['File' => ts('Select File')],
+ ['Link' => ts('Link')],
+ ['ContactReference' => ts('Autocomplete-Select')],
+ ];
}
}
@@ -223,10 +223,10 @@ public function setDefaultValues() {
$defaultHTMLType = array_search($defaults['html_type'],
self::$_dataToHTML[$defaultDataType]
);
- $defaults['data_type'] = array(
+ $defaults['data_type'] = [
'0' => $defaultDataType,
'1' => $defaultHTMLType,
- );
+ ];
$this->_defaultDataType = $defaults['data_type'];
}
@@ -237,6 +237,7 @@ public function setDefaultValues() {
else {
$defaults['is_active'] = 1;
$defaults['option_type'] = 1;
+ $defaults['is_search_range'] = 1;
}
// set defaults for weight.
@@ -247,7 +248,7 @@ public function setDefaultValues() {
}
if ($this->_action & CRM_Core_Action::ADD) {
- $fieldValues = array('custom_group_id' => $this->_gid);
+ $fieldValues = ['custom_group_id' => $this->_gid];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
$defaults['text_length'] = 255;
@@ -284,6 +285,8 @@ public function buildQuickForm() {
$this->assign('gid', $this->_gid);
}
+ $this->assign('dataTypeKeys', self::$_dataTypeKeys);
+
// lets trim all the whitespace
$this->applyFilter('__ALL__', 'trim');
@@ -298,57 +301,73 @@ public function buildQuickForm() {
);
$dt = &self::$_dataTypeValues;
- $it = array();
+ $it = [];
foreach ($dt as $key => $value) {
$it[$key] = self::$_dataToLabels[$key];
}
$sel = &$this->addElement('hierselect',
'data_type',
ts('Data and Input Field Type'),
- 'onclick="clearSearchBoxes();custom_option_html_type(this.form)"; onBlur="custom_option_html_type(this.form)";',
' '
);
- $sel->setOptions(array($dt, $it));
+ $sel->setOptions([$dt, $it]);
if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_multiple')) {
$this->add('checkbox', 'in_selector', ts('Display in Table?'));
}
+ $optionGroupParams = [
+ 'is_reserved' => 0,
+ 'is_active' => 1,
+ 'options' => ['limit' => 0, 'sort' => "title ASC"],
+ 'return' => ['title'],
+ ];
+
if ($this->_action == CRM_Core_Action::UPDATE) {
$this->freeze('data_type');
+ if (!empty($this->_values['option_group_id'])) {
+ // Before dev/core#155 we didn't set the is_reserved flag properly, which should be handled by the upgrade script...
+ // but it is still possible that existing installs may have optiongroups linked to custom fields that are marked reserved.
+ $optionGroupParams['id'] = $this->_values['option_group_id'];
+ $optionGroupParams['options']['or'] = [["is_reserved", "id"]];
+ }
}
- $includeFieldIds = NULL;
- if ($this->_action == CRM_Core_Action::UPDATE) {
- $includeFieldIds = $this->_values['id'];
- }
- $optionGroups = CRM_Core_BAO_CustomField::customOptionGroup($includeFieldIds);
- $emptyOptGroup = FALSE;
- if (empty($optionGroups)) {
- $emptyOptGroup = TRUE;
- $optionTypes = array('1' => ts('Create a new set of options'));
- }
- else {
- $optionTypes = array(
- '1' => ts('Create a new set of options'),
- '2' => ts('Reuse an existing set'),
- );
+
+ // Retrieve optiongroups for selection list
+ $optionGroupMetadata = civicrm_api3('OptionGroup', 'get', $optionGroupParams);
+
+ // OptionGroup selection
+ $optionTypes = ['1' => ts('Create a new set of options')];
+
+ if (!empty($optionGroupMetadata['values'])) {
+ $emptyOptGroup = FALSE;
+ $optionGroups = CRM_Utils_Array::collect('title', $optionGroupMetadata['values']);
+ $optionTypes['2'] = ts('Reuse an existing set');
$this->add('select',
'option_group_id',
ts('Multiple Choice Option Sets'),
- array(
+ [
'' => ts('- select -'),
- ) + $optionGroups
+ ] + $optionGroups
);
}
+ else {
+ // No custom (non-reserved) option groups
+ $emptyOptGroup = TRUE;
+ }
$element = &$this->addRadio('option_type',
ts('Option Type'),
$optionTypes,
- array(
+ [
'onclick' => "showOptionSelect();",
- ), ' '
+ ], ' '
);
+ // if empty option group freeze the option type.
+ if ($emptyOptGroup) {
+ $element->freeze();
+ }
$contactGroups = CRM_Core_PseudoConstant::group();
asort($contactGroups);
@@ -358,7 +377,7 @@ public function buildQuickForm() {
ts('Limit List to Group'),
$contactGroups,
FALSE,
- array('multiple' => 'multiple')
+ ['multiple' => 'multiple', 'class' => 'crm-select2']
);
$this->add('text',
@@ -367,15 +386,10 @@ public function buildQuickForm() {
$attributes['filter']
);
- $this->add('hidden', 'filter_selected', 'Group', array('id' => 'filter_selected'));
-
- //if empty option group freeze the option type.
- if ($emptyOptGroup) {
- $element->freeze();
- }
+ $this->add('hidden', 'filter_selected', 'Group', ['id' => 'filter_selected']);
// form fields of Custom Option rows
- $defaultOption = array();
+ $defaultOption = [];
$_showHide = new CRM_Core_ShowHideBlocks('', '');
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
@@ -403,7 +417,7 @@ public function buildQuickForm() {
);
// weight
- $this->add('text', "option_weight[$i]", ts('Order'),
+ $this->add('number', "option_weight[$i]", ts('Order'),
$optionAttributes['weight']
);
@@ -425,7 +439,7 @@ public function buildQuickForm() {
$this->add('number',
'text_length',
ts('Database field length'),
- $attributes['text_length'] + array('min' => 1),
+ $attributes['text_length'] + ['min' => 1],
FALSE
);
$this->addRule('text_length', ts('Value should be a positive number'), 'integer');
@@ -447,11 +461,11 @@ public function buildQuickForm() {
$this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
$this->add('select', 'date_format', ts('Date Format'),
- array('' => ts('- select -')) + CRM_Core_SelectValues::getDatePluginInputFormats()
+ ['' => ts('- select -')] + CRM_Core_SelectValues::getDatePluginInputFormats()
);
$this->add('select', 'time_format', ts('Time'),
- array('' => ts('- none -')) + CRM_Core_SelectValues::getTimeFormats()
+ ['' => ts('- none -')] + CRM_Core_SelectValues::getTimeFormats()
);
// for Note field
@@ -470,7 +484,8 @@ public function buildQuickForm() {
$this->add('number',
'note_length',
ts('Maximum length') . ' ',
- $attributes['text_length'], // note_length is an alias for the text-length field
+ // note_length is an alias for the text-length field
+ $attributes['text_length'],
FALSE
);
@@ -489,7 +504,7 @@ public function buildQuickForm() {
$this->add('advcheckbox', 'is_required', ts('Required?'));
// checkbox / radio options per line
- $this->add('number', 'options_per_line', ts('Options Per Line'), array('min' => 0));
+ $this->add('number', 'options_per_line', ts('Options Per Line'), ['min' => 0]);
$this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
// default value, help pre, help post, mask, attributes, javascript ?
@@ -515,38 +530,36 @@ public function buildQuickForm() {
// is searchable ?
$this->addElement('advcheckbox',
'is_searchable',
- ts('Is this Field Searchable?'),
- NULL, array('onclick' => "showSearchRange(this)")
+ ts('Is this Field Searchable?')
);
// is searchable by range?
- $searchRange = array();
+ $searchRange = [];
$searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
$searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
$this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
// add buttons
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Save and New'),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Save and New'),
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
// add a form rule to check default value
- $this->addFormRule(array('CRM_Custom_Form_Field', 'formRule'), $this);
+ $this->addFormRule(['CRM_Custom_Form_Field', 'formRule'], $this);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
@@ -555,7 +568,7 @@ public function buildQuickForm() {
$this->addElement('button',
'done',
ts('Done'),
- array('onclick' => "location.href='$url'")
+ ['onclick' => "location.href='$url'"]
);
}
}
@@ -576,23 +589,24 @@ public function buildQuickForm() {
public static function formRule($fields, $files, $self) {
$default = CRM_Utils_Array::value('default_value', $fields);
- $errors = array();
+ $errors = [];
self::clearEmptyOptions($fields);
//validate field label as well as name.
$title = $fields['label'];
$name = CRM_Utils_String::munge($title, '_', 64);
- $gId = $self->_gid; // CRM-7564
+ // CRM-7564
+ $gId = $self->_gid;
$query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
- $fldCnt = CRM_Core_DAO::singleValueQuery($query, array(
- 1 => array($name, 'String'),
- 2 => array($title, 'String'),
- 3 => array((int) $self->_id, 'Integer'),
- 4 => array($gId, 'Integer'),
- ));
+ $fldCnt = CRM_Core_DAO::singleValueQuery($query, [
+ 1 => [$name, 'String'],
+ 2 => [$title, 'String'],
+ 3 => [(int) $self->_id, 'Integer'],
+ 4 => [$gId, 'Integer'],
+ ]);
if ($fldCnt) {
- $errors['label'] = ts('Custom field \'%1\' already exists in Database.', array(1 => $title));
+ $errors['label'] = ts('Custom field \'%1\' already exists in Database.', [1 => $title]);
}
//checks the given custom field name doesnot start with digit
@@ -656,7 +670,7 @@ public static function formRule($fields, $files, $self) {
case 'Country':
if (!empty($default)) {
$query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
- $params = array(1 => array($fields['default_value'], 'String'));
+ $params = [1 => [$fields['default_value'], 'String']];
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['default_value'] = ts('Invalid default value for country.');
}
@@ -670,7 +684,7 @@ public static function formRule($fields, $files, $self) {
FROM civicrm_state_province
WHERE name = %1
OR abbreviation = %1";
- $params = array(1 => array($fields['default_value'], 'String'));
+ $params = [1 => [$fields['default_value'], 'String']];
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['default_value'] = ts('The invalid default value for State/Province data type');
}
@@ -686,7 +700,7 @@ public static function formRule($fields, $files, $self) {
$errors['filter'] = ts("Only 'get' action is supported.");
}
}
- $self->setDefaults(array('filter_selected', $fields['filter_selected']));
+ $self->setDefaults(['filter_selected', $fields['filter_selected']]);
break;
}
}
@@ -707,7 +721,7 @@ public static function formRule($fields, $files, $self) {
if (isset($fields['data_type'][1])) {
$dataField = $fields['data_type'][1];
}
- $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
+ $optionFields = ['Select', 'Multi-Select', 'CheckBox', 'Radio'];
if (isset($fields['option_type']) && $fields['option_type'] == 1) {
//capture duplicate Custom option values
@@ -821,7 +835,7 @@ public static function formRule($fields, $files, $self) {
}
elseif (isset($dataField) &&
in_array($dataField, $optionFields) &&
- !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))
+ !in_array($dataType, ['Boolean', 'Country', 'StateProvince'])
) {
if (!$fields['option_group_id']) {
$errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
@@ -832,13 +846,13 @@ public static function formRule($fields, $files, $self) {
FROM civicrm_custom_field
WHERE data_type != %1
AND option_group_id = %2";
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
self::$_dataTypeKeys[$fields['data_type'][0]],
'String',
- ),
- 2 => array($fields['option_group_id'], 'Integer'),
- );
+ ],
+ 2 => [$fields['option_group_id'], 'Integer'],
+ ];
$count = CRM_Core_DAO::singleValueQuery($query, $params);
if ($count > 0) {
$errors['option_group_id'] = ts('The data type of the multiple choice option set you\'ve selected does not match the data type assigned to this field.');
@@ -916,12 +930,12 @@ public function postProcess() {
}
//fix for 'is_search_range' field.
- if (in_array($dataTypeKey, array(
+ if (in_array($dataTypeKey, [
1,
2,
3,
5,
- ))) {
+ ])) {
if (empty($params['is_searchable'])) {
$params['is_search_range'] = 0;
}
@@ -945,7 +959,7 @@ public function postProcess() {
// fix for CRM-316
$oldWeight = NULL;
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $fieldValues = array('custom_group_id' => $this->_gid);
+ $fieldValues = ['custom_group_id' => $this->_gid];
if ($this->_id) {
$oldWeight = $this->_values['weight'];
}
@@ -1007,7 +1021,7 @@ public function postProcess() {
// reset the cache
CRM_Core_BAO_Cache::deleteGroup('contact fields');
- $msg = '
' . ts("Custom field '%1' has been saved.", array(1 => $customField->label)) . '
';
+ $msg = '
' . ts("Custom field '%1' has been saved.", [1 => $customField->label]) . '
';
$buttonName = $this->controller->getButtonName();
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Custom/Form/Group.php b/CRM/Custom/Form/Group.php
index 8f1c23a38867..d57e422557da 100644
--- a/CRM/Custom/Form/Group.php
+++ b/CRM/Custom/Form/Group.php
@@ -1,9 +1,9 @@
_action == CRM_Core_Action::UPDATE) {
$title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
- CRM_Utils_System::setTitle(ts('Edit %1', array(1 => $title)));
+ CRM_Utils_System::setTitle(ts('Edit %1', [1 => $title]));
}
elseif ($this->_action == CRM_Core_Action::VIEW) {
$title = CRM_Core_BAO_CustomGroup::getTitle($this->_id);
- CRM_Utils_System::setTitle(ts('Preview %1', array(1 => $title)));
+ CRM_Utils_System::setTitle(ts('Preview %1', [1 => $title]));
}
else {
CRM_Utils_System::setTitle(ts('New Custom Field Set'));
}
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Core_BAO_CustomGroup::retrieve($params, $this->_defaults);
$subExtends = CRM_Utils_Array::value('extends_entity_column_value', $this->_defaults);
@@ -110,19 +110,18 @@ public function preProcess() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
//validate group title as well as name.
$title = $fields['title'];
$name = CRM_Utils_String::munge($title, '_', 64);
- $query = 'select count(*) from civicrm_custom_group where ( name like %1 OR title like %2 ) and id != %3';
- $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
- 1 => array($name, 'String'),
- 2 => array($title, 'String'),
- 3 => array((int) $self->_id, 'Integer'),
- ));
+ $query = 'select count(*) from civicrm_custom_group where ( name like %1) and id != %2';
+ $grpCnt = CRM_Core_DAO::singleValueQuery($query, [
+ 1 => [$name, 'String'],
+ 2 => [(int) $self->_id, 'Integer'],
+ ]);
if ($grpCnt) {
- $errors['title'] = ts('Custom group \'%1\' already exists in Database.', array(1 => $title));
+ $errors['title'] = ts('Custom group \'%1\' already exists in Database.', [1 => $title]);
}
if (!empty($fields['extends'][1])) {
@@ -135,7 +134,7 @@ public static function formRule($fields, $files, $self) {
$errors['extends'] = ts("You need to select the type of record that this set of custom fields is applicable for.");
}
- $extends = array('Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant');
+ $extends = ['Activity', 'Relationship', 'Group', 'Contribution', 'Membership', 'Event', 'Participant'];
if (in_array($fields['extends'][0], $extends) && $fields['style'] == 'Tab') {
$errors['style'] = ts("Display Style should be Inline for this Class");
$self->assign('showStyle', TRUE);
@@ -171,7 +170,7 @@ public static function formRule($fields, $files, $self) {
* @see valid_date
*/
public function addRules() {
- $this->addFormRule(array('CRM_Custom_Form_Group', 'formRule'), $this);
+ $this->addFormRule(['CRM_Custom_Form_Group', 'formRule'], $this);
}
/**
@@ -189,11 +188,11 @@ public function buildQuickForm() {
$this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE);
//Fix for code alignment, CRM-3058
- $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
+ $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
$this->assign('contactTypes', json_encode($contactTypes));
- $sel1 = array("" => ts("- select -")) + CRM_Core_SelectValues::customGroupExtends();
- $sel2 = array();
+ $sel1 = ["" => ts("- select -")] + CRM_Core_SelectValues::customGroupExtends();
+ $sel2 = [];
$activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
$eventType = CRM_Core_OptionGroup::values('event_type');
@@ -228,22 +227,22 @@ public function buildQuickForm() {
foreach ($sel2 as $main => $sub) {
if (!empty($sel2[$main])) {
- $sel2[$main] = array(
+ $sel2[$main] = [
'' => ts("- Any -"),
- ) + $sel2[$main];
+ ] + $sel2[$main];
}
}
$cSubTypes = CRM_Core_Component::contactSubTypes();
if (!empty($cSubTypes)) {
- $contactSubTypes = array();
+ $contactSubTypes = [];
foreach ($cSubTypes as $key => $value) {
$contactSubTypes[$key] = $key;
}
- $sel2['Contact'] = array(
+ $sel2['Contact'] = [
"" => ("- Any -"),
- ) + $contactSubTypes;
+ ] + $contactSubTypes;
}
else {
if (!isset($this->_id)) {
@@ -259,13 +258,13 @@ public function buildQuickForm() {
$sel = &$this->add('hierselect',
'extends',
ts('Used For'),
- array(
+ [
'name' => 'extends[0]',
'style' => 'vertical-align: top;',
- ),
+ ],
TRUE
);
- $sel->setOptions(array($sel1, $sel2));
+ $sel->setOptions([$sel1, $sel2]);
if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) {
// make second selector a multi-select -
$sel->_elements[1]->setMultiple(TRUE);
@@ -308,7 +307,7 @@ public function buildQuickForm() {
$this->add('wysiwyg', 'help_post', ts('Post-form Help'), $attributes['help_post']);
// weight
- $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE);
+ $this->add('number', 'weight', ts('Order'), $attributes['weight'], TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// display style
@@ -346,18 +345,18 @@ public function buildQuickForm() {
$this->assign('showStyle', FALSE);
$this->assign('showMultiple', FALSE);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
if (!$this->_isGroupEmpty && !empty($this->_subtypes)) {
$buttons[0]['class'] = 'crm-warnDataLoss';
}
@@ -366,7 +365,7 @@ public function buildQuickForm() {
// TODO: Is this condition ever true? Can this code be removed?
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
- $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
+ $this->addElement('button', 'done', ts('Done'), ['onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"]);
}
}
@@ -406,11 +405,11 @@ public function setDefaultValues() {
$defaults['extends'][1] = $this->_subtypes;
}
else {
- $defaults['extends'][1] = array(0 => '');
+ $defaults['extends'][1] = [0 => ''];
}
if ($extends == 'Relationship' && !empty($this->_subtypes)) {
- $relationshipDefaults = array();
+ $relationshipDefaults = [];
foreach ($defaults['extends'][1] as $donCare => $rel_type_id) {
$relationshipDefaults[] = $rel_type_id;
}
@@ -439,7 +438,7 @@ public function postProcess() {
}
if (!empty($this->_subtypes)) {
- $subtypesToBeRemoved = array();
+ $subtypesToBeRemoved = [];
$subtypesToPreserve = $params['extends'][1];
// Don't remove any value if group is extended to -any- subtype
if (!empty($subtypesToPreserve[0])) {
@@ -461,14 +460,14 @@ public function postProcess() {
CRM_Core_BAO_Cache::deleteGroup('contact fields');
if ($this->_action & CRM_Core_Action::UPDATE) {
- CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', array(1 => $group->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('Your custom field set \'%1 \' has been saved.', [1 => $group->title]), ts('Saved'), 'success');
}
else {
// Jump directly to adding a field if popups are disabled
$action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? '' : '/add';
$url = CRM_Utils_System::url("civicrm/admin/custom/group/field$action", 'reset=1&new=1&gid=' . $group->id . '&action=' . ($action ? 'add' : 'browse'));
CRM_Core_Session::setStatus(ts("Your custom field set '%1' has been added. You can add custom fields now.",
- array(1 => $group->title)
+ [1 => $group->title]
), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
$session->replaceUserContext($url);
@@ -479,7 +478,7 @@ public function postProcess() {
$config = CRM_Core_Config::singleton();
if (is_array($db_prefix) && $config->userSystem->is_drupal && module_exists('views')) {
// get table_name for each custom group
- $tables = array();
+ $tables = [];
$sql = "SELECT table_name FROM civicrm_custom_group WHERE is_active = 1";
$result = CRM_Core_DAO::executeQuery($sql);
while ($result->fetch()) {
@@ -491,7 +490,7 @@ public function postProcess() {
if (!empty($missingTableNames)) {
CRM_Core_Session::setStatus(ts("To ensure that all of your custom data groups are available to Views, you may need to add the following key(s) to the db_prefix array in your settings.php file: '%1'.",
- array(1 => implode(', ', $missingTableNames))
+ [1 => implode(', ', $missingTableNames)]
), ts('Note'), 'info');
}
}
diff --git a/CRM/Custom/Form/MoveField.php b/CRM/Custom/Form/MoveField.php
index cc86d6face79..f52a549fc0e8 100644
--- a/CRM/Custom/Form/MoveField.php
+++ b/CRM/Custom/Form/MoveField.php
@@ -1,9 +1,9 @@
$this->_srcFieldLabel)
+ [1 => $this->_srcFieldLabel]
));
$session = CRM_Core_Session::singleton();
@@ -115,9 +115,9 @@ public function buildQuickForm() {
CRM_Core_Error::statusBounce(ts('You need more than one custom group to move fields'));
}
- $customGroup = array(
+ $customGroup = [
'' => ts('- select -'),
- ) + $customGroup;
+ ] + $customGroup;
$this->add('select',
'dst_group_id',
ts('Destination'),
@@ -125,20 +125,19 @@ public function buildQuickForm() {
TRUE
);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Move Custom Field'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $this->addFormRule(array('CRM_Custom_Form_MoveField', 'formRule'), $this);
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Move Custom Field'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFormRule(['CRM_Custom_Form_MoveField', 'formRule'], $this);
}
/**
@@ -151,7 +150,7 @@ public function buildQuickForm() {
public static function formRule($fields, $files, $self) {
$self->_dstGID = $fields['dst_group_id'];
$tmp = CRM_Core_BAO_CustomField::_moveFieldValidate($self->_srcFID, $self->_dstGID);
- $errors = array();
+ $errors = [];
if ($tmp['newGroupID']) {
$errors['dst_group_id'] = $tmp['newGroupID'];
}
@@ -172,11 +171,11 @@ public function postProcess() {
);
$srcUrl = CRM_Utils_System::url('civicrm/admin/custom/group/field', "reset=1&action=browse&gid={$this->_dstGID}");
CRM_Core_Session::setStatus(ts("%1 has been moved to the custom set %2.",
- array(
+ [
1 => $this->_srcFieldLabel,
2 => $dstGroup,
3 => $srcUrl,
- )), '', 'success');
+ ]), '', 'success');
}
}
diff --git a/CRM/Custom/Form/Option.php b/CRM/Custom/Form/Option.php
index 00b450774431..34b02bd2bcf1 100644
--- a/CRM/Custom/Form/Option.php
+++ b/CRM/Custom/Form/Option.php
@@ -1,9 +1,9 @@
_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Core_BAO_CustomOption::retrieve($params, $defaults);
- $paramsField = array('id' => $this->_fid);
+ $paramsField = ['id' => $this->_fid];
CRM_Core_BAO_CustomField::retrieve($paramsField, $fieldDefaults);
if ($fieldDefaults['html_type'] == 'CheckBox'
|| $fieldDefaults['html_type'] == 'Multi-Select'
- || $fieldDefaults['html_type'] == 'AdvMulti-Select'
) {
if (!empty($fieldDefaults['default_value'])) {
$defaultCheckValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
@@ -137,7 +137,7 @@ public function setDefaultValues() {
}
if ($this->_action & CRM_Core_Action::ADD) {
- $fieldValues = array('option_group_id' => $this->_optionGroupID);
+ $fieldValues = ['option_group_id' => $this->_optionGroupID];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
}
@@ -151,20 +151,19 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action == CRM_Core_Action::DELETE) {
- $option = civicrm_api3('option_value', 'getsingle', array('id' => $this->_id));
+ $option = civicrm_api3('option_value', 'getsingle', ['id' => $this->_id]);
$this->assign('label', $option['label']);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
else {
// lets trim all the whitespace
@@ -181,8 +180,9 @@ public function buildQuickForm() {
$this->add('text', 'value', ts('Option Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'), TRUE);
+ $this->add('textarea', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'description'));
// weight
- $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
+ $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// is active ?
@@ -192,26 +192,25 @@ public function buildQuickForm() {
$this->add('checkbox', 'default_value', ts('Default'));
// add a custom form rule
- $this->addFormRule(array('CRM_Custom_Form_Option', 'formRule'), $this);
+ $this->addFormRule(['CRM_Custom_Form_Option', 'formRule'], $this);
// add buttons
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Save and New'),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Save and New'),
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
@@ -223,7 +222,7 @@ public function buildQuickForm() {
$this->addElement('button',
'done',
ts('Done'),
- array('onclick' => "location.href='$url'", 'class' => 'crm-form-submit cancel', 'crm-icon' => 'fa-times')
+ ['onclick' => "location.href='$url'", 'class' => 'crm-form-submit cancel', 'crm-icon' => 'fa-times']
);
}
}
@@ -248,17 +247,17 @@ public static function formRule($fields, $files, $form) {
$fieldId = $form->_fid;
$optionGroupId = $form->_optionGroupID;
- $temp = array();
+ $temp = [];
if (empty($form->_id)) {
$query = "
SELECT count(*)
FROM civicrm_option_value
WHERE option_group_id = %1
AND label = %2";
- $params = array(
- 1 => array($optionGroupId, 'Integer'),
- 2 => array($optionLabel, 'String'),
- );
+ $params = [
+ 1 => [$optionGroupId, 'Integer'],
+ 2 => [$optionLabel, 'String'],
+ ];
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['label'] = ts('There is an entry with the same label.');
}
@@ -268,10 +267,10 @@ public static function formRule($fields, $files, $form) {
FROM civicrm_option_value
WHERE option_group_id = %1
AND value = %2";
- $params = array(
- 1 => array($optionGroupId, 'Integer'),
- 2 => array($optionValue, 'String'),
- );
+ $params = [
+ 1 => [$optionGroupId, 'Integer'],
+ 2 => [$optionValue, 'String'],
+ ];
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['value'] = ts('There is an entry with the same value.');
}
@@ -287,11 +286,11 @@ public static function formRule($fields, $files, $form) {
WHERE option_group_id = %1
AND id != %2
AND label = %3";
- $params = array(
- 1 => array($optionGroupId, 'Integer'),
- 2 => array($optionId, 'Integer'),
- 3 => array($optionLabel, 'String'),
- );
+ $params = [
+ 1 => [$optionGroupId, 'Integer'],
+ 2 => [$optionId, 'Integer'],
+ 3 => [$optionLabel, 'String'],
+ ];
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['label'] = ts('There is an entry with the same label.');
}
@@ -303,11 +302,11 @@ public static function formRule($fields, $files, $form) {
WHERE option_group_id = %1
AND id != %2
AND value = %3";
- $params = array(
- 1 => array($optionGroupId, 'Integer'),
- 2 => array($optionId, 'Integer'),
- 3 => array($optionValue, 'String'),
- );
+ $params = [
+ 1 => [$optionGroupId, 'Integer'],
+ 2 => [$optionId, 'Integer'],
+ 3 => [$optionValue, 'String'],
+ ];
if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
$errors['value'] = ts('There is an entry with the same value.');
}
@@ -317,7 +316,7 @@ public static function formRule($fields, $files, $form) {
SELECT data_type
FROM civicrm_custom_field
WHERE id = %1";
- $params = array(1 => array($fieldId, 'Integer'));
+ $params = [1 => [$fieldId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
switch ($dao->data_type) {
@@ -356,7 +355,7 @@ public static function formRule($fields, $files, $form) {
case 'Country':
if (!empty($fields["value"])) {
- $params = array(1 => array($fields['value'], 'String'));
+ $params = [1 => [$fields['value'], 'String']];
$query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
$errors['value'] = ts('Invalid default value for country.');
@@ -366,7 +365,7 @@ public static function formRule($fields, $files, $form) {
case 'StateProvince':
if (!empty($fields["value"])) {
- $params = array(1 => array($fields['value'], 'String'));
+ $params = [1 => [$fields['value'], 'String']];
$query = "
SELECT count(*)
FROM civicrm_state_province
@@ -393,11 +392,11 @@ public function postProcess() {
$params = $this->controller->exportValues('Option');
if ($this->_action == CRM_Core_Action::DELETE) {
- $option = civicrm_api3('option_value', 'getsingle', array('id' => $this->_id));
- $fieldValues = array('option_group_id' => $this->_optionGroupID);
+ $option = civicrm_api3('option_value', 'getsingle', ['id' => $this->_id]);
+ $fieldValues = ['option_group_id' => $this->_optionGroupID];
CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
CRM_Core_BAO_CustomOption::del($this->_id);
- CRM_Core_Session::setStatus(ts('Option "%1" has been deleted.', array(1 => $option['label'])), ts('Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts('Option "%1" has been deleted.', [1 => $option['label']]), ts('Deleted'), 'success');
return;
}
@@ -406,6 +405,7 @@ public function postProcess() {
$customOption->label = $params['label'];
$customOption->name = CRM_Utils_String::titleToVar($params['label']);
$customOption->weight = $params['weight'];
+ $customOption->description = $params['description'];
$customOption->value = $params['value'];
$customOption->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
@@ -416,7 +416,7 @@ public function postProcess() {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
}
- $fieldValues = array('option_group_id' => $this->_optionGroupID);
+ $fieldValues = ['option_group_id' => $this->_optionGroupID];
$customOption->weight
= CRM_Utils_Weight::updateOtherWeights(
'CRM_Core_DAO_OptionValue',
@@ -432,7 +432,6 @@ public function postProcess() {
$customField->find(TRUE) &&
(
$customField->html_type == 'CheckBox' ||
- $customField->html_type == 'AdvMulti-Select' ||
$customField->html_type == 'Multi-Select'
)
) {
@@ -443,7 +442,7 @@ public function postProcess() {
if (!empty($params['default_value'])) {
if (!in_array($customOption->value, $defVal)) {
if (empty($defVal[0])) {
- $defVal = array($customOption->value);
+ $defVal = [$customOption->value];
}
else {
$defVal[] = $customOption->value;
@@ -456,7 +455,7 @@ public function postProcess() {
}
}
elseif (in_array($customOption->value, $defVal)) {
- $tempVal = array();
+ $tempVal = [];
foreach ($defVal as $v) {
if ($v != $customOption->value) {
$tempVal[] = $v;
@@ -498,7 +497,7 @@ public function postProcess() {
$customOption->save();
- $msg = ts('Your multiple choice option \'%1\' has been saved', array(1 => $customOption->label));
+ $msg = ts('Your multiple choice option \'%1\' has been saved', [1 => $customOption->label]);
CRM_Core_Session::setStatus($msg, '', 'success');
$buttonName = $this->controller->getButtonName();
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Custom/Form/Preview.php b/CRM/Custom/Form/Preview.php
index 22e9bc0409cd..9f7c9e06a738 100644
--- a/CRM/Custom/Form/Preview.php
+++ b/CRM/Custom/Form/Preview.php
@@ -1,9 +1,9 @@
_fieldId = $this->get('fieldId');
if ($this->_fieldId) {
// field preview
- $defaults = array();
- $params = array('id' => $this->_fieldId);
+ $defaults = [];
+ $params = ['id' => $this->_fieldId];
$fieldDAO = new CRM_Core_DAO_CustomField();
CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
@@ -75,9 +75,9 @@ public function preProcess() {
CRM_Core_Error::statusBounce(ts('This field is inactive so it will not display on edit form.'));
}
- $groupTree = array();
+ $groupTree = [];
$groupTree[$this->_groupId]['id'] = 0;
- $groupTree[$this->_groupId]['fields'] = array();
+ $groupTree[$this->_groupId]['fields'] = [];
$groupTree[$this->_groupId]['fields'][$this->_fieldId] = $defaults;
$this->_groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, $this);
$this->assign('preview_type', 'field');
@@ -96,7 +96,7 @@ public function preProcess() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
CRM_Core_BAO_CustomGroup::setDefaults($this->_groupTree, $defaults, FALSE, FALSE);
@@ -109,7 +109,7 @@ public function setDefaultValues() {
* @return void
*/
public function buildQuickForm() {
- if (is_array($this->_groupTree[$this->_groupId])) {
+ if (is_array($this->_groupTree) && !empty($this->_groupTree[$this->_groupId])) {
foreach ($this->_groupTree[$this->_groupId]['fields'] as & $field) {
//add the form elements
CRM_Core_BAO_CustomField::addQuickFormElement($this, $field['element_name'], $field['id'], CRM_Utils_Array::value('is_required', $field));
@@ -117,14 +117,13 @@ public function buildQuickForm() {
$this->assign('groupTree', $this->_groupTree);
}
- $this->addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done with Preview'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done with Preview'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Custom/Import/Controller.php b/CRM/Custom/Import/Controller.php
index a5053f34eff8..c67e3990314c 100644
--- a/CRM/Custom/Import/Controller.php
+++ b/CRM/Custom/Import/Controller.php
@@ -4,6 +4,7 @@
* Class CRM_Custom_Import_Controller
*/
class CRM_Custom_Import_Controller extends CRM_Core_Controller {
+
/**
* Class constructor.
*
@@ -26,7 +27,7 @@ public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $mod
// add all the actions
$config = CRM_Core_Config::singleton();
- $this->addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Custom/Import/Field.php b/CRM/Custom/Import/Field.php
index 844fdef56fbc..8b292da3415d 100644
--- a/CRM/Custom/Import/Field.php
+++ b/CRM/Custom/Import/Field.php
@@ -1,9 +1,9 @@
CRM_Import_Parser::CONTACT_INDIVIDUAL,
'fieldSeparator' => $config->fieldSeparator,
'multipleCustomData' => $this->_id,
- );
+ ];
if ($loadeMapping = $this->get('loadedMapping')) {
$this->assign('loadedMapping', $loadeMapping);
@@ -70,7 +70,7 @@ public function buildQuickForm() {
parent::buildQuickForm();
$multipleCustomData = CRM_Core_BAO_CustomGroup::getMultipleFieldGroup();
- $this->add('select', 'multipleCustomData', ts('Multi-value Custom Data'), array('' => ts('- select -')) + $multipleCustomData, TRUE);
+ $this->add('select', 'multipleCustomData', ts('Multi-value Custom Data'), ['' => ts('- select -')] + $multipleCustomData, TRUE);
$this->addContactTypeSelector();
}
@@ -81,12 +81,12 @@ public function buildQuickForm() {
* @return void
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'contactType',
'dateFormats',
'savedMapping',
'multipleCustomData',
- ));
+ ]);
$this->submitFileForMapping('CRM_Custom_Import_Parser_Api', 'multipleCustomData');
}
diff --git a/CRM/Custom/Import/Form/MapField.php b/CRM/Custom/Import/Form/MapField.php
index d68aa95a367b..b7a42335c242 100644
--- a/CRM/Custom/Import/Form/MapField.php
+++ b/CRM/Custom/Import/Form/MapField.php
@@ -23,7 +23,7 @@ public function preProcess() {
$this->_columnCount = $this->get('columnCount');
$this->assign('columnCount', $this->_columnCount);
$this->_dataValues = $this->get('dataValues');
- $highlightedFields = array('contact_id', 'external_identifier');
+ $highlightedFields = ['contact_id', 'external_identifier'];
//Separate column names from actual values.
$columnNames = $this->_dataValues[0];
@@ -52,7 +52,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addFormRule(array('CRM_Custom_Import_Form_MapField', 'formRule'));
+ $this->addFormRule(['CRM_Custom_Import_Form_MapField', 'formRule']);
}
/**
@@ -65,10 +65,10 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
$fieldMessage = NULL;
if (!array_key_exists('savedMapping', $fields)) {
- $importKeys = array();
+ $importKeys = [];
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
@@ -78,7 +78,7 @@ public static function formRule($fields) {
if (!isset($errors['_qf_default'])) {
$errors['_qf_default'] = '';
}
- $errors['_qf_default'] .= ts('Missing required field: %1', array(1 => ts('Contact ID or External Identifier')));
+ $errors['_qf_default'] .= ts('Missing required field: %1', [1 => ts('Contact ID or External Identifier')]);
}
}
@@ -88,8 +88,7 @@ public static function formRule($fields) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Multi value custom data', 'name');
- if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
+ if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Multi value custom data'))) {
$errors['saveMappingName'] = ts('Duplicate ' . $self->_mappingType . 'Mapping Name');
}
}
@@ -137,10 +136,10 @@ public function postProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$this->_entity = $this->controller->exportValue('DataSource', 'entity');
- $mapperKeys = array();
- $mapper = array();
+ $mapperKeys = [];
+ $mapper = [];
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
- $mapperKeysMain = array();
+ $mapperKeysMain = [];
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
@@ -159,7 +158,7 @@ public function postProcess() {
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
- $mappingFieldsId = array();
+ $mappingFieldsId = [];
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
@@ -184,14 +183,11 @@ public function postProcess() {
//Saving Mapping Details and Records
if (!empty($params['saveMapping'])) {
- $mappingParams = array(
+ $mappingParams = [
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- $this->_mappingType,
- 'name'
- ),
- );
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', $this->_mappingType),
+ ];
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
diff --git a/CRM/Custom/Import/Form/Preview.php b/CRM/Custom/Import/Form/Preview.php
index 3d772fcda1a0..76a5765705ce 100644
--- a/CRM/Custom/Import/Form/Preview.php
+++ b/CRM/Custom/Import/Form/Preview.php
@@ -56,7 +56,7 @@ public function preProcess() {
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'dataValues',
'columnCount',
@@ -67,7 +67,7 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -90,7 +90,7 @@ public function postProcess() {
$entity = $this->get('_entity');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
+ $mapperKeys = [];
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
@@ -102,7 +102,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -123,7 +123,7 @@ public function postProcess() {
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Custom/Import/Form/Summary.php b/CRM/Custom/Import/Form/Summary.php
index 228465fa21b1..716e59f1f951 100644
--- a/CRM/Custom/Import/Form/Summary.php
+++ b/CRM/Custom/Import/Form/Summary.php
@@ -4,6 +4,7 @@
* Class CRM_Custom_Import_Form_Summary
*/
class CRM_Custom_Import_Form_Summary extends CRM_Contact_Import_Form_Summary {
+
/**
* Set variables up before form is built.
*
diff --git a/CRM/Custom/Import/Parser.php b/CRM/Custom/Import/Parser.php
index 9d5d6432e4a4..0832d00bac6e 100644
--- a/CRM/Custom/Import/Parser.php
+++ b/CRM/Custom/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
@@ -191,14 +195,12 @@ public function run(
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode & self::CONFLICT) {
@@ -253,32 +255,26 @@ public function run(
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('View Activity History URL'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('View Activity History URL'),
+ ], $customHeaders);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
@@ -314,7 +310,7 @@ public function setActiveFields($fieldKeys) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
diff --git a/CRM/Custom/Import/Parser/Api.php b/CRM/Custom/Import/Parser/Api.php
index dad22e5fd5ac..ab60fa1d336d 100644
--- a/CRM/Custom/Import/Parser/Api.php
+++ b/CRM/Custom/Import/Parser/Api.php
@@ -6,16 +6,16 @@
class CRM_Custom_Import_Parser_Api extends CRM_Custom_Import_Parser {
protected $_entity = '';
- protected $_fields = array();
- protected $_requiredFields = array();
- protected $_dateFields = array();
+ protected $_fields = [];
+ protected $_requiredFields = [];
+ protected $_dateFields = [];
protected $_multipleCustomData = '';
/**
* Params for the current entity being prepared for the api.
* @var array
*/
- protected $_params = array();
+ protected $_params = [];
/**
* Class constructor.
@@ -32,11 +32,11 @@ public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneTyp
public function setFields() {
$customGroupID = $this->_multipleCustomData;
$importableFields = $this->getGroupFieldsForImport($customGroupID, $this);
- $this->_fields = array_merge(array(
- 'do_not_import' => array('title' => ts('- do not import -')),
- 'contact_id' => array('title' => ts('Contact ID')),
- 'external_identifier' => array('title' => ts('External Identifier')),
- ), $importableFields);
+ $this->_fields = array_merge([
+ 'do_not_import' => ['title' => ts('- do not import -')],
+ 'contact_id' => ['title' => ts('Contact ID')],
+ 'external_identifier' => ['title' => ts('External Identifier')],
+ ], $importableFields);
}
/**
@@ -121,7 +121,7 @@ public function summary(&$values) {
$errorMessage = NULL;
$contactType = $this->_contactType ? $this->_contactType : 'Organization';
- CRM_Contact_Import_Parser_Contact::isErrorInCustomData($this->_params + array('contact_type' => $contactType), $errorMessage, $this->_contactSubType, NULL);
+ CRM_Contact_Import_Parser_Contact::isErrorInCustomData($this->_params + ['contact_type' => $contactType], $errorMessage, $this->_contactSubType, NULL);
// pseudoconstants
if ($errorMessage) {
@@ -147,10 +147,10 @@ public function summary(&$values) {
public function import($onDuplicate, &$values) {
$response = $this->summary($values);
if ($response != CRM_Import_Parser::VALID) {
- $importRecordParams = array(
+ $importRecordParams = [
$statusFieldName => 'INVALID',
"${statusFieldName}Msg" => "Invalid (Error Code: $response)",
- );
+ ];
return $response;
}
@@ -159,9 +159,9 @@ public function import($onDuplicate, &$values) {
$params = $this->getActiveFieldParams();
$contactType = $this->_contactType ? $this->_contactType : 'Organization';
- $formatted = array(
+ $formatted = [
'contact_type' => $contactType,
- );
+ ];
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
@@ -237,8 +237,8 @@ public function fini() {
*
*/
public function getGroupFieldsForImport($id) {
- $importableFields = array();
- $params = array('custom_group_id' => $id);
+ $importableFields = [];
+ $params = ['custom_group_id' => $id];
$allFields = civicrm_api3('custom_field', 'get', $params);
$fields = $allFields['values'];
foreach ($fields as $id => $values) {
@@ -249,7 +249,7 @@ public function getGroupFieldsForImport($id) {
/* generate the key for the fields array */
$key = "custom_$id";
$regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
- $importableFields[$key] = array(
+ $importableFields[$key] = [
'name' => $key,
'title' => CRM_Utils_Array::value('label', $values),
'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
@@ -259,7 +259,7 @@ public function getGroupFieldsForImport($id) {
'data_type' => CRM_Utils_Array::value('data_type', $values),
'html_type' => CRM_Utils_Array::value('html_type', $values),
'is_search_range' => CRM_Utils_Array::value('is_search_range', $values),
- );
+ ];
if (CRM_Utils_Array::value('html_type', $values) == 'Select Date') {
$importableFields[$key]['date_format'] = CRM_Utils_Array::value('date_format', $values);
$importableFields[$key]['time_format'] = CRM_Utils_Array::value('time_format', $values);
diff --git a/CRM/Custom/Page/AJAX.php b/CRM/Custom/Page/AJAX.php
index ef99f073b5be..6774b584e8ca 100644
--- a/CRM/Custom/Page/AJAX.php
+++ b/CRM/Custom/Page/AJAX.php
@@ -1,9 +1,9 @@
array($params['start'], 'Integer'),
- 2 => array($params['end'], 'Integer'),
- 3 => array($params['gid'], 'Integer'),
- );
+ $queryParams = [
+ 1 => [$params['start'], 'Integer'],
+ 2 => [$params['end'], 'Integer'],
+ 3 => [$params['gid'], 'Integer'],
+ ];
$dao = "SELECT id FROM civicrm_option_value WHERE weight = %1 AND option_group_id = %3";
$startid = CRM_Core_DAO::singleValueQuery($dao, $queryParams);
@@ -132,12 +133,12 @@ public static function getMultiRecordFieldList() {
list($fields, $attributes) = $obj->browse();
// format params and add class attributes
- $fieldList = array();
+ $fieldList = [];
foreach ($fields as $id => $value) {
- $field = array();
+ $field = [];
foreach ($value as $fieldId => &$fieldName) {
if (!empty($attributes[$fieldId][$id]['class'])) {
- $fieldName = array('data' => $fieldName, 'cellClass' => $attributes[$fieldId][$id]['class']);
+ $fieldName = ['data' => $fieldName, 'cellClass' => $attributes[$fieldId][$id]['class']];
}
if (is_numeric($fieldId)) {
$fName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $fieldId, 'column_name');
@@ -149,7 +150,7 @@ public static function getMultiRecordFieldList() {
}
$totalRecords = !empty($obj->_total) ? $obj->_total : 0;
- $multiRecordFields = array();
+ $multiRecordFields = [];
$multiRecordFields['data'] = $fieldList;
$multiRecordFields['recordsTotal'] = $totalRecords;
$multiRecordFields['recordsFiltered'] = $totalRecords;
diff --git a/CRM/Custom/Page/Field.php b/CRM/Custom/Page/Field.php
index 5e856cb31185..328f5d89265b 100644
--- a/CRM/Custom/Page/Field.php
+++ b/CRM/Custom/Page/Field.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Field'),
'url' => 'civicrm/admin/custom/group/field/update',
'qs' => 'action=update&reset=1&gid=%%gid%%&id=%%id%%',
'title' => ts('Edit Custom Field'),
- ),
- CRM_Core_Action::BROWSE => array(
+ ],
+ CRM_Core_Action::BROWSE => [
'name' => ts('Edit Multiple Choice Options'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'reset=1&action=browse&gid=%%gid%%&fid=%%id%%',
'title' => ts('List Custom Options'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview Field Display'),
'url' => 'civicrm/admin/custom/group/field',
'qs' => 'action=preview&reset=1&gid=%%gid%%&id=%%id%%',
'title' => ts('Preview Custom Field'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Custom Field'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Custom Field'),
- ),
- CRM_Core_Action::EXPORT => array(
+ ],
+ CRM_Core_Action::EXPORT => [
'name' => ts('Move'),
'url' => 'civicrm/admin/custom/group/field/move',
'class' => 'small-popup',
'qs' => 'reset=1&fid=%%id%%',
'title' => ts('Move Custom Field'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/custom/group/field',
'qs' => 'action=delete&reset=1&gid=%%gid%%&id=%%id%%',
'title' => ts('Delete Custom Field'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -125,7 +125,7 @@ public function browse() {
$resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header');
}
- $customField = array();
+ $customField = [];
$customFieldBAO = new CRM_Core_BAO_CustomField();
// fkey is gid
@@ -134,7 +134,7 @@ public function browse() {
$customFieldBAO->find();
while ($customFieldBAO->fetch()) {
- $customField[$customFieldBAO->id] = array();
+ $customField[$customFieldBAO->id] = [];
CRM_Core_DAO::storeValues($customFieldBAO, $customField[$customFieldBAO->id]);
$action = array_sum(array_keys(self::actionLinks()));
if ($customFieldBAO->is_active) {
@@ -171,10 +171,10 @@ public function browse() {
$customField[$customFieldBAO->id]['data_type'] = $customFieldDataType[$customField[$customFieldBAO->id]['data_type']];
$customField[$customFieldBAO->id]['order'] = $customField[$customFieldBAO->id]['weight'];
$customField[$customFieldBAO->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action,
- array(
+ [
'id' => $customFieldBAO->id,
'gid' => $this->_gid,
- ),
+ ],
ts('more'),
FALSE,
'customField.row.actions',
@@ -231,7 +231,7 @@ public function run() {
);
if ($id) {
- $values = civicrm_api3('custom_field', 'getsingle', array('id' => $id));
+ $values = civicrm_api3('custom_field', 'getsingle', ['id' => $id]);
$this->_gid = $values['custom_group_id'];
}
// get the group id
@@ -262,7 +262,7 @@ public function run() {
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
- $fieldValues = array('custom_group_id' => $this->_gid);
+ $fieldValues = ['custom_group_id' => $this->_gid];
$wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_CustomField', $id, $fieldValues);
}
@@ -271,7 +271,7 @@ public function run() {
$this->assign('gid', $this->_gid);
$this->assign('groupTitle', $groupTitle);
if ($action & CRM_Core_Action::BROWSE) {
- CRM_Utils_System::setTitle(ts('%1 - Custom Fields', array(1 => $groupTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Custom Fields', [1 => $groupTitle]));
}
}
diff --git a/CRM/Custom/Page/Group.php b/CRM/Custom/Page/Group.php
index 5cc8e1293bc1..48b9b36f1026 100644
--- a/CRM/Custom/Page/Group.php
+++ b/CRM/Custom/Page/Group.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::BROWSE => [
'name' => ts('View and Edit Custom Fields'),
'url' => 'civicrm/admin/custom/group/field',
'qs' => 'reset=1&action=browse&gid=%%id%%',
'title' => ts('View and Edit Custom Fields'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview'),
'url' => 'civicrm/admin/custom/group',
'qs' => 'action=preview&reset=1&id=%%id%%',
'title' => ts('Preview Custom Data Set'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Settings'),
'url' => 'civicrm/admin/custom/group',
'qs' => 'action=update&reset=1&id=%%id%%',
'title' => ts('Edit Custom Set'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Custom Set'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Custom Set'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/custom/group',
'qs' => 'action=delete&reset=1&id=%%id%%',
'title' => ts('Delete Custom Set'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -200,7 +200,7 @@ public function preview($id) {
*/
public function browse($action = NULL) {
// get all custom groups sorted by weight
- $customGroup = array();
+ $customGroup = [];
$dao = new CRM_Core_DAO_CustomGroup();
$dao->is_reserved = FALSE;
$dao->orderBy('weight, title');
@@ -210,7 +210,7 @@ public function browse($action = NULL) {
$customGroupStyle = CRM_Core_SelectValues::customGroupStyle();
while ($dao->fetch()) {
$id = $dao->id;
- $customGroup[$id] = array();
+ $customGroup[$id] = [];
CRM_Core_DAO::storeValues($dao, $customGroup[$id]);
// form all action links
$action = array_sum(array_keys(self::actionLinks()));
@@ -224,7 +224,7 @@ public function browse($action = NULL) {
}
$customGroup[$id]['order'] = $customGroup[$id]['weight'];
$customGroup[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action,
- array('id' => $id),
+ ['id' => $id],
ts('more'),
FALSE,
'customGroup.row.actions',
@@ -238,7 +238,7 @@ public function browse($action = NULL) {
}
//fix for Displaying subTypes
- $subTypes = array();
+ $subTypes = [];
$subTypes['Activity'] = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
$subTypes['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
@@ -246,7 +246,7 @@ public function browse($action = NULL) {
$subTypes['Event'] = CRM_Core_OptionGroup::values('event_type');
$subTypes['Grant'] = CRM_Core_OptionGroup::values('grant_type');
$subTypes['Campaign'] = CRM_Campaign_PseudoConstant::campaignType();
- $subTypes['Participant'] = array();
+ $subTypes['Participant'] = [];
$subTypes['ParticipantRole'] = CRM_Core_OptionGroup::values('participant_role');;
$subTypes['ParticipantEventName'] = CRM_Event_PseudoConstant::event();
$subTypes['ParticipantEventType'] = CRM_Core_OptionGroup::values('event_type');
@@ -258,7 +258,7 @@ public function browse($action = NULL) {
$relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
$relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
- $allRelationshipType = array();
+ $allRelationshipType = [];
$allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
$allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
@@ -274,7 +274,7 @@ public function browse($action = NULL) {
$subTypes['Relationship'] = $allRelationshipType;
$cSubTypes = CRM_Core_Component::contactSubTypes();
- $contactSubTypes = array();
+ $contactSubTypes = [];
foreach ($cSubTypes as $key => $value) {
$contactSubTypes[$key] = $key;
}
diff --git a/CRM/Custom/Page/Option.php b/CRM/Custom/Page/Option.php
index 8fe3a8841a6e..bfdfc015bcb0 100644
--- a/CRM/Custom/Page/Option.php
+++ b/CRM/Custom/Page/Option.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Option'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'reset=1&action=update&id=%%id%%&fid=%%fid%%&gid=%%gid%%',
'title' => ts('Edit Multiple Choice Option'),
- ),
- CRM_Core_Action::VIEW => array(
+ ],
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'action=view&id=%%id%%&fid=%%fid%%',
'title' => ts('View Multiple Choice Option'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
- 'title' => ts('Disable Mutliple Choice Option'),
- ),
- CRM_Core_Action::ENABLE => array(
+ 'title' => ts('Disable Multiple Choice Option'),
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
- 'title' => ts('Enable Mutliple Choice Option'),
- ),
- CRM_Core_Action::DELETE => array(
+ 'title' => ts('Enable Multiple Choice Option'),
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/custom/group/field/option',
'qs' => 'action=delete&id=%%id%%&fid=%%fid%%',
- 'title' => ts('Disable Multiple Choice Option'),
- ),
- );
+ 'title' => ts('Delete Multiple Choice Option'),
+ ],
+ ];
}
return self::$_actionLinks;
}
+ /**
+ * Alphabetize multiple option values
+ *
+ * @return void
+ */
+ public function alphabetize() {
+ $optionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
+ $this->_fid,
+ 'option_group_id'
+ );
+ $query = "
+SELECT id, label
+FROM civicrm_option_value
+WHERE option_group_id = %1";
+ $params = [
+ 1 => [$optionGroupID, 'Integer'],
+ ];
+ $dao = CRM_Core_DAO::executeQuery($query, $params);
+ $optionValue = [];
+ while ($dao->fetch()) {
+ $optionValue[$dao->id] = $dao->label;
+ }
+ asort($optionValue, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
+
+ $i = 1;
+ foreach ($optionValue as $key => $_) {
+ $clause[] = "WHEN $key THEN $i";
+ $i++;
+ }
+
+ $when = implode(' ', $clause);
+ $sql = "
+UPDATE civicrm_option_value
+SET weight = CASE id
+$when
+END
+WHERE option_group_id = %1";
+
+ $dao = CRM_Core_DAO::executeQuery($sql, $params);
+ }
+
/**
* Browse all custom group fields.
*
@@ -125,19 +166,19 @@ public function browse() {
SELECT id, label
FROM civicrm_custom_field
WHERE option_group_id = %1";
- $params = array(
- 1 => array($optionGroupID, 'Integer'),
- 2 => array($this->_fid, 'Integer'),
- );
+ $params = [
+ 1 => [$optionGroupID, 'Integer'],
+ 2 => [$this->_fid, 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $reusedNames = array();
+ $reusedNames = [];
if ($dao->N > 1) {
while ($dao->fetch()) {
$reusedNames[] = $dao->label;
}
$reusedNames = implode(', ', $reusedNames);
$newTitle = ts('%1 - Multiple Choice Options',
- array(1 => $reusedNames)
+ [1 => $reusedNames]
);
CRM_Utils_System::setTitle($newTitle);
$this->assign('reusedNames', $reusedNames);
@@ -167,7 +208,6 @@ public function edit($action) {
$controller->setEmbedded(TRUE);
$controller->process();
$controller->run();
- $this->browse();
}
/**
@@ -189,16 +229,21 @@ public function run() {
);
if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
- CRM_Core_Error::fatal("You cannot add or edit muliple choice options in a reserved custom field-set.");
+ CRM_Core_Error::fatal("You cannot add or edit multiple choice options in a reserved custom field-set.");
}
+ $optionGroupId = $this->getOptionGroupId($this->_fid);
+ $isOptionGroupLocked = $optionGroupId ? $this->isOptionGroupLocked($optionGroupId) : FALSE;
+ $this->assign('optionGroupId', $optionGroupId);
+ $this->assign('isOptionGroupLocked', $isOptionGroupLocked);
+
//as url contain $gid so append breadcrumb dynamically.
- $breadcrumb = array(
- array(
+ $breadcrumb = [
+ [
'title' => ts('Custom Data Fields'),
'url' => CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&gid=' . $this->_gid),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadcrumb);
if ($this->_fid) {
@@ -206,7 +251,7 @@ public function run() {
$this->assign('fid', $this->_fid);
$this->assign('gid', $this->_gid);
$this->assign('fieldTitle', $fieldTitle);
- CRM_Utils_System::setTitle(ts('%1 - Multiple Choice Options', array(1 => $fieldTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Multiple Choice Options', [1 => $fieldTitle]));
}
// get the requested action
@@ -222,7 +267,7 @@ public function run() {
$this, FALSE, 0
);
- // what action to take ?
+ // take action in addition to default browse ?
if (($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD |
CRM_Core_Action::VIEW | CRM_Core_Action::DELETE
)
@@ -232,11 +277,43 @@ public function run() {
// no browse for edit/update/view
$this->edit($action);
}
- else {
- $this->browse();
+ elseif ($action & CRM_Core_Action::MAP) {
+ $this->alphabetize();
}
+ $this->browse();
+
// Call the parents run method
return parent::run();
}
+ /**
+ * Gets the "is_locked" status for the provided option group
+ *
+ * @param int $optionGroupId
+ *
+ * @return bool
+ */
+ private function isOptionGroupLocked($optionGroupId) {
+ return (bool) CRM_Core_DAO::getFieldValue(
+ CRM_Core_DAO_OptionGroup::class,
+ $optionGroupId,
+ 'is_locked'
+ );
+ }
+
+ /**
+ * Gets the associated "option_group_id" for a custom field
+ *
+ * @param int $customFieldId
+ *
+ * @return int
+ */
+ private function getOptionGroupId($customFieldId) {
+ return (int) CRM_Core_DAO::getFieldValue(
+ CRM_Core_DAO_CustomField::class,
+ $customFieldId,
+ 'option_group_id'
+ );
+ }
+
}
diff --git a/CRM/Cxn/ApiRouter.php b/CRM/Cxn/ApiRouter.php
index 63a1a7572bd4..4ea90fdac053 100644
--- a/CRM/Cxn/ApiRouter.php
+++ b/CRM/Cxn/ApiRouter.php
@@ -1,9 +1,9 @@
array(json_encode($appMeta), 'String'),
- 2 => array($appMeta['appId'], 'String'),
- ));
+ CRM_Core_DAO::executeQuery('UPDATE civicrm_cxn SET app_meta = %1 WHERE app_guid = %2', [
+ 1 => [json_encode($appMeta), 'String'],
+ 2 => [$appMeta['appId'], 'String'],
+ ]);
}
/**
@@ -160,12 +160,12 @@ public static function createApiServer() {
$apiServer->setLog(new CRM_Utils_SystemLogger());
$apiServer->setCertValidator(self::createCertificateValidator());
$apiServer->setHttp(CRM_Cxn_CiviCxnHttp::singleton());
- $apiServer->setRouter(array('CRM_Cxn_ApiRouter', 'route'));
+ $apiServer->setRouter(['CRM_Cxn_ApiRouter', 'route']);
return $apiServer;
}
/**
- * @return DefaultCertificateValidator
+ * @return \Civi\Cxn\Rpc\DefaultCertificateValidator
* @throws CRM_Core_Exception
*/
public static function createCertificateValidator() {
diff --git a/CRM/Cxn/CiviCxnHttp.php b/CRM/Cxn/CiviCxnHttp.php
index f2b2c6357c8c..f8acdb970432 100644
--- a/CRM/Cxn/CiviCxnHttp.php
+++ b/CRM/Cxn/CiviCxnHttp.php
@@ -22,11 +22,11 @@ class CRM_Cxn_CiviCxnHttp extends \Civi\Cxn\Rpc\Http\PhpHttp {
*/
public static function singleton($fresh = FALSE) {
if (self::$singleton === NULL || $fresh) {
- $cache = CRM_Utils_Cache::create(array(
+ $cache = CRM_Utils_Cache::create([
'name' => 'CiviCxnHttp',
- 'type' => Civi::settings()->get('debug_enabled') ? 'ArrayCache' : array('SqlGroup', 'ArrayCache'),
+ 'type' => Civi::settings()->get('debug_enabled') ? 'ArrayCache' : ['SqlGroup', 'ArrayCache'],
'prefetch' => FALSE,
- ));
+ ]);
self::$singleton = new CRM_Cxn_CiviCxnHttp($cache);
}
@@ -50,11 +50,11 @@ public function __construct($cache) {
* @return array
* array($headers, $blob, $code)
*/
- public function send($verb, $url, $blob, $headers = array()) {
+ public function send($verb, $url, $blob, $headers = []) {
$lowVerb = strtolower($verb);
if ($lowVerb === 'get' && $this->cache) {
- $cachePath = 'get/' . md5($url);
+ $cachePath = 'get_' . md5($url);
$cacheLine = $this->cache->get($cachePath);
if ($cacheLine && $cacheLine['expires'] > CRM_Utils_Time::getTimeRaw()) {
return $cacheLine['data'];
@@ -66,12 +66,12 @@ public function send($verb, $url, $blob, $headers = array()) {
if ($lowVerb === 'get' && $this->cache) {
$expires = CRM_Utils_Http::parseExpiration($result[0]);
if ($expires !== NULL) {
- $cachePath = 'get/' . md5($url);
- $cacheLine = array(
+ $cachePath = 'get_' . md5($url);
+ $cacheLine = [
'url' => $url,
'expires' => $expires,
'data' => $result,
- );
+ ];
$this->cache->set($cachePath, $cacheLine);
}
}
@@ -93,9 +93,9 @@ public function send($verb, $url, $blob, $headers = array()) {
protected function createStreamOpts($verb, $url, $blob, $headers) {
$result = parent::createStreamOpts($verb, $url, $blob, $headers);
- $caConfig = CA_Config_Stream::probe(array(
+ $caConfig = CA_Config_Stream::probe([
'verify_peer' => (bool) Civi::settings()->get('verifySSL'),
- ));
+ ]);
if ($caConfig->isEnableSSL()) {
$result['ssl'] = $caConfig->toStreamOptions();
}
@@ -106,4 +106,11 @@ protected function createStreamOpts($verb, $url, $blob, $headers) {
return $result;
}
+ /**
+ * @return \CRM_Utils_Cache_Interface|null
+ */
+ public function getCache() {
+ return $this->cache;
+ }
+
}
diff --git a/CRM/Cxn/CiviCxnStore.php b/CRM/Cxn/CiviCxnStore.php
index dc25dc8c51ba..972fbfa1dbc0 100644
--- a/CRM/Cxn/CiviCxnStore.php
+++ b/CRM/Cxn/CiviCxnStore.php
@@ -5,14 +5,14 @@
*/
class CRM_Cxn_CiviCxnStore implements Civi\Cxn\Rpc\CxnStore\CxnStoreInterface {
- protected $cxns = array();
+ protected $cxns = [];
/**
* @inheritDoc
*/
public function getAll() {
if (!$this->cxns) {
- $this->cxns = array();
+ $this->cxns = [];
$dao = new CRM_Cxn_DAO_Cxn();
$dao->find();
while ($dao->fetch()) {
@@ -71,9 +71,9 @@ public function add($cxn) {
WHERE created_date IS NULL
AND cxn_guid = %1
';
- CRM_Core_DAO::executeQuery($sql, array(
- 1 => array($cxn['cxnId'], 'String'),
- ));
+ CRM_Core_DAO::executeQuery($sql, [
+ 1 => [$cxn['cxnId'], 'String'],
+ ]);
$this->cxns[$cxn['cxnId']] = $cxn;
}
@@ -82,9 +82,9 @@ public function add($cxn) {
* @inheritDoc
*/
public function remove($cxnId) {
- CRM_Core_DAO::executeQuery('DELETE FROM civicrm_cxn WHERE cxn_guid = %1', array(
- 1 => array($cxnId, 'String'),
- ));
+ CRM_Core_DAO::executeQuery('DELETE FROM civicrm_cxn WHERE cxn_guid = %1', [
+ 1 => [$cxnId, 'String'],
+ ]);
unset($this->cxns[$cxnId]);
}
@@ -95,14 +95,14 @@ public function remove($cxnId) {
*/
protected function convertDaoToCxn($dao) {
$appMeta = json_decode($dao->app_meta, TRUE);
- return array(
+ return [
'cxnId' => $dao->cxn_guid,
'secret' => $dao->secret,
'appId' => $dao->app_guid,
'appUrl' => $appMeta['appUrl'],
'siteUrl' => CRM_Cxn_BAO_Cxn::getSiteCallbackUrl(),
'perm' => json_decode($dao->perm, TRUE),
- );
+ ];
}
/**
diff --git a/CRM/Cxn/DAO/Cxn.php b/CRM/Cxn/DAO/Cxn.php
index 42778d9a85aa..7713ee953ff5 100644
--- a/CRM/Cxn/DAO/Cxn.php
+++ b/CRM/Cxn/DAO/Cxn.php
@@ -1,291 +1,297 @@
__table = 'civicrm_cxn';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Connection ID') ,
- 'description' => 'Connection ID',
- 'required' => true,
+ 'title' => ts('Connection ID'),
+ 'description' => ts('Connection ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_cxn.id',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'app_guid' => array(
+ ],
+ 'app_guid' => [
'name' => 'app_guid',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Application GUID') ,
- 'description' => 'Application GUID',
+ 'title' => ts('Application GUID'),
+ 'description' => ts('Application GUID'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_cxn.app_guid',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'app_meta' => array(
+ ],
+ 'app_meta' => [
'name' => 'app_meta',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Application Metadata (JSON)') ,
- 'description' => 'Application Metadata (JSON)',
+ 'title' => ts('Application Metadata (JSON)'),
+ 'description' => ts('Application Metadata (JSON)'),
+ 'where' => 'civicrm_cxn.app_meta',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'cxn_guid' => array(
+ ],
+ 'cxn_guid' => [
'name' => 'cxn_guid',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Connection GUID') ,
- 'description' => 'Connection GUID',
+ 'title' => ts('Connection GUID'),
+ 'description' => ts('Connection GUID'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_cxn.cxn_guid',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'secret' => array(
+ ],
+ 'secret' => [
'name' => 'secret',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Secret') ,
- 'description' => 'Shared secret',
+ 'title' => ts('Secret'),
+ 'description' => ts('Shared secret'),
+ 'where' => 'civicrm_cxn.secret',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'perm' => array(
+ ],
+ 'perm' => [
'name' => 'perm',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Perm') ,
- 'description' => 'Permissions approved for the service (JSON)',
+ 'title' => ts('Perm'),
+ 'description' => ts('Permissions approved for the service (JSON)'),
+ 'where' => 'civicrm_cxn.perm',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'options' => array(
+ ],
+ 'options' => [
'name' => 'options',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Options') ,
- 'description' => 'Options for the service (JSON)',
+ 'title' => ts('Options'),
+ 'description' => ts('Options for the service (JSON)'),
+ 'where' => 'civicrm_cxn.options',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'serialize' => self::SERIALIZE_JSON,
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is connection currently enabled?',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is connection currently enabled?'),
+ 'where' => 'civicrm_cxn.is_active',
'default' => '1',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Created Date') ,
- 'description' => 'When was the connection was created.',
- 'required' => false,
+ 'title' => ts('Created Date'),
+ 'description' => ts('When was the connection was created.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_cxn.created_date',
'default' => 'NULL',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'modified_date' => array(
+ ],
+ 'modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Modified Date') ,
- 'description' => 'When the connection was created or modified.',
- 'required' => false,
+ 'title' => ts('Modified Date'),
+ 'description' => ts('When the connection was created or modified.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_cxn.modified_date',
'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- 'fetched_date' => array(
+ ],
+ 'fetched_date' => [
'name' => 'fetched_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Fetched Date') ,
- 'description' => 'The last time the application metadata was fetched.',
- 'required' => false,
+ 'title' => ts('Fetched Date'),
+ 'description' => ts('The last time the application metadata was fetched.'),
+ 'required' => FALSE,
+ 'where' => 'civicrm_cxn.fetched_date',
'default' => 'NULL',
'table_name' => 'civicrm_cxn',
'entity' => 'Cxn',
'bao' => 'CRM_Cxn_BAO_Cxn',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -293,10 +299,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'cxn', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'cxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -304,34 +311,40 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'cxn', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'cxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_appid' => array(
+ $indices = [
+ 'UI_appid' => [
'name' => 'UI_appid',
- 'field' => array(
+ 'field' => [
0 => 'app_guid',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_cxn::1::app_guid',
- ) ,
- 'UI_keypair_cxnid' => array(
+ ],
+ 'UI_keypair_cxnid' => [
'name' => 'UI_keypair_cxnid',
- 'field' => array(
+ 'field' => [
0 => 'cxn_guid',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_cxn::1::cxn_guid',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Dashlet/Page/Activity.php b/CRM/Dashlet/Page/Activity.php
index a48deb4ee7a0..74d81a90f24d 100644
--- a/CRM/Dashlet/Page/Activity.php
+++ b/CRM/Dashlet/Page/Activity.php
@@ -1,9 +1,9 @@
assign('contactID', $contactID);
$this->assign('contactId', $contactID);
- $context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'dashlet');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'dashlet');
$this->assign('context', $context);
// a user can always view their own activity
diff --git a/CRM/Dashlet/Page/AllCases.php b/CRM/Dashlet/Page/AllCases.php
index a6f6078a1122..50fc6f5cba5d 100644
--- a/CRM/Dashlet/Page/AllCases.php
+++ b/CRM/Dashlet/Page/AllCases.php
@@ -1,9 +1,9 @@
assign('context', $context);
//check for civicase access.
@@ -53,12 +53,17 @@ public function run() {
CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
}
- $session = CRM_Core_Session::singleton();
- $userID = $session->get('userID');
- $upcoming = CRM_Case_BAO_Case::getCases(TRUE, $userID, 'upcoming', $context);
+ $controller = new CRM_Core_Controller_Simple('CRM_Case_Form_Search',
+ ts('Case'), CRM_Core_Action::BROWSE,
+ NULL,
+ FALSE, FALSE, TRUE
+ );
+ $controller->setEmbedded(TRUE);
+ $controller->process();
+ $controller->run();
- if (!empty($upcoming)) {
- $this->assign('AllCases', $upcoming);
+ if (CRM_Case_BAO_Case::getCases(TRUE, ['type' => 'any'], 'dashboard', TRUE)) {
+ $this->assign('casePresent', TRUE);
}
return parent::run();
}
diff --git a/CRM/Dashlet/Page/Blog.php b/CRM/Dashlet/Page/Blog.php
index 6e3efc9cac56..03ea32f1c443 100644
--- a/CRM/Dashlet/Page/Blog.php
+++ b/CRM/Dashlet/Page/Blog.php
@@ -1,9 +1,9 @@
fetch()) {
- $expire = time() - (60 * 60 * 24 * self::CACHE_DAYS);
- // Refresh data after CACHE_DAYS
- if (strtotime($cache->created_date) < $expire) {
- $new_data = $this->getFeeds();
- // If fetching the new rss feed was successful, return it
- // Otherwise use the old cached data - it's better than nothing
- if ($new_data) {
- return $new_data;
- }
+ $value = Civi::cache('community_messages')->get('dashboard_newsfeed');
+
+ if (!$value) {
+ $value = $this->getFeeds();
+
+ if ($value) {
+ Civi::cache('community_messages')->set('dashboard_newsfeed', $value, (60 * 60 * 24 * self::CACHE_DAYS));
}
- return unserialize($cache->data);
}
- return $this->getFeeds();
+
+ return $value;
}
/**
- * Fetch all feeds & cache results.
+ * Fetch all feeds.
*
* @return array
*/
@@ -101,10 +95,9 @@ protected function getFeeds() {
$newsFeed = $this->getFeed($this->getNewsUrl());
// If unable to fetch the feed, return empty results.
if (!$newsFeed) {
- return array();
+ return [];
}
$feeds = $this->formatItems($newsFeed);
- CRM_Core_BAO_Cache::setItem($feeds, 'dashboard', 'newsfeed');
return $feeds;
}
@@ -130,15 +123,15 @@ protected function getFeed($url) {
* @return array
*/
protected function formatItems($feed) {
- $result = array();
+ $result = [];
if ($feed && !empty($feed->channel)) {
foreach ($feed->channel as $channel) {
- $content = array(
+ $content = [
'title' => (string) $channel->title,
'description' => (string) $channel->description,
'name' => strtolower(CRM_Utils_String::munge($channel->title, '-')),
- 'items' => array(),
- );
+ 'items' => [],
+ ];
foreach ($channel->item as $item) {
$item = (array) $item;
$item['title'] = strip_tags($item['title']);
diff --git a/CRM/Dashlet/Page/CaseDashboard.php b/CRM/Dashlet/Page/CaseDashboard.php
index 0765646103f4..92580cb92646 100644
--- a/CRM/Dashlet/Page/CaseDashboard.php
+++ b/CRM/Dashlet/Page/CaseDashboard.php
@@ -1,9 +1,9 @@
get('userID');
- $summary = CRM_Case_BAO_Case::getCasesSummary(TRUE, $userID);
+ $summary = CRM_Case_BAO_Case::getCasesSummary(TRUE);
if (!empty($summary)) {
$this->assign('casesSummary', $summary);
diff --git a/CRM/Dashlet/Page/GettingStarted.php b/CRM/Dashlet/Page/GettingStarted.php
index 775726b06d94..d9d44fba9944 100644
--- a/CRM/Dashlet/Page/GettingStarted.php
+++ b/CRM/Dashlet/Page/GettingStarted.php
@@ -1,9 +1,9 @@
array(
+ public static $_tokens = [
+ 'crmurl' => [
'configbackend' => 'civicrm/admin/configtask',
- ),
- );
+ ],
+ ];
/**
* Get the final, usable URL string (after interpolating any variables)
@@ -70,7 +71,7 @@ public function gettingStartedUrl() {
* List gettingStarted page as dashlet.
*/
public function run() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'dashlet');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'dashlet');
// Assign smarty variables.
$this->assign('context', $context);
@@ -87,27 +88,21 @@ public function run() {
* @return array
*/
private function _gettingStarted() {
- // Fetch data from cache
- $cache = CRM_Core_DAO::executeQuery("SELECT data, created_date FROM civicrm_cache
- WHERE group_name = 'dashboard' AND path = 'gettingStarted'");
- if ($cache->fetch()) {
- $expire = time() - (60 * 60 * 24 * self::CACHE_DAYS);
- // Refresh data after CACHE_DAYS
- if (strtotime($cache->created_date) < $expire) {
- $new_data = $this->_getHtml($this->gettingStartedUrl());
- // If fetching the new html was successful, return it
- // Otherwise use the old cached data - it's better than nothing
- if ($new_data) {
- return $new_data;
- }
+ $value = Civi::cache('community_messages')->get('dashboard_gettingStarted');
+
+ if (!$value) {
+ $value = $this->_getHtml($this->gettingStartedUrl());
+
+ if ($value) {
+ Civi::cache('community_messages')->set('dashboard_gettingStarted', $value, (60 * 60 * 24 * self::CACHE_DAYS));
}
- return unserialize($cache->data);
}
- return $this->_getHtml($this->gettingStartedUrl());
+
+ return $value;
}
/**
- * Get html and cache results.
+ * Get html.
*
* @param $url
*
@@ -115,22 +110,18 @@ private function _gettingStarted() {
* array of gettingStarted items; or NULL if not available
*/
public function _getHtml($url) {
-
$httpClient = new CRM_Utils_HttpClient(self::CHECK_TIMEOUT);
list ($status, $html) = $httpClient->get($url);
+
if ($status !== CRM_Utils_HttpClient::STATUS_OK) {
return NULL;
}
$tokensList = CRM_Utils_Token::getTokens($html);
$this->replaceLinkToken($tokensList, $html);
- if ($html) {
- CRM_Core_BAO_Cache::setItem($html, 'dashboard', 'gettingStarted');
- }
return $html;
}
-
/**
* @param array $tokensList
* @param string $str
diff --git a/CRM/Dashlet/Page/MyCases.php b/CRM/Dashlet/Page/MyCases.php
index 51d9b06385a5..071102fa3b44 100644
--- a/CRM/Dashlet/Page/MyCases.php
+++ b/CRM/Dashlet/Page/MyCases.php
@@ -1,9 +1,9 @@
assign('context', $context);
//check for civicase access.
@@ -53,12 +53,17 @@ public function run() {
CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
}
- $session = CRM_Core_Session::singleton();
- $userID = $session->get('userID');
- $upcoming = CRM_Case_BAO_Case::getCases(FALSE, $userID, 'upcoming', $context);
+ $controller = new CRM_Core_Controller_Simple('CRM_Case_Form_Search',
+ ts('Case'), CRM_Core_Action::BROWSE,
+ NULL,
+ FALSE, FALSE, TRUE
+ );
+ $controller->setEmbedded(TRUE);
+ $controller->process();
+ $controller->run();
- if (!empty($upcoming)) {
- $this->assign('upcomingCases', $upcoming);
+ if (CRM_Case_BAO_Case::getCases(FALSE, ['type' => 'any'], $context, TRUE)) {
+ $this->assign('casePresent', TRUE);
}
return parent::run();
}
diff --git a/CRM/Dedupe/BAO/QueryBuilder.php b/CRM/Dedupe/BAO/QueryBuilder.php
index 3daff16951f3..1137be40c940 100644
--- a/CRM/Dedupe/BAO/QueryBuilder.php
+++ b/CRM/Dedupe/BAO/QueryBuilder.php
@@ -3,6 +3,7 @@
* Class CRM_Dedupe_BAO_QueryBuilder
*/
class CRM_Dedupe_BAO_QueryBuilder {
+
/**
* @param $rg
* @param string $strID1
diff --git a/CRM/Dedupe/BAO/QueryBuilder/IndividualGeneral.php b/CRM/Dedupe/BAO/QueryBuilder/IndividualGeneral.php
index 00be6f40b0b3..373866f7a868 100644
--- a/CRM/Dedupe/BAO/QueryBuilder/IndividualGeneral.php
+++ b/CRM/Dedupe/BAO/QueryBuilder/IndividualGeneral.php
@@ -5,6 +5,7 @@
* Class CRM_Dedupe_BAO_QueryBuilder_IndividualGeneral
*/
class CRM_Dedupe_BAO_QueryBuilder_IndividualGeneral extends CRM_Dedupe_BAO_QueryBuilder {
+
/**
* @param $rg
*
@@ -41,7 +42,7 @@ public static function record($rg) {
$query .= " AND (contact1.middle_name IS NULL or contact1.middle_name = '$middle_name')\n";
}
- return array("civicrm_contact.{$rg->name}.{$rg->threshold}" => $query);
+ return ["civicrm_contact.{$rg->name}.{$rg->threshold}" => $query];
}
/**
@@ -66,7 +67,7 @@ public static function internal($rg) {
AND (contact1.middle_name IS NULL OR contact2.middle_name IS NULL OR contact1.middle_name = contact2.middle_name)
AND (contact1.birth_date IS NULL OR contact2.birth_date IS NULL OR contact1.birth_date = contact2.birth_date)
AND " . self::internalFilters($rg);
- return array("civicrm_contact.{$rg->name}.{$rg->threshold}" => $query);
+ return ["civicrm_contact.{$rg->name}.{$rg->threshold}" => $query];
}
}
diff --git a/CRM/Dedupe/BAO/QueryBuilder/IndividualSupervised.php b/CRM/Dedupe/BAO/QueryBuilder/IndividualSupervised.php
index e150f44fd06a..4928fa0a3758 100644
--- a/CRM/Dedupe/BAO/QueryBuilder/IndividualSupervised.php
+++ b/CRM/Dedupe/BAO/QueryBuilder/IndividualSupervised.php
@@ -15,25 +15,25 @@ class CRM_Dedupe_BAO_QueryBuilder_IndividualSupervised extends CRM_Dedupe_BAO_Qu
*/
public static function record($rg) {
- $civicrm_contact = CRM_Utils_Array::value('civicrm_contact', $rg->params, array());
- $civicrm_email = CRM_Utils_Array::value('civicrm_email', $rg->params, array());
+ $civicrm_contact = CRM_Utils_Array::value('civicrm_contact', $rg->params, []);
+ $civicrm_email = CRM_Utils_Array::value('civicrm_email', $rg->params, []);
- $params = array(
- 1 => array(
+ $params = [
+ 1 => [
CRM_Utils_Array::value('first_name', $civicrm_contact, ''),
'String',
- ),
- 2 => array(
+ ],
+ 2 => [
CRM_Utils_Array::value('last_name', $civicrm_contact, ''),
'String',
- ),
- 3 => array(
+ ],
+ 3 => [
CRM_Utils_Array::value('email', $civicrm_email, ''),
'String',
- ),
- );
+ ],
+ ];
- return array(
+ return [
"civicrm_contact.{$rg->name}.{$rg->threshold}" => CRM_Core_DAO::composeQuery("
SELECT contact.id as id1, {$rg->threshold} as weight
FROM civicrm_contact as contact
@@ -42,7 +42,7 @@ public static function record($rg) {
AND first_name = %1
AND last_name = %2
AND email = %3", $params, TRUE),
- );
+ ];
}
/**
@@ -65,9 +65,9 @@ public static function internal($rg) {
email1.email=email2.email
WHERE contact1.contact_type = 'Individual'");
- return array(
+ return [
"civicrm_contact.{$rg->name}.{$rg->threshold}" => $query,
- );
+ ];
}
}
diff --git a/CRM/Dedupe/BAO/QueryBuilder/IndividualUnsupervised.php b/CRM/Dedupe/BAO/QueryBuilder/IndividualUnsupervised.php
index 60858b7dc6d0..1c2e9b23735c 100644
--- a/CRM/Dedupe/BAO/QueryBuilder/IndividualUnsupervised.php
+++ b/CRM/Dedupe/BAO/QueryBuilder/IndividualUnsupervised.php
@@ -1,9 +1,9 @@
params, array());
+ $civicrm_email = CRM_Utils_Array::value('civicrm_email', $rg->params, []);
- $params = array(
- 1 => array(CRM_Utils_Array::value('email', $civicrm_email, ''), 'String'),
- );
+ $params = [
+ 1 => [CRM_Utils_Array::value('email', $civicrm_email, ''), 'String'],
+ ];
- return array(
+ return [
"civicrm_contact.{$rg->name}.{$rg->threshold}" => CRM_Core_DAO::composeQuery("
SELECT contact.id as id1, {$rg->threshold} as weight
FROM civicrm_contact as contact
JOIN civicrm_email as email ON email.contact_id=contact.id
WHERE contact_type = 'Individual'
AND email = %1", $params, TRUE),
- );
+ ];
}
/**
@@ -68,7 +68,7 @@ public static function internal($rg) {
email1.email=email2.email
WHERE contact1.contact_type = 'Individual'
AND " . self::internalFilters($rg);
- return array("civicrm_contact.{$rg->name}.{$rg->threshold}" => $query);
+ return ["civicrm_contact.{$rg->name}.{$rg->threshold}" => $query];
}
/**
@@ -109,7 +109,7 @@ public static function internalOptimized($rg) {
AND contact2.contact_type='Individual'
AND " . self::internalFilters($rg);
- return array("civicrm_contact.{$rg->name}.{$rg->threshold}" => $query);
+ return ["civicrm_contact.{$rg->name}.{$rg->threshold}" => $query];
}
}
diff --git a/CRM/Dedupe/BAO/Rule.php b/CRM/Dedupe/BAO/Rule.php
index 6484e934a639..5bb117b68863 100644
--- a/CRM/Dedupe/BAO/Rule.php
+++ b/CRM/Dedupe/BAO/Rule.php
@@ -1,9 +1,9 @@
rule_field}, 1, {$this->rule_length}) = SUBSTR(t2.{$this->rule_field}, 1, {$this->rule_length})");
- $using = array($this->rule_field);
+ $where = [];
+ $on = ["SUBSTR(t1.{$this->rule_field}, 1, {$this->rule_length}) = SUBSTR(t2.{$this->rule_field}, 1, {$this->rule_length})"];
+ $entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($this->rule_table));
+ $fields = civicrm_api3($entity, 'getfields', ['action' => 'create'])['values'];
+
+ $innerJoinClauses = [
+ "t1.{$this->rule_field} IS NOT NULL",
+ "t2.{$this->rule_field} IS NOT NULL",
+ "t1.{$this->rule_field} = t2.{$this->rule_field}",
+ ];
+ if ($fields[$this->rule_field]['type'] === CRM_Utils_Type::T_DATE) {
+ $innerJoinClauses[] = "t1.{$this->rule_field} > '1000-01-01'";
+ $innerJoinClauses[] = "t2.{$this->rule_field} > '1000-01-01'";
+ }
+ else {
+ $innerJoinClauses[] = "t1.{$this->rule_field} <> ''";
+ $innerJoinClauses[] = "t2.{$this->rule_field} <> ''";
+ }
switch ($this->rule_table) {
case 'civicrm_contact':
@@ -92,8 +109,8 @@ public function sql() {
case 'civicrm_address':
$id = 'contact_id';
$on[] = 't1.location_type_id = t2.location_type_id';
- $using[] = 'location_type_id';
- if ($this->params['civicrm_address']['location_type_id']) {
+ $innerJoinClauses[] = 't1.location_type_id = t2.location_type_id';
+ if (!empty($this->params['civicrm_address']['location_type_id'])) {
$locTypeId = CRM_Utils_Type::escape($this->params['civicrm_address']['location_type_id'], 'Integer', FALSE);
if ($locTypeId) {
$where[] = "t1.location_type_id = $locTypeId";
@@ -152,7 +169,6 @@ public function sql() {
if ($this->rule_length) {
$where[] = "SUBSTR(t1.{$this->rule_field}, 1, {$this->rule_length}) = SUBSTR('$str', 1, {$this->rule_length})";
$where[] = "t1.{$this->rule_field} IS NOT NULL";
- $where[] = "t1.{$this->rule_field} <> ''";
}
else {
$where[] = "t1.{$this->rule_field} = '$str'";
@@ -163,19 +179,17 @@ public function sql() {
$from = "{$this->rule_table} t1 JOIN {$this->rule_table} t2 ON (" . implode(' AND ', $on) . ")";
}
else {
- $from = "{$this->rule_table} t1 JOIN {$this->rule_table} t2 USING (" . implode(', ', $using) . ")";
+ $from = "{$this->rule_table} t1 INNER JOIN {$this->rule_table} t2 ON (" . implode(' AND ', $innerJoinClauses) . ")";
}
}
// finish building WHERE, also limit the results if requested
if (!$this->params) {
$where[] = "t1.$id < t2.$id";
- $where[] = "t1.{$this->rule_field} IS NOT NULL";
- $where[] = "t1.{$this->rule_field} <> ''";
}
$query = "SELECT $select FROM $from WHERE " . implode(' AND ', $where);
if ($this->contactIds) {
- $cids = array();
+ $cids = [];
foreach ($this->contactIds as $cid) {
$cids[] = CRM_Utils_Type::escape($cid, 'Integer');
}
@@ -211,7 +225,7 @@ public static function dedupeRuleFields($params) {
$ruleBao = new CRM_Dedupe_BAO_Rule();
$ruleBao->dedupe_rule_group_id = $rgBao->id;
$ruleBao->find();
- $ruleFields = array();
+ $ruleFields = [];
while ($ruleBao->fetch()) {
$ruleFields[] = $ruleBao->rule_field;
}
diff --git a/CRM/Dedupe/BAO/RuleGroup.php b/CRM/Dedupe/BAO/RuleGroup.php
index b3b0ef128aad..61f70b2d279e 100644
--- a/CRM/Dedupe/BAO/RuleGroup.php
+++ b/CRM/Dedupe/BAO/RuleGroup.php
@@ -1,9 +1,9 @@
'civicrm_address.country_id',
'civicrm_county.name' => 'civicrm_address.county_id',
'civicrm_state_province.name' => 'civicrm_address.state_province_id',
@@ -87,9 +92,9 @@ public static function &supportedFields($requestedType) {
'email_greeting.label' => 'civicrm_contact.email_greeting_id',
'postal_greeting.label' => 'civicrm_contact.postal_greeting_id',
'civicrm_phone.phone' => 'civicrm_phone.phone_numeric',
- );
+ ];
// the table names we support in dedupe rules - a filter for importableFields()
- $supportedTables = array(
+ $supportedTables = [
'civicrm_address',
'civicrm_contact',
'civicrm_email',
@@ -97,9 +102,9 @@ public static function &supportedFields($requestedType) {
'civicrm_note',
'civicrm_openid',
'civicrm_phone',
- );
+ ];
- foreach (array('Individual', 'Organization', 'Household') as $ctype) {
+ foreach (['Individual', 'Organization', 'Household'] as $ctype) {
// take the table.field pairs and their titles from importableFields() if the table is supported
foreach (CRM_Contact_BAO_Contact::importableFields($ctype) as $iField) {
if (isset($iField['where'])) {
@@ -114,6 +119,13 @@ public static function &supportedFields($requestedType) {
$fields[$ctype][$table][$field] = $iField['title'];
}
}
+ // Note that most of the fields available come from 'importable fields' -
+ // I thought about making this field 'importable' but it felt like there might be unknown consequences
+ // so I opted for just adding it in & securing it with a unit test.
+ // Example usage of sort_name - It is possible to alter sort name via hook so 2 organization names might differ as in
+ // Justice League vs The Justice League but these could have the same sort_name if 'the the'
+ // exension is installed (https://github.com/eileenmcnaughton/org.wikimedia.thethe)
+ $fields[$ctype]['civicrm_contact']['sort_name'] = ts('Sort Name');
// add custom data fields
foreach (CRM_Core_BAO_CustomGroup::getTree($ctype, NULL, NULL, -1) as $key => $cg) {
if (!is_int($key)) {
@@ -126,7 +138,7 @@ public static function &supportedFields($requestedType) {
}
}
CRM_Utils_Hook::dupeQuery(CRM_Core_DAO::$_nullObject, 'supportedFields', $fields);
- return $fields[$requestedType];
+ return !empty($fields[$requestedType]) ? $fields[$requestedType] : [];
}
/**
@@ -152,7 +164,7 @@ public function tableQuery() {
CRM_Utils_File::isIncludable("CRM/Dedupe/BAO/QueryBuilder/{$this->name}.php")
) {
$command = empty($this->params) ? 'internal' : 'record';
- $queries = call_user_func(array("CRM_Dedupe_BAO_QueryBuilder_{$this->name}", $command), $this);
+ $queries = call_user_func(["CRM_Dedupe_BAO_QueryBuilder_{$this->name}", $command], $this);
}
else {
// All other rule groups have queries generated by the member dedupe
@@ -167,7 +179,7 @@ public function tableQuery() {
// Generate a SQL query for each rule in the rule group that is
// tailored to respect the param and contactId options provided.
- $queries = array();
+ $queries = [];
while ($bao->fetch()) {
$bao->contactIds = $this->contactIds;
$bao->params = $this->params;
@@ -183,7 +195,7 @@ public function tableQuery() {
// add an empty query fulfilling the pattern
if (!$queries) {
$this->noRules = TRUE;
- return array();
+ return [];
}
return $queries;
@@ -194,24 +206,25 @@ public function fillTable() {
$tableQueries = $this->tableQuery();
if ($this->params && !$this->noRules) {
- $tempTableQuery = "CREATE TEMPORARY TABLE dedupe (id1 int, weight int, UNIQUE UI_id1 (id1)) ENGINE=InnoDB";
- $insertClause = "INSERT INTO dedupe (id1, weight)";
- $groupByClause = "GROUP BY id1";
+ $this->temporaryTables['dedupe'] = CRM_Utils_SQL_TempTable::build()
+ ->setCategory('dedupe')
+ ->createWithColumns("id1 int, weight int, UNIQUE UI_id1 (id1)")->getName();
+ $insertClause = "INSERT INTO {$this->temporaryTables['dedupe']} (id1, weight)";
+ $groupByClause = "GROUP BY id1, weight";
$dupeCopyJoin = " JOIN dedupe_copy ON dedupe_copy.id1 = t1.column WHERE ";
}
else {
- $tempTableQuery = "CREATE TEMPORARY TABLE dedupe (id1 int, id2 int, weight int, UNIQUE UI_id1_id2 (id1, id2)) ENGINE=InnoDB";
- $insertClause = "INSERT INTO dedupe (id1, id2, weight)";
- $groupByClause = "GROUP BY id1, id2";
+ $this->temporaryTables['dedupe'] = CRM_Utils_SQL_TempTable::build()
+ ->setCategory('dedupe')
+ ->createWithColumns("id1 int, id2 int, weight int, UNIQUE UI_id1_id2 (id1, id2)")->getName();
+ $insertClause = "INSERT INTO {$this->temporaryTables['dedupe']} (id1, id2, weight)";
+ $groupByClause = "GROUP BY id1, id2, weight";
$dupeCopyJoin = " JOIN dedupe_copy ON dedupe_copy.id1 = t1.column AND dedupe_copy.id2 = t2.column WHERE ";
}
$patternColumn = '/t1.(\w+)/';
- $exclWeightSum = array();
+ $exclWeightSum = [];
- // create temp table
$dao = new CRM_Core_DAO();
- $dao->query($tempTableQuery);
-
CRM_Utils_Hook::dupeQuery($this, 'table', $tableQueries);
while (!empty($tableQueries)) {
@@ -233,8 +246,7 @@ public function fillTable() {
if ($searchWithinDupes) {
// get prepared to search within already found dupes if $searchWithinDupes flag is set
$dao->query("DROP TEMPORARY TABLE IF EXISTS dedupe_copy");
- $dao->query("CREATE TEMPORARY TABLE dedupe_copy SELECT * FROM dedupe WHERE weight >= {$weightSum}");
- $dao->free();
+ $dao->query("CREATE TEMPORARY TABLE dedupe_copy SELECT * FROM {$this->temporaryTables['dedupe']} WHERE weight >= {$weightSum}");
preg_match($patternColumn, $query, $matches);
$query = str_replace(' WHERE ', str_replace('column', $matches[1], $dupeCopyJoin), $query);
@@ -244,8 +256,7 @@ public function fillTable() {
if (preg_match('/dedupe_copy[\S\s]*(union)[\S\s]*dedupe_copy/i', $query, $matches, PREG_OFFSET_CAPTURE)) {
// Make a second temp table:
$dao->query("DROP TEMPORARY TABLE IF EXISTS dedupe_copy_2");
- $dao->query("CREATE TEMPORARY TABLE dedupe_copy_2 SELECT * FROM dedupe WHERE weight >= {$weightSum}");
- $dao->free();
+ $dao->query("CREATE TEMPORARY TABLE dedupe_copy_2 SELECT * FROM {$this->temporaryTables['dedupe']} WHERE weight >= {$weightSum}");
// After the union, use that new temp table:
$part1 = substr($query, 0, $matches[1][1]);
$query = $part1 . str_replace('dedupe_copy', 'dedupe_copy_2', substr($query, $matches[1][1]));
@@ -260,12 +271,11 @@ public function fillTable() {
// FIXME: we need to be more acurate with affected rows, especially for insert vs duplicate insert.
// And that will help optimize further.
$affectedRows = $dao->affectedRows();
- $dao->free();
// In an inclusive situation, failure of any query means no further processing -
if ($affectedRows == 0) {
// reset to make sure no further execution is done.
- $tableQueries = array();
+ $tableQueries = [];
break;
}
$weightSum = substr($fieldWeight, strrpos($fieldWeight, '.') + 1) + $weightSum;
@@ -282,7 +292,6 @@ public function fillTable() {
if ($dao->affectedRows() >= 1) {
$exclWeightSum[] = substr($fieldWeight, strrpos($fieldWeight, '.') + 1);
}
- $dao->free();
}
else {
// its a die situation
@@ -300,8 +309,8 @@ public function fillTable() {
*
* @return array
*/
- public static function isQuerySetInclusive($tableQueries, $threshold, $exclWeightSum = array()) {
- $input = array();
+ public static function isQuerySetInclusive($tableQueries, $threshold, $exclWeightSum = []) {
+ $input = [];
foreach ($tableQueries as $key => $query) {
$input[] = substr($key, strrpos($key, '.') + 1);
}
@@ -312,12 +321,12 @@ public static function isQuerySetInclusive($tableQueries, $threshold, $exclWeigh
}
if (count($input) == 1) {
- return array(FALSE, $input[0] < $threshold);
+ return [FALSE, $input[0] < $threshold];
}
$totalCombinations = 0;
for ($i = 0; $i < count($input); $i++) {
- $combination = array($input[$i]);
+ $combination = [$input[$i]];
if (array_sum($combination) >= $threshold) {
$totalCombinations++;
continue;
@@ -329,7 +338,7 @@ public static function isQuerySetInclusive($tableQueries, $threshold, $exclWeigh
}
}
}
- return array($totalCombinations == 1, $totalCombinations <= 0);
+ return [$totalCombinations == 1, $totalCombinations <= 0];
}
/**
@@ -337,9 +346,9 @@ public static function isQuerySetInclusive($tableQueries, $threshold, $exclWeigh
* @param $tableQueries
*/
public static function orderByTableCount(&$tableQueries) {
- static $tableCount = array();
+ static $tableCount = [];
- $tempArray = array();
+ $tempArray = [];
foreach ($tableQueries as $key => $query) {
$table = explode(".", $key);
$table = $table[0];
@@ -379,22 +388,22 @@ public function thresholdQuery($checkPermission = TRUE) {
list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('civicrm_contact');
$this->_aclWhere = $this->_aclWhere ? "AND {$this->_aclWhere}" : '';
}
- $query = "SELECT dedupe.id1 as id
- FROM dedupe JOIN civicrm_contact ON dedupe.id1 = civicrm_contact.id {$this->_aclFrom}
+ $query = "SELECT {$this->temporaryTables['dedupe']}.id1 as id
+ FROM {$this->temporaryTables['dedupe']} JOIN civicrm_contact ON {$this->temporaryTables['dedupe']}.id1 = civicrm_contact.id {$this->_aclFrom}
WHERE contact_type = '{$this->contact_type}' {$this->_aclWhere}
AND weight >= {$this->threshold}";
}
else {
$this->_aclWhere = ' AND c1.is_deleted = 0 AND c2.is_deleted = 0';
if ($checkPermission) {
- list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause(array('c1', 'c2'));
+ list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause(['c1', 'c2']);
$this->_aclWhere = $this->_aclWhere ? "AND {$this->_aclWhere}" : '';
}
- $query = "SELECT IF(dedupe.id1 < dedupe.id2, dedupe.id1, dedupe.id2) as id1,
- IF(dedupe.id1 < dedupe.id2, dedupe.id2, dedupe.id1) as id2, dedupe.weight
- FROM dedupe JOIN civicrm_contact c1 ON dedupe.id1 = c1.id
- JOIN civicrm_contact c2 ON dedupe.id2 = c2.id {$this->_aclFrom}
- LEFT JOIN civicrm_dedupe_exception exc ON dedupe.id1 = exc.contact_id1 AND dedupe.id2 = exc.contact_id2
+ $query = "SELECT IF({$this->temporaryTables['dedupe']}.id1 < {$this->temporaryTables['dedupe']}.id2, {$this->temporaryTables['dedupe']}.id1, {$this->temporaryTables['dedupe']}.id2) as id1,
+ IF({$this->temporaryTables['dedupe']}.id1 < {$this->temporaryTables['dedupe']}.id2, {$this->temporaryTables['dedupe']}.id2, {$this->temporaryTables['dedupe']}.id1) as id2, {$this->temporaryTables['dedupe']}.weight
+ FROM {$this->temporaryTables['dedupe']} JOIN civicrm_contact c1 ON {$this->temporaryTables['dedupe']}.id1 = c1.id
+ JOIN civicrm_contact c2 ON {$this->temporaryTables['dedupe']}.id2 = c2.id {$this->_aclFrom}
+ LEFT JOIN civicrm_dedupe_exception exc ON {$this->temporaryTables['dedupe']}.id1 = exc.contact_id1 AND {$this->temporaryTables['dedupe']}.id2 = exc.contact_id2
WHERE c1.contact_type = '{$this->contact_type}' AND
c2.contact_type = '{$this->contact_type}' {$this->_aclWhere}
AND weight >= {$this->threshold} AND exc.contact_id1 IS NULL";
@@ -427,12 +436,12 @@ public static function dedupeRuleFieldsWeight($params) {
$ruleBao = new CRM_Dedupe_BAO_Rule();
$ruleBao->dedupe_rule_group_id = $rgBao->id;
$ruleBao->find();
- $ruleFields = array();
+ $ruleFields = [];
while ($ruleBao->fetch()) {
$ruleFields[$ruleBao->rule_field] = $ruleBao->rule_weight;
}
- return array($ruleFields, $rgBao->threshold);
+ return [$ruleFields, $rgBao->threshold];
}
/**
@@ -443,7 +452,7 @@ public static function dedupeRuleFieldsWeight($params) {
* @param array $combos
* @param array $running
*/
- public static function combos($rgFields, $threshold, &$combos, $running = array()) {
+ public static function combos($rgFields, $threshold, &$combos, $running = []) {
foreach ($rgFields as $rgField => $weight) {
unset($rgFields[$rgField]);
$diff = $threshold - $weight;
@@ -478,7 +487,7 @@ public static function getByType($contactType = NULL) {
}
$dao->find();
- $result = array();
+ $result = [];
while ($dao->fetch()) {
$title = !empty($dao->title) ? $dao->title : (!empty($dao->name) ? $dao->name : $dao->contact_type);
@@ -488,7 +497,6 @@ public static function getByType($contactType = NULL) {
return $result;
}
-
/**
* Get the cached contact type for a particular rule group.
*
@@ -498,7 +506,7 @@ public static function getByType($contactType = NULL) {
*/
public static function getContactTypeForRuleGroup($rule_group_id) {
if (!isset(\Civi::$statics[__CLASS__]) || !isset(\Civi::$statics[__CLASS__]['rule_groups'])) {
- \Civi::$statics[__CLASS__]['rule_groups'] = array();
+ \Civi::$statics[__CLASS__]['rule_groups'] = [];
}
if (empty(\Civi::$statics[__CLASS__]['rule_groups'][$rule_group_id])) {
\Civi::$statics[__CLASS__]['rule_groups'][$rule_group_id]['contact_type'] = CRM_Core_DAO::getFieldValue(
diff --git a/CRM/Dedupe/DAO/Exception.php b/CRM/Dedupe/DAO/Exception.php
index 3b6b7e52b14b..cfc6bc3b9a0a 100644
--- a/CRM/Dedupe/DAO/Exception.php
+++ b/CRM/Dedupe/DAO/Exception.php
@@ -1,169 +1,161 @@
__table = 'civicrm_dedupe_exception';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id1', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id2', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id1', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id2', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dedupe Exception ID') ,
- 'description' => 'Unique dedupe exception id',
- 'required' => true,
+ 'title' => ts('Dedupe Exception ID'),
+ 'description' => ts('Unique dedupe exception id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_exception.id',
'table_name' => 'civicrm_dedupe_exception',
'entity' => 'Exception',
'bao' => 'CRM_Dedupe_DAO_Exception',
'localizable' => 0,
- ) ,
- 'contact_id1' => array(
+ ],
+ 'contact_id1' => [
'name' => 'contact_id1',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('First Dupe Contact ID') ,
- 'description' => 'FK to Contact ID',
+ 'title' => ts('First Dupe Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_exception.contact_id1',
'table_name' => 'civicrm_dedupe_exception',
'entity' => 'Exception',
'bao' => 'CRM_Dedupe_DAO_Exception',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'contact_id2' => array(
+ ],
+ 'contact_id2' => [
'name' => 'contact_id2',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Second Dupe Contact ID') ,
- 'description' => 'FK to Contact ID',
+ 'title' => ts('Second Dupe Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_exception.contact_id2',
'table_name' => 'civicrm_dedupe_exception',
'entity' => 'Exception',
'bao' => 'CRM_Dedupe_DAO_Exception',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -171,10 +163,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dedupe_exception', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dedupe_exception', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -182,26 +175,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dedupe_exception', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dedupe_exception', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contact_id1_contact_id2' => array(
+ $indices = [
+ 'UI_contact_id1_contact_id2' => [
'name' => 'UI_contact_id1_contact_id2',
- 'field' => array(
+ 'field' => [
0 => 'contact_id1',
1 => 'contact_id2',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_dedupe_exception::1::contact_id1::contact_id2',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Dedupe/DAO/Rule.php b/CRM/Dedupe/DAO/Rule.php
index 924e230f5215..806185c260a9 100644
--- a/CRM/Dedupe/DAO/Rule.php
+++ b/CRM/Dedupe/DAO/Rule.php
@@ -1,229 +1,225 @@
__table = 'civicrm_dedupe_rule';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'dedupe_rule_group_id', 'civicrm_dedupe_rule_group', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'dedupe_rule_group_id', 'civicrm_dedupe_rule_group', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dedupe Rule ID') ,
- 'description' => 'Unique dedupe rule id',
- 'required' => true,
+ 'title' => ts('Dedupe Rule ID'),
+ 'description' => ts('Unique dedupe rule id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_rule.id',
'table_name' => 'civicrm_dedupe_rule',
'entity' => 'Rule',
'bao' => 'CRM_Dedupe_BAO_Rule',
'localizable' => 0,
- ) ,
- 'dedupe_rule_group_id' => array(
+ ],
+ 'dedupe_rule_group_id' => [
'name' => 'dedupe_rule_group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dedupe Rule Group') ,
- 'description' => 'The id of the rule group this rule belongs to',
- 'required' => true,
+ 'title' => ts('Dedupe Rule Group'),
+ 'description' => ts('The id of the rule group this rule belongs to'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_rule.dedupe_rule_group_id',
'table_name' => 'civicrm_dedupe_rule',
'entity' => 'Rule',
'bao' => 'CRM_Dedupe_BAO_Rule',
'localizable' => 0,
'FKClassName' => 'CRM_Dedupe_DAO_RuleGroup',
- ) ,
- 'rule_table' => array(
+ ],
+ 'rule_table' => [
'name' => 'rule_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Rule Table') ,
- 'description' => 'The name of the table this rule is about',
- 'required' => true,
+ 'title' => ts('Rule Table'),
+ 'description' => ts('The name of the table this rule is about'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_dedupe_rule.rule_table',
'table_name' => 'civicrm_dedupe_rule',
'entity' => 'Rule',
'bao' => 'CRM_Dedupe_BAO_Rule',
'localizable' => 0,
- ) ,
- 'rule_field' => array(
+ ],
+ 'rule_field' => [
'name' => 'rule_field',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Rule Field') ,
- 'description' => 'The name of the field of the table referenced in rule_table',
- 'required' => true,
+ 'title' => ts('Rule Field'),
+ 'description' => ts('The name of the field of the table referenced in rule_table'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_dedupe_rule.rule_field',
'table_name' => 'civicrm_dedupe_rule',
'entity' => 'Rule',
'bao' => 'CRM_Dedupe_BAO_Rule',
'localizable' => 0,
- ) ,
- 'rule_length' => array(
+ ],
+ 'rule_length' => [
'name' => 'rule_length',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Rule Length') ,
- 'description' => 'The length of the matching substring',
+ 'title' => ts('Rule Length'),
+ 'description' => ts('The length of the matching substring'),
+ 'where' => 'civicrm_dedupe_rule.rule_length',
'table_name' => 'civicrm_dedupe_rule',
'entity' => 'Rule',
'bao' => 'CRM_Dedupe_BAO_Rule',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'rule_weight' => array(
+ ],
+ ],
+ 'rule_weight' => [
'name' => 'rule_weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'The weight of the rule',
- 'required' => true,
+ 'title' => ts('Order'),
+ 'description' => ts('The weight of the rule'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_rule.rule_weight',
'table_name' => 'civicrm_dedupe_rule',
'entity' => 'Rule',
'bao' => 'CRM_Dedupe_BAO_Rule',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -231,10 +227,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dedupe_rule', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dedupe_rule', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -242,15 +239,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dedupe_rule', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dedupe_rule', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Dedupe/DAO/RuleGroup.php b/CRM/Dedupe/DAO/RuleGroup.php
index b662b02795e2..505c8044dcdc 100644
--- a/CRM/Dedupe/DAO/RuleGroup.php
+++ b/CRM/Dedupe/DAO/RuleGroup.php
@@ -1,250 +1,247 @@
__table = 'civicrm_dedupe_rule_group';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Rule Group ID') ,
- 'description' => 'Unique dedupe rule group id',
- 'required' => true,
+ 'title' => ts('Rule Group ID'),
+ 'description' => ts('Unique dedupe rule group id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_rule_group.id',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- ) ,
- 'contact_type' => array(
+ ],
+ 'contact_type' => [
'name' => 'contact_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Contact Type') ,
- 'description' => 'The type of contacts this group applies to',
+ 'title' => ts('Contact Type'),
+ 'description' => ts('The type of contacts this group applies to'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_dedupe_rule_group.contact_type',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_contact_type',
'keyColumn' => 'name',
'labelColumn' => 'label',
'condition' => 'parent_id IS NULL',
- )
- ) ,
- 'threshold' => array(
+ ]
+ ],
+ 'threshold' => [
'name' => 'threshold',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Threshold') ,
- 'description' => 'The weight threshold the sum of the rule weights has to cross to consider two contacts the same',
- 'required' => true,
+ 'title' => ts('Threshold'),
+ 'description' => ts('The weight threshold the sum of the rule weights has to cross to consider two contacts the same'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_dedupe_rule_group.threshold',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'used' => array(
+ ],
+ ],
+ 'used' => [
'name' => 'used',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Length') ,
- 'description' => 'Whether the rule should be used for cases where usage is Unsupervised, Supervised OR General(programatically)',
- 'required' => true,
+ 'title' => ts('Length'),
+ 'description' => ts('Whether the rule should be used for cases where usage is Unsupervised, Supervised OR General(programatically)'),
+ 'required' => TRUE,
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_dedupe_rule_group.used',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Radio',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::getDedupeRuleTypes',
- )
- ) ,
- 'name' => array(
+ ]
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Name of the rule group',
+ 'title' => ts('Name'),
+ 'description' => ts('Name of the rule group'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_dedupe_rule_group.name',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- ) ,
- 'title' => array(
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Title') ,
- 'description' => 'Label of the rule group',
+ 'title' => ts('Title'),
+ 'description' => ts('Label of the rule group'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_dedupe_rule_group.title',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_reserved' => array(
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Reserved?') ,
- 'description' => 'Is this a reserved rule - a rule group that has been optimized and cannot be changed by the admin',
+ 'title' => ts('Reserved?'),
+ 'description' => ts('Is this a reserved rule - a rule group that has been optimized and cannot be changed by the admin'),
+ 'where' => 'civicrm_dedupe_rule_group.is_reserved',
'table_name' => 'civicrm_dedupe_rule_group',
'entity' => 'RuleGroup',
'bao' => 'CRM_Dedupe_BAO_RuleGroup',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -252,10 +249,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dedupe_rule_group', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'dedupe_rule_group', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -263,15 +261,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dedupe_rule_group', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'dedupe_rule_group', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Dedupe/Finder.php b/CRM/Dedupe/Finder.php
index 19d2ce2c8e4b..7b6c936e72df 100644
--- a/CRM/Dedupe/Finder.php
+++ b/CRM/Dedupe/Finder.php
@@ -1,9 +1,9 @@
id = $rgid;
$rgBao->contactIds = $cids;
if (!$rgBao->find(TRUE)) {
CRM_Core_Error::fatal("Dedupe rule not found for selected contacts");
}
- if (empty($rgBao->contactIds) && !empty($limit)) {
- $limitedContacts = civicrm_api3('Contact', 'get', array(
+ if (empty($rgBao->contactIds) && !empty($searchLimit)) {
+ $limitedContacts = civicrm_api3('Contact', 'get', [
'return' => 'id',
'contact_type' => $rgBao->contact_type,
- 'options' => array('limit' => $limit),
- ));
+ 'options' => ['limit' => $searchLimit],
+ ]);
$rgBao->contactIds = array_keys($limitedContacts['values']);
}
$rgBao->fillTable();
$dao = new CRM_Core_DAO();
$dao->query($rgBao->thresholdQuery($checkPermissions));
- $dupes = array();
+ $dupes = [];
while ($dao->fetch()) {
- $dupes[] = array($dao->id1, $dao->id2, $dao->weight);
+ $dupes[] = [$dao->id1, $dao->id2, $dao->weight];
}
$dao->query($rgBao->tableDropQuery());
@@ -96,7 +97,7 @@ public static function dupes($rgid, $cids = array(), $checkPermissions = TRUE, $
*
* check_permission is a boolean flag to indicate if permission should be considered.
* default is to always check permissioning but public pages for example might not want
- * permission to be checked for anonymous users. Refer CRM-6211. We might be beaking
+ * permission to be checked for anonymous users. Refer CRM-6211. We might be breaking
* Multi-Site dedupe for public pages.
*
* @param array $params
@@ -117,13 +118,16 @@ public static function dupesByParams(
$params,
$ctype,
$used = 'Unsupervised',
- $except = array(),
+ $except = [],
$ruleGroupID = NULL
) {
// If $params is empty there is zero reason to proceed.
if (!$params) {
- return array();
+ return [];
}
+ $checkPermission = CRM_Utils_Array::value('check_permission', $params, TRUE);
+ // This may no longer be required - see https://github.com/civicrm/civicrm-core/pull/13176
+ $params = array_filter($params);
$foundByID = FALSE;
if ($ruleGroupID) {
@@ -143,7 +147,6 @@ public static function dupesByParams(
CRM_Core_Error::fatal("$used rule for $ctype does not exist");
}
}
- $params['check_permission'] = CRM_Utils_Array::value('check_permission', $params, TRUE);
if (isset($params['civicrm_phone']['phone_numeric'])) {
$orig = $params['civicrm_phone']['phone_numeric'];
@@ -152,8 +155,8 @@ public static function dupesByParams(
$rgBao->params = $params;
$rgBao->fillTable();
$dao = new CRM_Core_DAO();
- $dao->query($rgBao->thresholdQuery($params['check_permission']));
- $dupes = array();
+ $dao->query($rgBao->thresholdQuery($checkPermission));
+ $dupes = [];
while ($dao->fetch()) {
if (isset($dao->id) && $dao->id) {
$dupes[] = $dao->id;
@@ -169,18 +172,22 @@ public static function dupesByParams(
* @param int $rgid
* Rule group id.
* @param int $gid
- * Contact group id (currently, works only with non-smart groups).
+ * Contact group id.
+ *
+ * @param int $searchLimit
+ * Limit for the number of contacts to be used for comparison.
+ * The search methodology finds all matches for the searchedContacts so this limits
+ * the number of searched contacts, not the matches found.
*
- * @param int $limit
* @return array
* array of (cid1, cid2, weight) dupe triples
*/
- public static function dupesInGroup($rgid, $gid, $limit = NULL) {
- $cids = array_keys(CRM_Contact_BAO_Group::getMember($gid, $limit));
+ public static function dupesInGroup($rgid, $gid, $searchLimit = 0) {
+ $cids = array_keys(CRM_Contact_BAO_Group::getMember($gid, TRUE, $searchLimit));
if (!empty($cids)) {
return self::dupes($rgid, $cids);
}
- return array();
+ return [];
}
/**
@@ -196,16 +203,16 @@ public static function dupesInGroup($rgid, $gid, $limit = NULL) {
* valid $params array for dedupe
*/
public static function formatParams($fields, $ctype) {
- $flat = array();
+ $flat = [];
CRM_Utils_Array::flatten($fields, $flat);
// FIXME: This may no longer be necessary - check inputs
- $replace_these = array(
+ $replace_these = [
'individual_prefix' => 'prefix_id',
'individual_suffix' => 'suffix_id',
'gender' => 'gender_id',
- );
- foreach (array('individual_suffix', 'individual_prefix', 'gender') as $name) {
+ ];
+ foreach (['individual_suffix', 'individual_prefix', 'gender'] as $name) {
if (!empty($fields[$name])) {
$flat[$replace_these[$name]] = $flat[$name];
unset($flat[$name]);
@@ -213,10 +220,10 @@ public static function formatParams($fields, $ctype) {
}
// handle {birth,deceased}_date
- foreach (array(
+ foreach ([
'birth_date',
'deceased_date',
- ) as $date) {
+ ] as $date) {
if (!empty($fields[$date])) {
$flat[$date] = $fields[$date];
if (is_array($flat[$date])) {
@@ -233,7 +240,7 @@ public static function formatParams($fields, $ctype) {
// handle preferred_communication_method
if (!empty($fields['preferred_communication_method'])) {
- $methods = array_intersect($fields['preferred_communication_method'], array('1'));
+ $methods = array_intersect($fields['preferred_communication_method'], ['1']);
$methods = array_keys($methods);
sort($methods);
if ($methods) {
@@ -270,7 +277,7 @@ public static function formatParams($fields, $ctype) {
// FIXME: CRM-5026 should be fixed here; the below clobbers all address info; we should split off address fields and match
// the -digit to civicrm_address.location_type_id and -Primary to civicrm_address.is_primary
foreach ($flat as $key => $value) {
- $matches = array();
+ $matches = [];
if (preg_match('/(.*)-(Primary-[\d+])$|(.*)-(\d+|Primary)$/', $key, $matches)) {
$return = array_values(array_filter($matches));
$flat[$return[1]] = $value;
@@ -278,7 +285,7 @@ public static function formatParams($fields, $ctype) {
}
}
- $params = array();
+ $params = [];
$supportedFields = CRM_Dedupe_BAO_RuleGroup::supportedFields($ctype);
if (is_array($supportedFields)) {
foreach ($supportedFields as $table => $fields) {
@@ -286,12 +293,12 @@ public static function formatParams($fields, $ctype) {
// for matching on civicrm_address fields, we also need the location_type_id
$fields['location_type_id'] = '';
// FIXME: we also need to do some hacking for id and name fields, see CRM-3902’s comments
- $fixes = array(
+ $fixes = [
'address_name' => 'name',
'country' => 'country_id',
'state_province' => 'state_province_id',
'county' => 'county_id',
- );
+ ];
foreach ($fixes as $orig => $target) {
if (!empty($flat[$orig])) {
$params[$table][$target] = $flat[$orig];
@@ -299,9 +306,9 @@ public static function formatParams($fields, $ctype) {
}
}
if ($table == 'civicrm_phone') {
- $fixes = array(
+ $fixes = [
'phone' => 'phone_numeric',
- );
+ ];
foreach ($fixes as $orig => $target) {
if (!empty($flat[$orig])) {
$params[$table][$target] = $flat[$orig];
@@ -324,7 +331,7 @@ public static function formatParams($fields, $ctype) {
* @param array $foundDupes
* @param string $cacheKeyString
*
- * @return array Dupe pairs with the keys
+ * @return array
* Dupe pairs with the keys
* -srcID
* -srcName
@@ -336,7 +343,7 @@ public static function formatParams($fields, $ctype) {
* @throws CRM_Core_Exception
*/
public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
- $cids = array();
+ $cids = [];
foreach ($foundDupes as $dupe) {
$cids[$dupe[0]] = 1;
$cids[$dupe[1]] = 1;
@@ -344,7 +351,7 @@ public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
$cidString = implode(', ', array_keys($cids));
$dao = CRM_Core_DAO::executeQuery("SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name");
- $displayNames = array();
+ $displayNames = [];
while ($dao->fetch()) {
$displayNames[$dao->id] = $dao->display_name;
}
@@ -359,14 +366,14 @@ public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
$dstID = $userId;
}
- $mainContacts[] = $row = array(
+ $mainContacts[] = $row = [
'dstID' => $dstID,
'dstName' => $displayNames[$dstID],
'srcID' => $srcID,
'srcName' => $displayNames[$srcID],
'weight' => $dupes[2],
'canMerge' => TRUE,
- );
+ ];
$data = CRM_Core_DAO::escapeString(serialize($row));
$values[] = " ( 'civicrm_contact', $dstID, $srcID, '$cacheKeyString', '$data' ) ";
diff --git a/CRM/Dedupe/Merger.php b/CRM/Dedupe/Merger.php
index c2ebae711941..6703e57a7cda 100644
--- a/CRM/Dedupe/Merger.php
+++ b/CRM/Dedupe/Merger.php
@@ -1,9 +1,9 @@
userSystem->getUserRecordUrl() - however that function takes a contact_id &
- // we may need a different function when it is not known.
- $title = $userRecordUrl = '';
-
- $config = CRM_Core_Config::singleton();
- if ($config->userSystem->is_drupal) {
- $userRecordUrl = CRM_Utils_System::url('user/%ufid');
- $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
- }
- elseif ($config->userFramework == 'Joomla') {
- $userRecordUrl = $config->userSystem->getVersion() > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
- $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
- }
+ if (!isset(Civi::$statics[__CLASS__]['relTables'])) {
+
+ // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
+ // if the url can't be retrieved. A more standardised way to retrieve them is.
+ // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
+ // we may need a different function when it is not known.
+ $title = $userRecordUrl = '';
+
+ $config = CRM_Core_Config::singleton();
+ if ($config->userSystem->is_drupal) {
+ $userRecordUrl = CRM_Utils_System::url('user/%ufid');
+ $title = ts('%1 User: %2; user id: %3', [
+ 1 => $config->userFramework,
+ 2 => '$ufname',
+ 3 => '$ufid',
+ ]);
+ }
+ elseif ($config->userFramework == 'Joomla') {
+ $userRecordUrl = $config->userSystem->getVersion() > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
+ $title = ts('%1 User: %2; user id: %3', [
+ 1 => $config->userFramework,
+ 2 => '$ufname',
+ 3 => '$ufid',
+ ]);
+ }
- if (!$relTables) {
- $relTables = array(
- 'rel_table_contributions' => array(
+ $relTables = [
+ 'rel_table_contributions' => [
'title' => ts('Contributions'),
- 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
+ 'tables' => [
+ 'civicrm_contribution',
+ 'civicrm_contribution_recur',
+ 'civicrm_contribution_soft',
+ ],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
- ),
- 'rel_table_contribution_page' => array(
+ ],
+ 'rel_table_contribution_page' => [
'title' => ts('Contribution Pages'),
- 'tables' => array('civicrm_contribution_page'),
+ 'tables' => ['civicrm_contribution_page'],
'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
- ),
- 'rel_table_memberships' => array(
+ ],
+ 'rel_table_memberships' => [
'title' => ts('Memberships'),
- 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
+ 'tables' => [
+ 'civicrm_membership',
+ 'civicrm_membership_log',
+ 'civicrm_membership_type',
+ ],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
- ),
- 'rel_table_participants' => array(
+ ],
+ 'rel_table_participants' => [
'title' => ts('Participants'),
- 'tables' => array('civicrm_participant'),
+ 'tables' => ['civicrm_participant'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
- ),
- 'rel_table_events' => array(
+ ],
+ 'rel_table_events' => [
'title' => ts('Events'),
- 'tables' => array('civicrm_event'),
+ 'tables' => ['civicrm_event'],
'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
- ),
- 'rel_table_activities' => array(
+ ],
+ 'rel_table_activities' => [
'title' => ts('Activities'),
- 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
+ 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
- ),
- 'rel_table_relationships' => array(
+ ],
+ 'rel_table_relationships' => [
'title' => ts('Relationships'),
- 'tables' => array('civicrm_relationship'),
+ 'tables' => ['civicrm_relationship'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
- ),
- 'rel_table_custom_groups' => array(
+ ],
+ 'rel_table_custom_groups' => [
'title' => ts('Custom Groups'),
- 'tables' => array('civicrm_custom_group'),
+ 'tables' => ['civicrm_custom_group'],
'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
- ),
- 'rel_table_uf_groups' => array(
+ ],
+ 'rel_table_uf_groups' => [
'title' => ts('Profiles'),
- 'tables' => array('civicrm_uf_group'),
+ 'tables' => ['civicrm_uf_group'],
'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
- ),
- 'rel_table_groups' => array(
+ ],
+ 'rel_table_groups' => [
'title' => ts('Groups'),
- 'tables' => array('civicrm_group_contact'),
+ 'tables' => ['civicrm_group_contact'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
- ),
- 'rel_table_notes' => array(
+ ],
+ 'rel_table_notes' => [
'title' => ts('Notes'),
- 'tables' => array('civicrm_note'),
+ 'tables' => ['civicrm_note'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
- ),
- 'rel_table_tags' => array(
+ ],
+ 'rel_table_tags' => [
'title' => ts('Tags'),
- 'tables' => array('civicrm_entity_tag'),
+ 'tables' => ['civicrm_entity_tag'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
- ),
- 'rel_table_mailings' => array(
+ ],
+ 'rel_table_mailings' => [
'title' => ts('Mailings'),
- 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
+ 'tables' => [
+ 'civicrm_mailing',
+ 'civicrm_mailing_event_queue',
+ 'civicrm_mailing_event_subscribe',
+ ],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
- ),
- 'rel_table_cases' => array(
+ ],
+ 'rel_table_cases' => [
'title' => ts('Cases'),
- 'tables' => array('civicrm_case_contact'),
+ 'tables' => ['civicrm_case_contact'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
- ),
- 'rel_table_grants' => array(
+ ],
+ 'rel_table_grants' => [
'title' => ts('Grants'),
- 'tables' => array('civicrm_grant'),
+ 'tables' => ['civicrm_grant'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
- ),
- 'rel_table_pcp' => array(
+ ],
+ 'rel_table_pcp' => [
'title' => ts('PCPs'),
- 'tables' => array('civicrm_pcp'),
+ 'tables' => ['civicrm_pcp'],
'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
- ),
- 'rel_table_pledges' => array(
+ ],
+ 'rel_table_pledges' => [
'title' => ts('Pledges'),
- 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
+ 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
- ),
- 'rel_table_users' => array(
+ ],
+ 'rel_table_users' => [
'title' => $title,
- 'tables' => array('civicrm_uf_match'),
+ 'tables' => ['civicrm_uf_match'],
'url' => $userRecordUrl,
- ),
- );
+ ],
+ ];
$relTables += self::getMultiValueCustomSets('relTables');
// Allow hook_civicrm_merge() to adjust $relTables
CRM_Utils_Hook::merge('relTables', $relTables);
+
+ // Cache the results in a static variable
+ Civi::$statics[__CLASS__]['relTables'] = $relTables;
}
- return $relTables;
+
+ return Civi::$statics[__CLASS__]['relTables'];
}
/**
@@ -168,13 +192,13 @@ public static function relTables() {
*/
public static function getActiveRelTables($cid) {
$cid = (int) $cid;
- $groups = array();
+ $groups = [];
$relTables = self::relTables();
$cidRefs = self::cidRefs();
$eidRefs = self::eidRefs();
foreach ($relTables as $group => $params) {
- $sqls = array();
+ $sqls = [];
foreach ($params['tables'] as $table) {
if (isset($cidRefs[$table])) {
foreach ($cidRefs[$table] as $field) {
@@ -199,35 +223,24 @@ public static function getActiveRelTables($cid) {
/**
* Get array tables and fields that reference civicrm_contact.id.
*
- * This includes core tables, custom group tables, tables added by the merge
- * hook and (somewhat randomly) the entity_tag table.
+ * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
+ * The entityTypes hook is the recommended way to add tables to this result.
*
- * Refer to CRM-17454 for information on the danger of querying the information
- * schema to derive this.
- *
- * This function calls the merge hook but the entityTypes hook is the recommended
- * way to add tables to this result.
+ * I thought about adding another hook to alter tableReferences but decided it was unclear if there
+ * are use cases not covered by entityTables and instead we should wait & see.
*/
public static function cidRefs() {
if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
return \Civi::$statics[__CLASS__]['contact_references'];
}
- $contactReferences = array();
- $coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact');
- foreach ($coreReferences as $coreReference) {
- if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
- $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
- }
- }
- self::addCustomTablesExtendingContactsToCidRefs($contactReferences);
- // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
- $contactReferences['civicrm_entity_tag'][] = 'entity_id';
+ $contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable();
- // Allow hook_civicrm_merge() to adjust $cidRefs.
- // Note that if entities are registered using the entityTypes hook there
- // is no need to use this hook.
CRM_Utils_Hook::merge('cidRefs', $contactReferences);
+ if ($contactReferences !== $coreReferences) {
+ Civi::log()
+ ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
+ }
\Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
return \Civi::$statics[__CLASS__]['contact_references'];
}
@@ -240,14 +253,14 @@ public static function eidRefs() {
if (!$eidRefs) {
// FIXME: this should be generated dynamically from the schema
// tables that reference contacts with entity_{id,table}
- $eidRefs = array(
- 'civicrm_acl' => array('entity_table' => 'entity_id'),
- 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
- 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
- 'civicrm_log' => array('entity_table' => 'entity_id'),
- 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
- 'civicrm_note' => array('entity_table' => 'entity_id'),
- );
+ $eidRefs = [
+ 'civicrm_acl' => ['entity_table' => 'entity_id'],
+ 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
+ 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
+ 'civicrm_log' => ['entity_table' => 'entity_id'],
+ 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
+ 'civicrm_note' => ['entity_table' => 'entity_id'],
+ ];
// Allow hook_civicrm_merge() to adjust $eidRefs
CRM_Utils_Hook::merge('eidRefs', $eidRefs);
@@ -261,7 +274,7 @@ public static function eidRefs() {
public static function locTables() {
static $locTables;
if (!$locTables) {
- $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
+ $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
// Allow hook_civicrm_merge() to adjust $locTables
CRM_Utils_Hook::merge('locTables', $locTables);
@@ -273,31 +286,43 @@ public static function locTables() {
* We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
* @param string $request
* 'relTables' or 'cidRefs'.
+ * @return array
* @see CRM-13836
*/
public static function getMultiValueCustomSets($request) {
- static $data = NULL;
- if ($data === NULL) {
- $data = array(
- 'relTables' => array(),
- 'cidRefs' => array(),
- );
- $result = civicrm_api3('custom_group', 'get', array(
+
+ if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) {
+ $data = [
+ 'relTables' => [],
+ 'cidRefs' => [],
+ ];
+ $result = civicrm_api3('custom_group', 'get', [
'is_multiple' => 1,
- 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
- 'return' => array('id', 'title', 'table_name', 'style'),
- ));
+ 'extends' => [
+ 'IN' => [
+ 'Individual',
+ 'Organization',
+ 'Household',
+ 'Contact',
+ ],
+ ],
+ 'return' => ['id', 'title', 'table_name', 'style'],
+ ]);
foreach ($result['values'] as $custom) {
- $data['cidRefs'][$custom['table_name']] = array('entity_id');
+ $data['cidRefs'][$custom['table_name']] = ['entity_id'];
$urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
- $data['relTables']['rel_table_custom_' . $custom['id']] = array(
+ $data['relTables']['rel_table_custom_' . $custom['id']] = [
'title' => $custom['title'],
- 'tables' => array($custom['table_name']),
+ 'tables' => [$custom['table_name']],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
- );
+ ];
}
+
+ // Store the result in a static variable cache
+ Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data;
}
- return $data[$request];
+
+ return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request];
}
/**
@@ -307,13 +332,14 @@ public static function getMultiValueCustomSets($request) {
public static function cpTables() {
static $tables;
if (!$tables) {
- $tables = array(
- 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
- 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
+ $tables = [
+ 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
+ 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
// Empty array == do nothing - this table is handled by mergeGroupContact
- 'civicrm_subscription_history' => array(),
- 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
- );
+ 'civicrm_subscription_history' => [],
+ 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
+ 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
+ ];
}
return $tables;
}
@@ -324,7 +350,7 @@ public static function cpTables() {
public static function paymentTables() {
static $tables;
if (!$tables) {
- $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
+ $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
}
return $tables;
}
@@ -339,7 +365,7 @@ public static function paymentTables() {
* @return array
*/
public static function paymentSql($tableName, $mainContactId, $otherContactId) {
- $sqls = array();
+ $sqls = [];
if (!$tableName || !$mainContactId || !$otherContactId) {
return $sqls;
}
@@ -390,8 +416,8 @@ public static function paymentSql($tableName, $mainContactId, $otherContactId) {
*
* @return array
*/
- public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
- $sqls = array();
+ public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
+ $sqls = [];
if (!$tableName || !$mainId || !$otherId) {
return $sqls;
}
@@ -429,6 +455,34 @@ public static function operationSql($mainId, $otherId, $tableName, $tableOperati
return $sqls;
}
+ /**
+ * Based on the provided two contact_ids and a set of tables, remove the
+ * belongings of the other contact and of their relations.
+ *
+ * @param int $otherID
+ * @param bool $tables
+ */
+ public static function removeContactBelongings($otherID, $tables) {
+ // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
+ if (in_array("civicrm_membership", $tables)) {
+ $membershipIDs = CRM_Utils_Array::collect('id',
+ CRM_Utils_Array::value('values',
+ civicrm_api3("Membership", "get", [
+ "contact_id" => $otherID,
+ "return" => "id",
+ ])
+ )
+ );
+
+ if (!empty($membershipIDs)) {
+ civicrm_api3("Membership", "get", [
+ 'owner_membership_id' => ['IN' => $membershipIDs],
+ 'api.Membership.delete' => ['id' => '$value.id'],
+ ]);
+ }
+ }
+ }
+
/**
* Based on the provided two contact_ids and a set of tables, move the
* belongings of the other contact to the main one.
@@ -439,16 +493,17 @@ public static function operationSql($mainId, $otherId, $tableName, $tableOperati
* @param array $tableOperations
* @param array $customTableToCopyFrom
*/
- public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array(), $customTableToCopyFrom = NULL) {
+ public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) {
$cidRefs = self::cidRefs();
$eidRefs = self::eidRefs();
$cpTables = self::cpTables();
$paymentTables = self::paymentTables();
// getting all custom tables
- $customTables = array();
+ $customTables = [];
if ($customTableToCopyFrom !== NULL) {
- self::addCustomTablesExtendingContactsToCidRefs($customTables);
+ // @todo this duplicates cidRefs?
+ CRM_Core_DAO::appendCustomTablesExtendingContacts($customTables);
$customTables = array_keys($customTables);
}
@@ -467,18 +522,21 @@ public static function moveContactBelongings($mainId, $otherId, $tables = FALSE,
$mainId = (int) $mainId;
$otherId = (int) $otherId;
+ $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs'));
- $sqls = array();
+ $sqls = [];
foreach ($affected as $table) {
- // skipping non selected custom table's value migration
- if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
- continue;
+ // skipping non selected single-value custom table's value migration
+ if (!in_array($table, $multi_value_tables)) {
+ if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
+ continue;
+ }
}
// Call custom processing function for objects that require it
if (isset($cpTables[$table])) {
foreach ($cpTables[$table] as $className => $fnName) {
- $className::$fnName($mainId, $otherId, $sqls);
+ $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
}
// Skip normal processing
continue;
@@ -524,7 +582,7 @@ public static function moveContactBelongings($mainId, $otherId, $tables = FALSE,
// call the SQL queries in one transaction
$transaction = new CRM_Core_Transaction();
foreach ($sqls as $sql) {
- CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
+ CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE);
}
CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
$transaction->commit();
@@ -568,10 +626,10 @@ private static function customRecordExists($contactID, $table, $idField) {
* @return array
*/
public static function retrieveFields($main, $other) {
- $result = array(
- 'contact' => array(),
- 'custom' => array(),
- );
+ $result = [
+ 'contact' => [],
+ 'custom' => [],
+ ];
foreach (self::getContactFields() as $validField) {
// CRM-17556 Get all non-empty fields, to make comparison easier
if (!empty($main[$validField]) || !empty($other[$validField])) {
@@ -589,8 +647,11 @@ public static function retrieveFields($main, $other) {
}
$key1 = CRM_Utils_Array::value($key, $mainEvs);
$key2 = CRM_Utils_Array::value($key, $otherEvs);
- // CRM-17556 Get all non-empty fields, to make comparison easier
- if (!empty($key1) || !empty($key2)) {
+ // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
+ // However I can't think of a case where an empty string is more meaningful than null
+ // or where it would be FALSE or something else nullish.
+ $valuesToIgnore = [NULL, '', []];
+ if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) {
$result['custom'][] = $key;
}
}
@@ -610,27 +671,41 @@ public static function retrieveFields($main, $other) {
* mode does a force merge.
* @param int $batchLimit number of merges to carry out in one batch.
* @param int $isSelected if records with is_selected column needs to be processed.
+ * Note the option of '2' is only used in conjunction with $redirectForPerformance
+ * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
+ * out in favour of explicitly passing in $reloadCacheIfEmpty
*
* @param array $criteria
* Criteria to use in the filter.
*
* @param bool $checkPermissions
* Respect logged in user permissions.
+ * @param bool|NULL $reloadCacheIfEmpty
+ * If not set explicitly this is calculated but it is preferred that it be set
+ * per comments on isSelected above.
*
* @return array|bool
*/
- public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
+ public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) {
$redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
- $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
+
+ if (!isset($reloadCacheIfEmpty)) {
+ $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
+ }
+ if ($isSelected !== 0 && $isSelected !== 1) {
+ // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
+ $isSelected = NULL;
+ }
$dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
- $cacheParams = array(
+ $cacheParams = [
'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
// @todo stop passing these parameters in & instead calculate them in the merge function based
// on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
'join' => self::getJoinOnDedupeTable(),
- 'where' => self::getWhereString($batchLimit, $isSelected),
- );
+ 'where' => self::getWhereString($isSelected),
+ 'limit' => (int) $batchLimit,
+ ];
return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
}
@@ -652,21 +727,15 @@ public static function getJoinOnDedupeTable() {
/**
* Get where string for dedupe join.
*
- * @param int $batchLimit
* @param bool $isSelected
*
* @return string
*/
- protected static function getWhereString($batchLimit, $isSelected) {
+ protected static function getWhereString($isSelected) {
$where = "de.id IS NULL";
if ($isSelected === 0 || $isSelected === 1) {
$where .= " AND pn.is_selected = {$isSelected}";
}
- // else consider all dupe pairs
- // @todo Adding limit to Where??!!
- if ($batchLimit) {
- $where .= " LIMIT {$batchLimit}";
- }
return $where;
}
@@ -676,9 +745,9 @@ protected static function getWhereString($batchLimit, $isSelected) {
* @param string $cacheKeyString
* @param array $result
*/
- public static function updateMergeStats($cacheKeyString, $result = array()) {
+ public static function updateMergeStats($cacheKeyString, $result = []) {
// gather latest stats
- $merged = count($result['merged']);
+ $merged = count($result['merged']);
$skipped = count($result['skipped']);
if ($merged <= 0 && $skipped <= 0) {
@@ -700,13 +769,13 @@ public static function updateMergeStats($cacheKeyString, $result = array()) {
CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
// store the updated stats
- $data = array(
- 'merged' => $merged,
+ $data = [
+ 'merged' => $merged,
'skipped' => $skipped,
- );
+ ];
$data = CRM_Core_DAO::escapeString(serialize($data));
- $values = array();
+ $values = [];
$values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
CRM_Core_BAO_PrevNextCache::setItem($values);
}
@@ -739,18 +808,23 @@ public static function getMergeStats($cacheKeyString) {
/**
* Get merge statistics message.
*
- * @param string $cacheKeyString
+ * @param array $stats
*
* @return string
*/
- public static function getMergeStatsMsg($cacheKeyString) {
- $msg = '';
- $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
+ public static function getMergeStatsMsg($stats) {
+ $msg = '';
if (!empty($stats['merged'])) {
- $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
+ $msg = '
';
}
return $msg;
}
@@ -776,15 +850,15 @@ public static function getMergeStatsMsg($cacheKeyString) {
*
* @return array|bool
*/
- public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
- $redirectForPerformance = FALSE, $checkPermissions = TRUE
+ public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
+ $redirectForPerformance = FALSE, $checkPermissions = TRUE
) {
$cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
- $resultStats = array('merged' => array(), 'skipped' => array());
+ $resultStats = ['merged' => [], 'skipped' => []];
// we don't want dupe caching to get reset after every-merge, and therefore set the
CRM_Core_Config::setPermitCacheFlushMode(FALSE);
- $deletedContacts = array();
+ $deletedContacts = [];
while (!empty($dupePairs)) {
foreach ($dupePairs as $index => $dupes) {
@@ -818,8 +892,8 @@ public static function merge($dupePairs = array(), $cacheParams = array(), $mode
$cacheParams['join'],
$cacheParams['where'],
0,
- 0,
- array(),
+ $cacheParams['limit'],
+ [],
'',
FALSE
);
@@ -850,92 +924,13 @@ public static function merge($dupePairs = array(), $cacheParams = array(), $mode
* - Does a force merge otherwise (aggressive mode).
*
* @param array $conflicts
+ * An empty array to be filed with conflict information.
*
* @return bool
*/
- public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
-
- $originalMigrationInfo = $migrationInfo;
- foreach ($migrationInfo as $key => $val) {
- if ($val === "null") {
- // Rule: Never overwrite with an empty value (in any mode)
- unset($migrationInfo[$key]);
- continue;
- }
- elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
- substr($key, 0, 12) == 'move_custom_'
- ) and $val != NULL
- ) {
- // Rule: If both main-contact, and other-contact have a field with a
- // different value, then let $mode decide if to merge it or not
- if (
- (!empty($migrationInfo['rows'][$key]['main'])
- // For custom fields a 0 (e.g in an int field) could be a true conflict. This
- // is probably true for other fields too - e.g. 'do_not_email' but
- // leaving that investigation as a @todo - until tests can be written.
- // Note the handling of this has test coverage - although the data-typing
- // of '0' feels flakey we have insurance.
- || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
- )
- && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
- ) {
+ public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
- // note it down & lets wait for response from the hook.
- // For no response $mode will decide if to skip this merge
- $conflicts[$key] = NULL;
- }
- }
- elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
- $locField = explode('_', $key);
- $fieldName = $locField[2];
- $fieldCount = $locField[3];
-
- // Rule: Catch address conflicts (same address type on both contacts)
- if (
- isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
- !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
- ) {
-
- // Load the address we're inspecting from the 'other' contact
- $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
- $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
-
- // If it exists on the 'main' contact already, skip it. Otherwise
- // if the location type exists already, log a conflict.
- foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
- if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
- unset($migrationInfo[$key]);
- break;
- }
- elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
- $conflicts[$key] = NULL;
- break;
- }
- }
- }
-
- // For other locations, don't merge/add if the values are the same
- elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
- unset($migrationInfo[$key]);
- }
- }
- }
-
- // A hook to implement other algorithms for choosing which contact to bias to when
- // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
- // merge happens with new values filled in here. For a particular field / row not to be merged
- // field should be unset from fields_in_conflict.
- $migrationData = array(
- 'old_migration_info' => $originalMigrationInfo,
- 'mode' => $mode,
- 'fields_in_conflict' => $conflicts,
- 'merge_mode' => $mode,
- 'migration_info' => $migrationInfo,
- );
- CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
- $conflicts = $migrationData['fields_in_conflict'];
- // allow hook to override / manipulate migrationInfo as well
- $migrationInfo = $migrationData['migration_info'];
+ $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode);
if (!empty($conflicts)) {
foreach ($conflicts as $key => $val) {
@@ -949,9 +944,7 @@ public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'sa
}
}
// if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
- if (array_key_exists('skip_merge', $migrationData)) {
- return (bool) $migrationData['skip_merge'];
- }
+ return (bool) $migrationInfo['skip_merge'];
}
return FALSE;
}
@@ -964,8 +957,16 @@ public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'sa
*
* @return bool
*/
- static public function locationIsSame($mainAddress, $comparisonAddress) {
- $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id', 'reset_date', 'hold_date');
+ public static function locationIsSame($mainAddress, $comparisonAddress) {
+ $keysToIgnore = [
+ 'id',
+ 'is_primary',
+ 'is_billing',
+ 'manual_geo_code',
+ 'contact_id',
+ 'reset_date',
+ 'hold_date',
+ ];
foreach ($comparisonAddress as $field => $value) {
if (in_array($field, $keysToIgnore)) {
continue;
@@ -984,43 +985,43 @@ static public function locationIsSame($mainAddress, $comparisonAddress) {
* @return array
*/
public static function getLocationBlockInfo() {
- $locationBlocks = array(
- 'address' => array(
+ $locationBlocks = [
+ 'address' => [
'label' => 'Address',
'displayField' => 'display',
'sortString' => 'location_type_id',
'hasLocation' => TRUE,
'hasType' => FALSE,
- ),
- 'email' => array(
+ ],
+ 'email' => [
'label' => 'Email',
- 'displayField' => 'email',
+ 'displayField' => 'display',
'sortString' => 'location_type_id',
'hasLocation' => TRUE,
'hasType' => FALSE,
- ),
- 'im' => array(
+ ],
+ 'im' => [
'label' => 'IM',
'displayField' => 'name',
'sortString' => 'location_type_id,provider_id',
'hasLocation' => TRUE,
'hasType' => 'provider_id',
- ),
- 'phone' => array(
+ ],
+ 'phone' => [
'label' => 'Phone',
'displayField' => 'phone',
'sortString' => 'location_type_id,phone_type_id',
'hasLocation' => TRUE,
'hasType' => 'phone_type_id',
- ),
- 'website' => array(
+ ],
+ 'website' => [
'label' => 'Website',
'displayField' => 'url',
'sortString' => 'website_type_id',
'hasLocation' => FALSE,
'hasType' => 'website_type_id',
- ),
- );
+ ],
+ ];
return $locationBlocks;
}
@@ -1084,14 +1085,14 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
$compareFields = self::retrieveFields($main, $other);
- $rows = $elements = $relTableElements = $migrationInfo = array();
+ $rows = $elements = $relTableElements = $migrationInfo = [];
foreach ($compareFields['contact'] as $field) {
if ($field == 'contact_sub_type') {
// CRM-15681 don't display sub-types in UI
continue;
}
- foreach (array('main', 'other') as $moniker) {
+ foreach (['main', 'other'] as $moniker) {
$contact = &$$moniker;
$value = CRM_Utils_Array::value($field, $contact);
if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
@@ -1122,7 +1123,7 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
$label = CRM_Utils_Array::value('individual_suffix', $contact);
}
elseif ($field == 'gender_id' && !empty($value)) {
- $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
+ $genderOptions = civicrm_api3('contact', 'getoptions', ['field' => 'gender_id']);
$label = $genderOptions['values'][$value];
}
elseif ($field == 'current_employer_id' && !empty($value)) {
@@ -1143,7 +1144,14 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
// Display a checkbox to migrate, only if the values are different
if ($value != $main[$field]) {
- $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
+ $elements[] = [
+ 'advcheckbox',
+ "move_$field",
+ NULL,
+ NULL,
+ NULL,
+ $value,
+ ];
}
$migrationInfo["move_$field"] = $value;
@@ -1158,29 +1166,29 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
// Set up useful information about the location blocks
$locationBlocks = self::getLocationBlockInfo();
- $locations = array(
- 'main' => array(),
- 'other' => array(),
- );
+ $locations = [
+ 'main' => [],
+ 'other' => [],
+ ];
// @todo This could probably be defined and used earlier
- $mergeTargets = array(
+ $mergeTargets = [
'main' => $mainId,
'other' => $otherId,
- );
+ ];
foreach ($locationBlocks as $blockName => $blockInfo) {
// Collect existing fields from both 'main' and 'other' contacts first
// This allows us to match up location/types when building the table rows
foreach ($mergeTargets as $moniker => $cid) {
- $searchParams = array(
+ $searchParams = [
'contact_id' => $cid,
// CRM-17556 Order by field-specific criteria
- 'options' => array(
+ 'options' => [
'sort' => $blockInfo['sortString'],
- ),
- );
+ ],
+ ];
$values = civicrm_api3($blockName, 'get', $searchParams);
if ($values['count']) {
$cnt = 0;
@@ -1191,6 +1199,10 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
CRM_Core_BAO_Address::fixAddress($value);
$locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
}
+ // Fix email display
+ elseif ($blockName == 'email') {
+ $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail::format($value);
+ }
$cnt++;
}
@@ -1233,6 +1245,7 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
// Set this value as the default against the 'other' contact value
$rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
$rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
+ $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
$mainContactBlockId = $mainValueCheck['id'];
break;
}
@@ -1240,16 +1253,25 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
}
// Add checkbox to migrate data from 'other' to 'main'
- $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
+ $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
// Add checkbox to set the 'other' location as primary
- $elements[] = array('advcheckbox', "location_blocks[$blockName][$count][set_other_primary]", NULL, ts('Set as primary'));
+ $elements[] = [
+ 'advcheckbox',
+ "location_blocks[$blockName][$count][set_other_primary]",
+ NULL,
+ ts('Set as primary'),
+ ];
// Flag up this field to skipMerge function (@todo: do we need to?)
$migrationInfo["move_location_{$blockName}_{$count}"] = 1;
// Add a hidden field to store the ID of the target main contact block
- $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
+ $elements[] = [
+ 'hidden',
+ "location_blocks[$blockName][$count][mainContactBlockId]",
+ $mainContactBlockId,
+ ];
// Setup variables
$thisTypeId = FALSE;
@@ -1261,29 +1283,34 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
if ($blockInfo['hasLocation']) {
// Load the location options for this entity
- $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
+ $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
$thisLocId = $value['location_type_id'];
// Put this field's location type at the top of the list
$tmpIdList = $locationOptions['values'];
- $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
+ $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
unset($tmpIdList[$thisLocId]);
// Add the element
- $elements[] = array(
+ $elements[] = [
'select',
"location_blocks[$blockName][$count][locTypeId]",
NULL,
$defaultLocId + $tmpIdList,
- );
+ ];
// Add the relevant information to the $migrationInfo
// Keep location-type-id same as that of other-contact
// @todo Check this logic out
$migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
if ($blockName != 'address') {
- $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('Add new'));
+ $elements[] = [
+ 'advcheckbox',
+ "location_blocks[{$blockName}][$count][operation]",
+ NULL,
+ ts('Add new'),
+ ];
// always use add operation
$migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
}
@@ -1296,22 +1323,22 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
if ($blockInfo['hasType']) {
// Load the type options for this entity
- $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
+ $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
$thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
// Put this field's location type at the top of the list
$tmpIdList = $typeOptions['values'];
- $defaultTypeId = array($thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList));
+ $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)];
unset($tmpIdList[$thisTypeId]);
// Add the element
- $elements[] = array(
+ $elements[] = [
'select',
"location_blocks[$blockName][$count][typeTypeId]",
NULL,
$defaultTypeId + $tmpIdList,
- );
+ ];
// Add the information to the migrationInfo
$migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
@@ -1370,7 +1397,7 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
continue;
}
- $relTableElements[] = array('checkbox', "move_$name");
+ $relTableElements[] = ['checkbox', "move_$name"];
$migrationInfo["move_$name"] = 1;
$relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
@@ -1378,18 +1405,33 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
if ($name == 'rel_table_users') {
$relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
$relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
- $find = array('$ufid', '$ufname');
+ $find = ['$ufid', '$ufname'];
if ($mainUser) {
- $replace = array($mainUfId, $mainUser->name);
+ $replace = [$mainUfId, $mainUser->name];
$relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
}
if ($otherUser) {
- $replace = array($otherUfId, $otherUser->name);
+ $replace = [$otherUfId, $otherUser->name];
$relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
}
}
if ($name == 'rel_table_memberships') {
- $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
+ //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
+ $attributes = ['checked' => 'checked'];
+ $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId);
+ foreach ($otherContactMemberships as $membership) {
+ $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
+ if ($mainMembership) {
+ $attributes = [];
+ }
+ }
+ $elements[] = [
+ 'checkbox',
+ "operation[move_{$name}][add]",
+ NULL,
+ ts('add new'),
+ $attributes,
+ ];
$migrationInfo["operation"]["move_{$name}"]['add'] = 1;
}
}
@@ -1405,7 +1447,6 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
$otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
);
- CRM_Core_DAO::freeResult();
foreach ($otherTree as $gid => $group) {
$foundField = FALSE;
@@ -1436,13 +1477,20 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
}
$rows["move_custom_$fid"]['title'] = $field['label'];
- $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
+ $elements[] = [
+ 'advcheckbox',
+ "move_custom_$fid",
+ NULL,
+ NULL,
+ NULL,
+ $value,
+ ];
$migrationInfo["move_custom_$fid"] = $value;
}
}
}
- $result = array(
+ $result = [
'rows' => $rows,
'elements' => $elements,
'rel_table_elements' => $relTableElements,
@@ -1450,7 +1498,7 @@ public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissio
'main_details' => $main,
'other_details' => $other,
'migration_info' => $migrationInfo,
- );
+ ];
$result['main_details']['location_blocks'] = $locations['main'];
$result['other_details']['location_blocks'] = $locations['other'];
@@ -1480,14 +1528,12 @@ public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $che
return FALSE;
}
- $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
+ $contactType = $migrationInfo['main_details']['contact_type'];
$relTables = CRM_Dedupe_Merger::relTables();
- $submittedCustomFields = $moveTables = $locationMigrationInfo = $tableOperations = array();
+ $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
+ self::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
foreach ($migrationInfo as $key => $value) {
- if ($value == $qfZeroBug) {
- $value = '0';
- }
if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
$submitted[substr($key, 5)] = $value;
@@ -1496,10 +1542,6 @@ public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $che
elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
$submitted[substr($key, 5)] = $value;
}
- // Set up initial information for handling migration of location blocks
- elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
- $locationMigrationInfo[$key] = $value;
- }
elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
$moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
if (array_key_exists('operation', $migrationInfo)) {
@@ -1510,199 +1552,73 @@ public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $che
}
}
}
+ elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
+ $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
+ }
}
- self::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
+ self::mergeLocations($mainId, $otherId, $migrationInfo);
// **** Do contact related migrations
$customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields);
CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
unset($moveTables, $tableOperations);
+ // **** Do table related removals
+ if (!empty($removeTables)) {
+ // **** CRM-20421
+ CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables);
+ $removeTables = [];
+ }
+
// FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
- $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
- $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
- $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
- $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
- $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
- $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
- $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
+ $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
+ $names['individual_prefix'] = [
+ 'newName' => 'prefix_id',
+ 'groupName' => 'individual_prefix',
+ ];
+ $names['individual_suffix'] = [
+ 'newName' => 'suffix_id',
+ 'groupName' => 'individual_suffix',
+ ];
+ $names['communication_style'] = [
+ 'newName' => 'communication_style_id',
+ 'groupName' => 'communication_style',
+ ];
+ $names['addressee'] = [
+ 'newName' => 'addressee_id',
+ 'groupName' => 'addressee',
+ ];
+ $names['email_greeting'] = [
+ 'newName' => 'email_greeting_id',
+ 'groupName' => 'email_greeting',
+ ];
+ $names['postal_greeting'] = [
+ 'newName' => 'postal_greeting_id',
+ 'groupName' => 'postal_greeting',
+ ];
CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
-
// fix custom fields so they're edible by createProfileContact()
- static $treeCache = array();
- if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
- $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], NULL, NULL, -1);
- }
-
- $cFields = array();
- foreach ($treeCache[$migrationInfo['main_details']['contact_type']] as $key => $group) {
- if (!isset($group['fields'])) {
- continue;
- }
- foreach ($group['fields'] as $fid => $field) {
- $cFields[$fid]['attributes'] = $field;
- }
- }
+ $cFields = self::getCustomFieldMetadata($contactType);
if (!isset($submitted)) {
- $submitted = array();
+ $submitted = [];
}
+ $customFiles = [];
foreach ($submitted as $key => $value) {
- if (substr($key, 0, 7) == 'custom_') {
- $fid = (int) substr($key, 7);
- if (empty($cFields[$fid])) {
- continue;
- }
- $htmlType = $cFields[$fid]['attributes']['html_type'];
- switch ($htmlType) {
- case 'File':
- $customFiles[] = $fid;
- unset($submitted["custom_$fid"]);
- break;
-
- case 'Select Country':
- case 'Select State/Province':
- $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
- break;
-
- case 'Select Date':
- if ($cFields[$fid]['attributes']['is_view']) {
- $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
- }
- break;
-
- case 'CheckBox':
- case 'AdvMulti-Select':
- case 'Multi-Select':
- case 'Multi-Select Country':
- case 'Multi-Select State/Province':
- // Merge values from both contacts for multivalue fields, CRM-4385
- // get the existing custom values from db.
- $customParams = array('entityID' => $mainId, $key => TRUE);
- $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
- if (!empty($customfieldValues[$key])) {
- $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
- if (is_array($existingValue) && !empty($existingValue)) {
- $mergeValue = $submittedCustomFields = array();
- if ($value == 'null') {
- // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
- $submitted[$key] = $value;
- }
- else {
- if ($value) {
- $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
- }
-
- // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
- // custom field value stored at $submittedCustomValue.
- foreach ($submittedCustomFields as $k => $v) {
- if ($v != '' && !in_array($v, $mergeValue)) {
- $mergeValue[] = $v;
- }
- }
-
- //keep state and country as array format.
- //for checkbox and m-select format w/ VALUE_SEPARATOR
- if (in_array($htmlType, array(
- 'CheckBox',
- 'Multi-Select',
- 'AdvMulti-Select',
- ))) {
- $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
- $mergeValue
- ) . CRM_Core_DAO::VALUE_SEPARATOR;
- }
- else {
- $submitted[$key] = $mergeValue;
- }
- }
- }
- }
- elseif (in_array($htmlType, array(
- 'Multi-Select Country',
- 'Multi-Select State/Province',
- ))) {
- //we require submitted values should be in array format
- if ($value) {
- $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
- //hack to remove null values from array.
- $mergeValue = array();
- foreach ($mergeValueArray as $k => $v) {
- if ($v != '') {
- $mergeValue[] = $v;
- }
- }
- $submitted[$key] = $mergeValue;
- }
- }
- break;
-
- default:
- break;
- }
- }
+ list($cFields, $customFiles, $submitted) = self::processCustomFields($mainId, $key, $cFields, $customFiles, $submitted, $value);
}
- // **** Do file custom fields related migrations
- // FIXME: move this someplace else (one of the BAOs) after discussing
- // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
- // like, delete a file...
-
- if (!isset($customFiles)) {
- $customFiles = array();
- }
- foreach ($customFiles as $customId) {
- list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
-
- // get the contact_id -> file_id mapping
- $fileIds = array();
- $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
- $dao = CRM_Core_DAO::executeQuery($sql);
- while ($dao->fetch()) {
- $fileIds[$dao->entity_id] = $dao->file_id;
- if ($dao->entity_id == $mainId) {
- CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
- }
- }
- $dao->free();
-
- // move the other contact's file to main contact
- //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
- if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
- $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
- }
- else {
- $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
- }
- CRM_Core_DAO::executeQuery($sql);
-
- if (CRM_Core_DAO::singleValueQuery("
- SELECT id
- FROM civicrm_entity_file
- WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
- ) {
- $sql = "
- UPDATE civicrm_entity_file
- SET entity_id = {$mainId}
- WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
- }
- else {
- $sql = "
- INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
- VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
- }
- CRM_Core_DAO::executeQuery($sql);
- }
+ self::processCustomFieldFiles($mainId, $otherId, $customFiles);
// move view only custom fields CRM-5362
- $viewOnlyCustomFields = array();
+ $viewOnlyCustomFields = [];
foreach ($submitted as $key => $value) {
- $fid = (int) substr($key, 7);
- if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
+ $fid = CRM_Core_BAO_CustomField::getKeyID($key);
+ if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
+ ) {
$viewOnlyCustomFields[$key] = $value;
}
}
-
// special case to set values for view only, CRM-5362
if (!empty($viewOnlyCustomFields)) {
$viewOnlyCustomFields['entityID'] = $mainId;
@@ -1710,14 +1626,14 @@ public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $che
}
if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
- CRM_Core_Permission::check('delete contacts'))
+ CRM_Core_Permission::check('delete contacts'))
) {
// if ext id is submitted then set it null for contact to be deleted
if (!empty($submitted['external_identifier'])) {
$query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
CRM_Core_DAO::executeQuery($query);
}
- civicrm_api3('contact', 'delete', array('id' => $otherId));
+ civicrm_api3('contact', 'delete', ['id' => $otherId]);
}
// CRM-15681 merge sub_types
@@ -1771,19 +1687,19 @@ public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $che
* Array of custom table names
*/
private static function getAffectedCustomTables($customFieldIDs) {
- $customTableToCopyValues = array();
+ $customTableToCopyValues = [];
foreach ($customFieldIDs as $fieldID) {
if (!empty($fieldID)) {
- $customField = civicrm_api3('custom_field', 'getsingle', array(
+ $customField = civicrm_api3('custom_field', 'getsingle', [
'id' => $fieldID,
'is_active' => TRUE,
- ));
+ ]);
if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
- $customGroup = civicrm_api3('custom_group', 'getsingle', array(
+ $customGroup = civicrm_api3('custom_group', 'getsingle', [
'id' => $customField['custom_group_id'],
'is_active' => TRUE,
- ));
+ ]);
if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
$customTableToCopyValues[] = $customGroup['table_name'];
@@ -1803,7 +1719,7 @@ private static function getAffectedCustomTables($customFieldIDs) {
*/
public static function getContactFields() {
$contactFields = CRM_Contact_DAO_Contact::fields();
- $invalidFields = array(
+ $invalidFields = [
'api_key',
'created_date',
'display_name',
@@ -1813,7 +1729,7 @@ public static function getContactFields() {
'primary_contact_id',
'sort_name',
'user_unique_id',
- );
+ ];
foreach ($contactFields as $field => $value) {
if (in_array($field, $invalidFields)) {
unset($contactFields[$field]);
@@ -1839,7 +1755,7 @@ public static function addMembershipToRealtedContacts($contactID) {
while ($dao->fetch()) {
$relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
if ($relationshipTypeId) {
- $membershipParams = array(
+ $membershipParams = [
'id' => $dao->id,
'contact_id' => $dao->contact_id,
'membership_type_id' => $dao->membership_type_id,
@@ -1848,33 +1764,13 @@ public static function addMembershipToRealtedContacts($contactID) {
'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
'source' => $dao->source,
'status_id' => $dao->status_id,
- );
+ ];
// create/update membership(s) for related contact(s)
CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
} // end of if relationshipTypeId
}
}
- /**
- * Add custom tables that extend contacts to the list of contact references.
- *
- * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
- * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
- * - the down side is it is not cached.
- *
- * Further changes should be include tests in the CRM_Core_MergerTest class
- * to ensure that disabled, subtype, multiple etc groups are still captured.
- *
- * @param array $cidRefs
- */
- public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
- $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
- $customValueTables->find();
- while ($customValueTables->fetch()) {
- $cidRefs[$customValueTables->table_name] = array('entity_id');
- }
- }
-
/**
* Create activities tracking the merge on affected contacts.
*
@@ -1884,28 +1780,31 @@ public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
* @throws \CiviCRM_API3_Exception
*/
public static function createMergeActivities($mainId, $otherId) {
- $params = array(
+ $params = [
1 => $otherId,
2 => $mainId,
- );
- $activity = civicrm_api3('activity', 'create', array(
+ ];
+ $activity = civicrm_api3('activity', 'create', [
'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
- $mainId,
+ $mainId,
'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
'target_contact_id' => $mainId,
'activity_type_id' => 'Contact Merged',
'status_id' => 'Completed',
- ));
- if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
- civicrm_api3('activity', 'create', array(
+ ]);
+ if (civicrm_api3('Setting', 'getvalue', [
+ 'name' => 'contact_undelete',
+ 'group' => 'CiviCRM Preferences',
+ ])) {
+ civicrm_api3('activity', 'create', [
'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
- $otherId,
+ $otherId,
'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
'target_contact_id' => $otherId,
'activity_type_id' => 'Contact Deleted by Merge',
'parent_id' => $activity['id'],
'status_id' => 'Completed',
- ));
+ ]);
}
}
@@ -1915,6 +1814,7 @@ public static function createMergeActivities($mainId, $otherId) {
* @param int $rule_group_id
* @param int $group_id
* @param bool $reloadCacheIfEmpty
+ * Should the cache be reloaded if empty - this must be false when in a dedupe action!
* @param int $batchLimit
* @param bool $isSelected
* Limit to selected pairs.
@@ -1926,20 +1826,23 @@ public static function createMergeActivities($mainId, $otherId) {
* @param bool $checkPermissions
* Respect logged in user permissions.
*
+ * @param int $searchLimit
+ * Limit to searching for matches against this many contacts.
+ *
* @return array
- * Array of matches meeting the criteria.
+ * Array of matches meeting the criteria.
*/
- public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE) {
- $where = self::getWhereString($batchLimit, $isSelected);
+ public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0) {
+ $where = self::getWhereString($isSelected);
$cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
$join = self::getJoinOnDedupeTable();
- $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
+ $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, [], $orderByClause, $includeConflicts);
if (empty($dupePairs) && $reloadCacheIfEmpty) {
// If we haven't found any dupes, probably cache is empty.
// Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
// until we have done some processing.
- CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions);
- $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
+ CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
+ $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, [], $orderByClause, $includeConflicts);
return $dupePairs;
}
return $dupePairs;
@@ -1959,9 +1862,9 @@ public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCache
*
* @return string
*/
- public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
+ public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = [], $checkPermissions = TRUE) {
$contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
- $cacheKeyString = "merge {$contactType}";
+ $cacheKeyString = "merge_{$contactType}";
$cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
$cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
$cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
@@ -1986,23 +1889,23 @@ public static function getMergeCacheKeyString($rule_group_id, $group_id, $criter
*/
public static function getSpecialValues($contact) {
$preferred_communication_method = CRM_Utils_Array::value('preferred_communication_method', $contact);
- $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
- $specialValues = array(
+ $value = empty($preferred_communication_method) ? [] : $preferred_communication_method;
+ $specialValues = [
'preferred_communication_method' => $value,
'communication_style_id' => $value,
- );
+ ];
if (!empty($contact['preferred_communication_method'])) {
// api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
$prefCommList = is_array($specialValues['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method'];
$specialValues['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
}
- $names = array(
- 'preferred_communication_method' => array(
+ $names = [
+ 'preferred_communication_method' => [
'newName' => 'preferred_communication_method_display',
'groupName' => 'preferred_communication_method',
- ),
- );
+ ],
+ ];
CRM_Core_OptionGroup::lookupValues($specialValues, $names);
if (!empty($contact['communication_style'])) {
@@ -2024,7 +1927,7 @@ public static function getMergeFieldsMetadata() {
return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
}
$fields = CRM_Contact_DAO_Contact::fields();
- static $optionValueFields = array();
+ static $optionValueFields = [];
if (empty($optionValueFields)) {
$optionValueFields = CRM_Core_OptionValue::getFields();
}
@@ -2045,18 +1948,18 @@ public static function getMergeFieldsMetadata() {
* @throws CRM_Core_Exception
*/
public static function getMergeContactDetails($contact_id) {
- $params = array(
+ $params = [
'contact_id' => $contact_id,
'version' => 3,
- 'return' => array_merge(array('display_name'), self::getContactFields()),
- );
+ 'return' => array_merge(['display_name'], self::getContactFields()),
+ ];
$result = civicrm_api('contact', 'get', $params);
// CRM-18480: Cancel the process if the contact is already deleted
if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
- throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', array(
+ throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1 => $contact_id,
- )));
+ ]));
}
return $result['values'][$contact_id];
@@ -2082,14 +1985,16 @@ public static function getMergeContactDetails($contact_id) {
*
* @param int $mainId
* @param int $otherId
- * @param array $locationMigrationInfo
- * Portion of the migration_info that holds location migration information.
*
* @param array $migrationInfo
* Migration info for the merge. This is passed to the hook as informational only.
*/
- public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) {
- foreach ($locationMigrationInfo as $key => $value) {
+ public static function mergeLocations($mainId, $otherId, $migrationInfo) {
+ foreach ($migrationInfo as $key => $value) {
+ $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
+ if (!$isLocationField) {
+ continue;
+ }
$locField = explode('_', $key);
$fieldName = $locField[2];
$fieldCount = $locField[3];
@@ -2107,17 +2012,17 @@ public static function mergeLocations($mainId, $otherId, $locationMigrationInfo,
}
$locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
}
- $blocksDAO = array();
+ $blocksDAO = [];
// @todo Handle OpenID (not currently in API).
if (!empty($locBlocks)) {
$locationBlocks = self::getLocationBlockInfo();
- $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
- $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
+ $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]);
+ $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]);
foreach ($locBlocks as $name => $block) {
- $blocksDAO[$name] = array('delete' => array(), 'update' => array());
+ $blocksDAO[$name] = ['delete' => [], 'update' => []];
if (!is_array($block) || CRM_Utils_System::isNull($block)) {
continue;
}
@@ -2226,20 +2131,20 @@ public static function mergeLocations($mainId, $otherId, $locationMigrationInfo,
protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
// go ahead with merge if there is no conflict
- $conflicts = array();
+ $conflicts = [];
if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
- $resultStats['merged'][] = array(
+ $resultStats['merged'][] = [
'main_id' => $mainId,
'other_id' => $otherId,
- );
+ ];
$deletedContacts[] = $otherId;
}
else {
- $resultStats['skipped'][] = array(
+ $resultStats['skipped'][] = [
'main_id' => $mainId,
'other_id' => $otherId,
- );
+ ];
}
// store any conflicts
@@ -2254,8 +2159,329 @@ protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedCo
// pair may have been flipped, so make sure we delete using both orders
CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
}
+ }
+
+ /**
+ * Replace the pseudo QFKey with zero if it is present.
+ *
+ * @todo - on the slim chance this is still relevant it should be moved to the form layer.
+ *
+ * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
+ * can still help.
+ *
+ * @param array $migrationInfo
+ */
+ protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
+ $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
+ foreach ($migrationInfo as $key => &$value) {
+ if ($value == $qfZeroBug) {
+ $value = '0';
+ }
+ }
+ }
+
+ /**
+ * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
+ *
+ * @param $mainId
+ * @param $key
+ * @param $cFields
+ * @param $customFiles
+ * @param $submitted
+ * @param $value
+ *
+ * @return array
+ */
+ protected static function processCustomFields($mainId, $key, $cFields, $customFiles, $submitted, $value) {
+ if (substr($key, 0, 7) == 'custom_') {
+ $fid = (int) substr($key, 7);
+ if (empty($cFields[$fid])) {
+ return [$cFields, $customFiles, $submitted];
+ }
+ $htmlType = $cFields[$fid]['attributes']['html_type'];
+ switch ($htmlType) {
+ case 'File':
+ $customFiles[] = $fid;
+ unset($submitted["custom_$fid"]);
+ break;
+
+ case 'Select Country':
+ case 'Select State/Province':
+ $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
+ break;
+
+ case 'Select Date':
+ if ($cFields[$fid]['attributes']['is_view']) {
+ $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
+ }
+ break;
+
+ case 'CheckBox':
+ case 'Multi-Select':
+ case 'Multi-Select Country':
+ case 'Multi-Select State/Province':
+ // Merge values from both contacts for multivalue fields, CRM-4385
+ // get the existing custom values from db.
+ $customParams = ['entityID' => $mainId, $key => TRUE];
+ $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
+ if (!empty($customfieldValues[$key])) {
+ $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
+ if (is_array($existingValue) && !empty($existingValue)) {
+ $mergeValue = $submittedCustomFields = [];
+ if ($value == 'null') {
+ // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
+ $submitted[$key] = $value;
+ }
+ else {
+ if ($value) {
+ $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
+ }
+
+ // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
+ // custom field value stored at $submittedCustomValue.
+ foreach ($submittedCustomFields as $k => $v) {
+ if ($v != '' && !in_array($v, $mergeValue)) {
+ $mergeValue[] = $v;
+ }
+ }
+
+ //keep state and country as array format.
+ //for checkbox and m-select format w/ VALUE_SEPARATOR
+ if (in_array($htmlType, [
+ 'CheckBox',
+ 'Multi-Select',
+ ])) {
+ $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
+ $mergeValue
+ ) . CRM_Core_DAO::VALUE_SEPARATOR;
+ }
+ else {
+ $submitted[$key] = $mergeValue;
+ }
+ }
+ }
+ }
+ elseif (in_array($htmlType, [
+ 'Multi-Select Country',
+ 'Multi-Select State/Province',
+ ])) {
+ //we require submitted values should be in array format
+ if ($value) {
+ $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
+ //hack to remove null values from array.
+ $mergeValue = [];
+ foreach ($mergeValueArray as $k => $v) {
+ if ($v != '') {
+ $mergeValue[] = $v;
+ }
+ }
+ $submitted[$key] = $mergeValue;
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+ }
+ return [$cFields, $customFiles, $submitted];
+ }
+
+ /**
+ * Get metadata for the custom fields for the merge.
+ *
+ * @param string $contactType
+ *
+ * @return array
+ */
+ protected static function getCustomFieldMetadata($contactType) {
+ $treeCache = [];
+ if (!array_key_exists($contactType, $treeCache)) {
+ $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree(
+ $contactType,
+ NULL,
+ NULL,
+ -1,
+ [],
+ NULL,
+ TRUE,
+ NULL,
+ FALSE,
+ FALSE
+ );
+ }
+
+ $cFields = [];
+ foreach ($treeCache[$contactType] as $key => $group) {
+ if (!isset($group['fields'])) {
+ continue;
+ }
+ foreach ($group['fields'] as $fid => $field) {
+ $cFields[$fid]['attributes'] = $field;
+ }
+ }
+ return $cFields;
+ }
+
+ /**
+ * Get conflicts for proposed merge pair.
+ *
+ * @param array $migrationInfo
+ * This is primarily to inform hooks. The can also modify it which feels
+ * pretty fragile to do it here - but it is historical.
+ * @param int $mainId
+ * Main contact with whom merge has to happen.
+ * @param int $otherId
+ * Duplicate contact which would be deleted after merge operation.
+ * @param string $mode
+ * Helps decide how to behave when there are conflicts.
+ * - A 'safe' value skips the merge if there are any un-resolved conflicts.
+ * - Does a force merge otherwise (aggressive mode).
+ *
+ * @return array
+ */
+ public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
+ $conflicts = [];
+ $originalMigrationInfo = $migrationInfo;
+ foreach ($migrationInfo as $key => $val) {
+ if ($val === "null") {
+ // Rule: Never overwrite with an empty value (in any mode)
+ unset($migrationInfo[$key]);
+ continue;
+ }
+ elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
+ substr($key, 0, 12) == 'move_custom_'
+ ) and $val != NULL
+ ) {
+ // Rule: If both main-contact, and other-contact have a field with a
+ // different value, then let $mode decide if to merge it or not
+ if (
+ (!empty($migrationInfo['rows'][$key]['main'])
+ // For custom fields a 0 (e.g in an int field) could be a true conflict. This
+ // is probably true for other fields too - e.g. 'do_not_email' but
+ // leaving that investigation as a @todo - until tests can be written.
+ // Note the handling of this has test coverage - although the data-typing
+ // of '0' feels flakey we have insurance.
+ || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
+ )
+ && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
+ ) {
+
+ // note it down & lets wait for response from the hook.
+ // For no response $mode will decide if to skip this merge
+ $conflicts[$key] = NULL;
+ }
+ }
+ elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
+ $locField = explode('_', $key);
+ $fieldName = $locField[2];
+ $fieldCount = $locField[3];
+
+ // Rule: Catch address conflicts (same address type on both contacts)
+ if (
+ isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
+ !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
+ ) {
+
+ // Load the address we're inspecting from the 'other' contact
+ $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
+ $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
+
+ // If it exists on the 'main' contact already, skip it. Otherwise
+ // if the location type exists already, log a conflict.
+ foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
+ if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
+ unset($migrationInfo[$key]);
+ break;
+ }
+ elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
+ $conflicts[$key] = NULL;
+ break;
+ }
+ }
+ }
+
+ // For other locations, don't merge/add if the values are the same
+ elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
+ unset($migrationInfo[$key]);
+ }
+ }
+ }
- CRM_Core_DAO::freeResult();
+ // A hook to implement other algorithms for choosing which contact to bias to when
+ // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
+ // merge happens with new values filled in here. For a particular field / row not to be merged
+ // field should be unset from fields_in_conflict.
+ $migrationData = [
+ 'old_migration_info' => $originalMigrationInfo,
+ 'mode' => $mode,
+ 'fields_in_conflict' => $conflicts,
+ 'merge_mode' => $mode,
+ 'migration_info' => $migrationInfo,
+ ];
+ CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
+ $conflicts = $migrationData['fields_in_conflict'];
+ // allow hook to override / manipulate migrationInfo as well
+ $migrationInfo = $migrationData['migration_info'];
+ $migrationInfo['skip_merge'] = CRM_Utils_Array::value('skip_merge', $migrationData);
+ return $conflicts;
+ }
+
+ /**
+ * Do file custom fields related migrations.
+ * FIXME: move this someplace else (one of the BAOs) after discussing
+ * where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
+ * like, delete a file...
+ *
+ * Note outstanding bug https://lab.civicrm.org/dev/core/issues/723
+ * relates to this code....
+ *
+ * @param $mainId
+ * @param $otherId
+ * @param $customFiles
+ */
+ protected static function processCustomFieldFiles($mainId, $otherId, $customFiles) {
+ foreach ($customFiles as $customId) {
+ list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
+
+ // get the contact_id -> file_id mapping
+ $fileIds = [];
+ $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
+ $dao = CRM_Core_DAO::executeQuery($sql);
+ while ($dao->fetch()) {
+ $fileIds[$dao->entity_id] = $dao->file_id;
+ if ($dao->entity_id == $mainId) {
+ CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
+ }
+ }
+
+ // move the other contact's file to main contact
+ //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
+ if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
+ $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
+ }
+ else {
+ $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
+ }
+ CRM_Core_DAO::executeQuery($sql);
+
+ if (CRM_Core_DAO::singleValueQuery("
+ SELECT id
+ FROM civicrm_entity_file
+ WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
+ ) {
+ $sql = "
+ UPDATE civicrm_entity_file
+ SET entity_id = {$mainId}
+ WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
+ }
+ else {
+ $sql = "
+ INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
+ VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
+ }
+ CRM_Core_DAO::executeQuery($sql);
+ }
}
}
diff --git a/CRM/Event/ActionMapping.php b/CRM/Event/ActionMapping.php
index c1a314a662e5..3d34696b8562 100644
--- a/CRM/Event/ActionMapping.php
+++ b/CRM/Event/ActionMapping.php
@@ -1,9 +1,9 @@
register(CRM_Event_ActionMapping::create(array(
+ $registrations->register(CRM_Event_ActionMapping::create([
'id' => CRM_Event_ActionMapping::EVENT_TYPE_MAPPING_ID,
'entity' => 'civicrm_participant',
'entity_label' => ts('Event Type'),
@@ -61,10 +61,8 @@ public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\Mappi
'entity_value_label' => ts('Event Type'),
'entity_status' => 'civicrm_participant_status_type',
'entity_status_label' => ts('Participant Status'),
- 'entity_date_start' => 'event_start_date',
- 'entity_date_end' => 'event_end_date',
- )));
- $registrations->register(CRM_Event_ActionMapping::create(array(
+ ]));
+ $registrations->register(CRM_Event_ActionMapping::create([
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
'entity' => 'civicrm_participant',
'entity_label' => ts('Event Name'),
@@ -72,10 +70,8 @@ public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\Mappi
'entity_value_label' => ts('Event Name'),
'entity_status' => 'civicrm_participant_status_type',
'entity_status_label' => ts('Participant Status'),
- 'entity_date_start' => 'event_start_date',
- 'entity_date_end' => 'event_end_date',
- )));
- $registrations->register(CRM_Event_ActionMapping::create(array(
+ ]));
+ $registrations->register(CRM_Event_ActionMapping::create([
'id' => CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID,
'entity' => 'civicrm_participant',
'entity_label' => ts('Event Template'),
@@ -83,9 +79,22 @@ public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\Mappi
'entity_value_label' => ts('Event Template'),
'entity_status' => 'civicrm_participant_status_type',
'entity_status_label' => ts('Participant Status'),
- 'entity_date_start' => 'event_start_date',
- 'entity_date_end' => 'event_end_date',
- )));
+ ]));
+ }
+
+ /**
+ * Get a list of available date fields.
+ *
+ * @return array
+ * Array(string $fieldName => string $fieldLabel).
+ */
+ public function getDateFields() {
+ return [
+ 'start_date' => ts('Event Start Date'),
+ 'end_date' => ts('Event End Date'),
+ 'registration_start_date' => ts('Registration Start Date'),
+ 'registration_end_date' => ts('Registration End Date'),
+ ];
}
/**
@@ -121,7 +130,7 @@ public function getRecipientListing($recipientType) {
return \CRM_Event_PseudoConstant::participantRole();
default:
- return array();
+ return [];
}
}
@@ -148,6 +157,9 @@ public function createQuery($schedule, $phase, $defaultParams) {
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
$query['casDateField'] = str_replace('event_', 'r.', $schedule->start_action_date);
+ if (empty($query['casDateField']) && $schedule->absolute_date) {
+ $query['casDateField'] = $schedule->absolute_date;
+ }
$query->join('r', 'INNER JOIN civicrm_event r ON e.event_id = r.id');
if ($schedule->recipient_listing && $schedule->limit_to) {
diff --git a/CRM/Event/BAO/Event.php b/CRM/Event/BAO/Event.php
index d9a653736e28..22034dd9f5d3 100644
--- a/CRM/Event/BAO/Event.php
+++ b/CRM/Event/BAO/Event.php
@@ -1,9 +1,9 @@
'civicrm_event',
'entity_id' => $event->id,
'modified_id' => $contactId,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Log::add($logParams);
@@ -183,28 +183,28 @@ public static function del($id) {
CRM_Utils_Hook::pre('delete', 'Event', $id, CRM_Core_DAO::$_nullArray);
- $extends = array('event');
+ $extends = ['event'];
$groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
foreach ($groupTree as $values) {
$query = "DELETE FROM %1 WHERE entity_id = %2";
- CRM_Core_DAO::executeQuery($query, array(
- 1 => array($values['table_name'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
- 2 => array($id, 'Integer'),
- ));
+ CRM_Core_DAO::executeQuery($query, [
+ 1 => [$values['table_name'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
+ 2 => [$id, 'Integer'],
+ ]);
}
// Clean up references to profiles used by the event (CRM-20935)
- $ufJoinParams = array(
+ $ufJoinParams = [
'module' => 'CiviEvent',
'entity_table' => 'civicrm_event',
'entity_id' => $id,
- );
+ ];
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
- $ufJoinParams = array(
+ $ufJoinParams = [
'module' => 'CiviEvent_Additional',
'entity_table' => 'civicrm_event',
'entity_id' => $id,
- );
+ ];
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
// price set cleanup, CRM-5527
@@ -306,7 +306,7 @@ public static function getEvents(
}
$query .= " ORDER BY title asc";
- $events = array();
+ $events = [];
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
@@ -332,7 +332,7 @@ public static function getEvents(
* Array of event summary values
*/
public static function getEventSummary() {
- $eventSummary = $eventIds = array();
+ $eventSummary = $eventIds = [];
$config = CRM_Core_Config::singleton();
// get permission and include them here
@@ -374,7 +374,7 @@ public static function getEventSummary() {
$cpst = $cpstObject->getTableName();
$query = "SELECT id, name, label, class FROM $cpst";
$status = CRM_Core_DAO::executeQuery($query);
- $statusValues = array();
+ $statusValues = [];
while ($status->fetch()) {
$statusValues[$status->id]['id'] = $status->id;
$statusValues[$status->id]['name'] = $status->name;
@@ -421,9 +421,9 @@ public static function getEventSummary() {
ORDER BY civicrm_event.start_date ASC
$event_summary_limit
";
- $eventParticipant = array();
+ $eventParticipant = [];
- $properties = array(
+ $properties = [
'id' => 'id',
'eventTitle' => 'event_title',
'isPublic' => 'is_public',
@@ -436,12 +436,12 @@ public static function getEventSummary() {
'notCountedDueToRole' => 'notCountedDueToRole',
'notCountedDueToStatus' => 'notCountedDueToStatus',
'notCountedParticipants' => 'notCountedParticipants',
- );
+ ];
- $params = array(1 => array($optionGroupId, 'Integer'));
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $params = [1 => [$optionGroupId, 'Integer']];
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
- )));
+ ]));
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
foreach ($properties as $property => $name) {
@@ -459,9 +459,9 @@ public static function getEventSummary() {
case 'is_map':
if ($dao->$name && $config->mapAPIKey) {
- $values = array();
- $ids = array();
- $params = array('entity_id' => $dao->id, 'entity_table' => 'civicrm_event');
+ $values = [];
+ $ids = [];
+ $params = ['entity_id' => $dao->id, 'entity_table' => 'civicrm_event'];
$values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
if (is_numeric(CRM_Utils_Array::value('geo_code_1', $values['location']['address'][1])) ||
(
@@ -483,7 +483,7 @@ public static function getEventSummary() {
case 'end_date':
case 'start_date':
$eventSummary['events'][$dao->id][$property] = CRM_Utils_Date::customFormat($dao->$name,
- NULL, array('d')
+ NULL, ['d']
);
break;
@@ -537,8 +537,8 @@ public static function getEventSummary() {
}
// prepare the area for per-status participant counts
- $statusClasses = array('Positive', 'Pending', 'Waiting', 'Negative');
- $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, array());
+ $statusClasses = ['Positive', 'Pending', 'Waiting', 'Negative'];
+ $eventSummary['events'][$dao->id]['statuses'] = array_fill_keys($statusClasses, []);
$eventSummary['events'][$dao->id]['friend'] = $dao->is_friend_active;
$eventSummary['events'][$dao->id]['is_monetary'] = $dao->is_monetary;
@@ -558,12 +558,12 @@ public static function getEventSummary() {
$statusCount = self::eventTotalSeats($dao->id, "( participant.status_id = {$statusId} )");
if ($statusCount) {
$urlString = "reset=1&force=1&event={$dao->id}&status=$statusId";
- $statusInfo = array(
+ $statusInfo = [
'url' => CRM_Utils_System::url('civicrm/event/search', $urlString),
'name' => $statusValue['name'],
'label' => $statusValue['label'],
'count' => $statusCount,
- );
+ ];
$eventSummary['events'][$dao->id]['statuses'][$class][] = $statusInfo;
}
}
@@ -615,7 +615,7 @@ public static function getParticipantCount(
if ($considerStatus && $considerRole && !$status && !$role) {
$operator = " OR ";
}
- $clause = array();
+ $clause = [];
if ($considerStatus) {
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
$statusClause = 'NOT IN';
@@ -637,7 +637,7 @@ public static function getParticipantCount(
}
if (!empty($roleTypes)) {
- $escapedRoles = array();
+ $escapedRoles = [];
foreach (array_keys($roleTypes) as $roleType) {
$escapedRoles[] = CRM_Utils_Type::escape($roleType, 'String');
}
@@ -692,24 +692,24 @@ public static function &getMapInfo(&$id) {
$dao = new CRM_Core_DAO();
$dao->query($sql);
- $locations = array();
+ $locations = [];
$config = CRM_Core_Config::singleton();
while ($dao->fetch()) {
- $location = array();
+ $location = [];
$location['displayName'] = addslashes($dao->display_name);
$location['lat'] = $dao->latitude;
$location['marker_class'] = 'Event';
$location['lng'] = $dao->longitude;
- $params = array('entity_id' => $id, 'entity_table' => 'civicrm_event');
+ $params = ['entity_id' => $id, 'entity_table' => 'civicrm_event'];
$addressValues = CRM_Core_BAO_Location::getValues($params, TRUE);
- $location['address'] = str_replace(array(
+ $location['address'] = str_replace([
"\r",
"\n",
- ), '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
+ ], '', addslashes(nl2br($addressValues['address'][1]['display_text'])));
$location['url'] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id);
$location['location_type'] = $dao->location_type;
@@ -834,9 +834,9 @@ public static function &getCompleteInfo(
}
$query .= " ORDER BY civicrm_event.start_date ASC";
- $params = array(1 => array($optionGroupId, 'Integer'));
+ $params = [1 => [$optionGroupId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $all = array();
+ $all = [];
$config = CRM_Core_Config::singleton();
$baseURL = parse_url($config->userFrameworkBaseURL);
@@ -860,7 +860,7 @@ public static function &getCompleteInfo(
}
while ($dao->fetch()) {
if (!empty($permissions) && in_array($dao->event_id, $permissions)) {
- $info = array();
+ $info = [];
$info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL) . $url;
$info['title'] = $dao->title;
@@ -879,7 +879,7 @@ public static function &getCompleteInfo(
$address = '';
- $addrFields = array(
+ $addrFields = [
'address_name' => $dao->address_name,
'street_address' => $dao->street_address,
'supplemental_address_1' => $dao->supplemental_address_1,
@@ -891,7 +891,7 @@ public static function &getCompleteInfo(
'postal_code_suffix' => $dao->postal_code_suffix,
'country' => $dao->country,
'county' => NULL,
- );
+ ];
CRM_Utils_String::append($address, ', ',
CRM_Utils_Address::format($addrFields)
@@ -920,149 +920,79 @@ public static function &getCompleteInfo(
* @param int $id
* The event id to copy.
* boolean $afterCreate call to copy after the create function
- * @param null $newEvent
- * @param bool $afterCreate
- *
+ * @param array $params
* @return CRM_Event_DAO_Event
+ * @throws \CRM_Core_Exception
*/
- public static function copy($id, $newEvent = NULL, $afterCreate = FALSE) {
-
- $eventValues = array();
+ public static function copy($id, $params = []) {
+ $eventValues = [];
//get the require event values.
- $eventParams = array('id' => $id);
- $returnProperties = array(
+ $eventParams = ['id' => $id];
+ $returnProperties = [
'loc_block_id',
'is_show_location',
'default_fee_id',
'default_discount_fee_id',
'is_template',
- );
+ ];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
- // since the location is sharable, lets use the same loc_block_id.
- $locBlockId = CRM_Utils_Array::value('loc_block_id', $eventValues);
-
- $fieldsFix = ($afterCreate) ? array() : array('prefix' => array('title' => ts('Copy of') . ' '));
+ $fieldsFix = ['prefix' => ['title' => ts('Copy of') . ' ']];
if (empty($eventValues['is_show_location'])) {
$fieldsFix['prefix']['is_show_location'] = 0;
}
- if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
- $copyEvent = $newEvent;
- }
-
- if (!isset($copyEvent)) {
- $copyEvent = &CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event',
- array('id' => $id),
- array(
- 'loc_block_id' =>
- ($locBlockId) ? $locBlockId : NULL,
- ),
- $fieldsFix
- );
- }
+ $copyEvent = CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event',
+ ['id' => $id],
+ // since the location is sharable, lets use the same loc_block_id.
+ ['loc_block_id' => CRM_Utils_Array::value('loc_block_id', $eventValues)] + $params,
+ $fieldsFix
+ );
CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_event', $id, $copyEvent->id);
- $copyUF = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin',
- array(
+ CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin',
+ [
'entity_id' => $id,
'entity_table' => 'civicrm_event',
- ),
- array('entity_id' => $copyEvent->id)
+ ],
+ ['entity_id' => $copyEvent->id]
);
- $copyTellFriend = &CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend',
- array(
+ CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend',
+ [
'entity_id' => $id,
'entity_table' => 'civicrm_event',
- ),
- array('entity_id' => $copyEvent->id)
+ ],
+ ['entity_id' => $copyEvent->id]
);
- $copyPCP = &CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock',
- array(
+ CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock',
+ [
'entity_id' => $id,
'entity_table' => 'civicrm_event',
- ),
- array('entity_id' => $copyEvent->id),
- array('replace' => array('target_entity_id' => $copyEvent->id))
+ ],
+ ['entity_id' => $copyEvent->id],
+ ['replace' => ['target_entity_id' => $copyEvent->id]]
);
- $oldMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $oldMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => ($eventValues['is_template'] ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
- )));
- $copyMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ ]));
+ $copyMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => ($copyEvent->is_template == 1 ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
- )));
- $copyReminder = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule',
- array('entity_value' => $id, 'mapping_id' => $oldMapping->getId()),
- array('entity_value' => $copyEvent->id, 'mapping_id' => $copyMapping->getId())
+ ]));
+ CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule',
+ ['entity_value' => $id, 'mapping_id' => $oldMapping->getId()],
+ ['entity_value' => $copyEvent->id, 'mapping_id' => $copyMapping->getId()]
);
- if (!$afterCreate) {
- // CRM-19302
- self::copyCustomFields($id, $copyEvent->id);
- }
-
$copyEvent->save();
CRM_Utils_System::flushCache();
- if (!$afterCreate) {
- CRM_Utils_Hook::copy('Event', $copyEvent);
- }
- return $copyEvent;
- }
+ CRM_Utils_Hook::copy('Event', $copyEvent);
- /**
- * Method that copies custom fields values from an old event to a new one. Fixes bug CRM-19302,
- * where if a custom field of File type was present, left both events using the same file,
- * breaking download URL's for the old event.
- *
- * @param int $oldEventID
- * @param int $newCopyID
- */
- public static function copyCustomFields($oldEventID, $newCopyID) {
- // Obtain custom values for old event
- $customParams = $htmlType = array();
- $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($oldEventID, 'Event');
-
- // If custom values present, we copy them
- if (!empty($customValues)) {
- // Get Field ID's and identify File type attributes, to handle file copying.
- $fieldIds = implode(', ', array_keys($customValues));
- $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
- $result = CRM_Core_DAO::executeQuery($sql);
-
- // Build array of File type fields
- while ($result->fetch()) {
- $htmlType[] = $result->id;
- }
-
- // Build params array of custom values
- foreach ($customValues as $field => $value) {
- if ($value !== NULL) {
- // Handle File type attributes
- if (in_array($field, $htmlType)) {
- $fileValues = CRM_Core_BAO_File::path($value, $oldEventID);
- $customParams["custom_{$field}_-1"] = array(
- 'name' => CRM_Utils_File::duplicate($fileValues[0]),
- 'type' => $fileValues[1],
- );
- }
- // Handle other types
- else {
- $customParams["custom_{$field}_-1"] = $value;
- }
- }
- }
-
- // Save Custom Fields for new Event
- CRM_Core_BAO_CustomValueTable::postProcess($customParams, 'civicrm_event', $newCopyID, 'Event');
- }
-
- // copy activity attachments ( if any )
- CRM_Core_BAO_File::copyEntityFile('civicrm_event', $oldEventID, 'civicrm_event', $newCopyID);
+ return $copyEvent;
}
/**
@@ -1075,7 +1005,7 @@ public static function copyCustomFields($oldEventID, $newCopyID) {
* @return bool
*/
public static function isMonetary($id) {
- static $isMonetary = array();
+ static $isMonetary = [];
if (!array_key_exists($id, $isMonetary)) {
$isMonetary[$id] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$id,
@@ -1095,7 +1025,7 @@ public static function isMonetary($id) {
* @return bool
*/
public static function usesPriceSet($id) {
- static $usesPriceSet = array();
+ static $usesPriceSet = [];
if (!array_key_exists($id, $usesPriceSet)) {
$usesPriceSet[$id] = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $id);
}
@@ -1110,24 +1040,25 @@ public static function usesPriceSet($id) {
* @param int $participantId
* @param bool $isTest
* @param bool $returnMessageText
+ * @return array|null
*/
public static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE) {
$template = CRM_Core_Smarty::singleton();
- $gIds = array(
+ $gIds = [
'custom_pre_id' => $values['custom_pre_id'],
'custom_post_id' => $values['custom_post_id'],
- );
+ ];
//get the params submitted by participant.
- $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array());
+ $participantParams = CRM_Utils_Array::value($participantId, $values['params'], []);
if (!$returnMessageText) {
//send notification email if field values are set (CRM-1941)
foreach ($gIds as $key => $gIdValues) {
if ($gIdValues) {
if (!is_array($gIdValues)) {
- $gIdValues = array($gIdValues);
+ $gIdValues = [$gIdValues];
}
foreach ($gIdValues as $gId) {
@@ -1144,11 +1075,11 @@ public static function sendMail($contactID, &$values, $participantId, $isTest =
$participantParams
);
list($profileValues) = $profileValues;
- $val = array(
+ $val = [
'id' => $gId,
'values' => $profileValues,
'email' => $email,
- );
+ ];
CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
}
}
@@ -1191,7 +1122,7 @@ public static function sendMail($contactID, &$values, $participantId, $isTest =
$sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
- $tplParams = array_merge($values, $participantParams, array(
+ $tplParams = array_merge($values, $participantParams, [
'email' => $email,
'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']),
'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']),
@@ -1200,13 +1131,13 @@ public static function sendMail($contactID, &$values, $participantId, $isTest =
'participantID' => $participantId,
'conference_sessions' => $sessions,
'credit_card_number' =>
- CRM_Utils_System::mungeCreditCard(
+ CRM_Utils_System::mungeCreditCard(
CRM_Utils_Array::value('credit_card_number', $participantParams)),
'credit_card_exp_date' =>
- CRM_Utils_Date::mysqlToIso(
+ CRM_Utils_Date::mysqlToIso(
CRM_Utils_Date::format(
CRM_Utils_Array::value('credit_card_exp_date', $participantParams))),
- ));
+ ]);
// CRM-13890 : NOTE wait list condition need to be given so that
// wait list message is shown properly in email i.e. WRT online event registration template
@@ -1219,14 +1150,14 @@ public static function sendMail($contactID, &$values, $participantId, $isTest =
$tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($tplParams['participant_status'], NULL, 'label');
}
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_online_receipt',
'contactId' => $contactID,
'isTest' => $isTest,
'tplParams' => $tplParams,
'PDFFilename' => ts('confirmation') . '.pdf',
- );
+ ];
// address required during receipt processing (pdf and email receipt)
if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
@@ -1240,7 +1171,7 @@ public static function sendMail($contactID, &$values, $participantId, $isTest =
// check if additional participant, if so filter only to relevant ones
// CRM-9902
if (!empty($values['params']['additionalParticipant'])) {
- $ownLineItems = array();
+ $ownLineItems = [];
foreach ($lineItem as $liKey => $liValue) {
$firstElement = array_pop($liValue);
if ($firstElement['entity_id'] == $participantId) {
@@ -1259,12 +1190,12 @@ public static function sendMail($contactID, &$values, $participantId, $isTest =
if ($returnMessageText) {
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
- return array(
+ return [
'subject' => $subject,
'body' => $message,
'to' => $displayName,
'html' => $html,
- );
+ ];
}
else {
$sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">";
@@ -1314,15 +1245,15 @@ public static function buildCustomDisplay(
$participantId,
$isTest,
$isCustomProfile = FALSE,
- $participantParams = array()
+ $participantParams = []
) {
if (!$id) {
- return array(NULL, NULL);
+ return [NULL, NULL];
}
if (!is_array($id)) {
$id = CRM_Utils_Type::escape($id, 'Positive');
- $profileIds = array($id);
+ $profileIds = [$id];
}
else {
$profileIds = $id;
@@ -1331,7 +1262,7 @@ public static function buildCustomDisplay(
$val = $groupTitles = NULL;
foreach ($profileIds as $gid) {
if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
- $values = array();
+ $values = [];
$fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW,
NULL, NULL, FALSE, NULL,
FALSE, NULL, CRM_Core_Permission::CREATE,
@@ -1339,16 +1270,16 @@ public static function buildCustomDisplay(
);
//this condition is added, since same contact can have multiple event registrations..
- $params = array(array('participant_id', '=', $participantId, 0, 0));
+ $params = [['participant_id', '=', $participantId, 0, 0]];
//add participant id
- $fields['participant_id'] = array(
+ $fields['participant_id'] = [
'name' => 'participant_id',
'title' => ts('Participant ID'),
- );
+ ];
//check whether its a text drive
if ($isTest) {
- $params[] = array('participant_test', '=', 1, 0, 0);
+ $params[] = ['participant_test', '=', 1, 0, 0];
}
//display campaign on thankyou page.
@@ -1388,7 +1319,7 @@ public static function buildCustomDisplay(
if (($groups = CRM_Utils_Array::value('group', $participantParams)) &&
is_array($groups)
) {
- $grpIds = array();
+ $grpIds = [];
foreach ($groups as $grpId => $isSelected) {
if ($isSelected) {
$grpIds[] = $grpId;
@@ -1396,7 +1327,7 @@ public static function buildCustomDisplay(
}
if (!empty($grpIds)) {
//get the group titles.
- $grpTitles = array();
+ $grpTitles = [];
$query = 'SELECT title FROM civicrm_group where id IN ( ' . implode(',', $grpIds) . ' )';
$grp = CRM_Core_DAO::executeQuery($query);
while ($grp->fetch()) {
@@ -1417,7 +1348,7 @@ public static function buildCustomDisplay(
isset($values[$fields['participant_status_id']['title']]) &&
is_numeric($values[$fields['participant_status_id']['title']])
) {
- $status = array();
+ $status = [];
$status = CRM_Event_PseudoConstant::participantStatus();
$values[$fields['participant_status_id']['title']] = $status[$values[$fields['participant_status_id']['title']]];
}
@@ -1426,7 +1357,7 @@ public static function buildCustomDisplay(
isset($values[$fields['participant_role_id']['title']]) &&
is_numeric($values[$fields['participant_role_id']['title']])
) {
- $roles = array();
+ $roles = [];
$roles = CRM_Event_PseudoConstant::participantRole();
$values[$fields['participant_role_id']['title']] = $roles[$values[$fields['participant_role_id']['title']]];
}
@@ -1469,7 +1400,7 @@ public static function buildCustomDisplay(
//return if we only require array of participant's info.
if ($isCustomProfile) {
if (count($val)) {
- return array($val, $groupTitles);
+ return [$val, $groupTitles];
}
else {
return NULL;
@@ -1491,7 +1422,7 @@ public static function buildCustomDisplay(
*
* @param array $profileFields
*/
- public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) {
+ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = []) {
if ($gid) {
$config = CRM_Core_Config::singleton();
$session = CRM_Core_Session::singleton();
@@ -1555,21 +1486,21 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
$values[$index] = '';
}
}
- elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
+ elseif (in_array(substr($name, 0, -3), ['gender', 'prefix', 'suffix', 'communication_style'])) {
$values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
}
- elseif (in_array($name, array(
+ elseif (in_array($name, [
'addressee',
'email_greeting',
'postal_greeting',
- ))) {
- $filterCondition = array('greeting_type' => $name);
+ ])) {
+ $filterCondition = ['greeting_type' => $name];
$greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
$values[$index] = $greeting[$params[$name]];
}
elseif ($name === 'preferred_communication_method') {
$communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
- $compref = array();
+ $compref = [];
$pref = $params[$name];
if (is_array($pref)) {
foreach ($pref as $k => $v) {
@@ -1585,7 +1516,7 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
}
elseif ($name == 'group') {
$groups = CRM_Contact_BAO_GroupContact::getGroupList();
- $title = array();
+ $title = [];
foreach ($params[$name] as $gId => $dontCare) {
if ($dontCare) {
$title[] = $groups[$gId];
@@ -1595,8 +1526,8 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
}
elseif ($name == 'tag') {
$entityTags = $params[$name];
- $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 = [];
if (is_array($entityTags)) {
foreach ($entityTags as $tagId => $dontCare) {
$title[] = $allTags[$tagId];
@@ -1604,13 +1535,13 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
}
$values[$index] = implode(', ', $title);
}
- elseif ('participant_role_id' == $name OR
+ elseif ('participant_role_id' == $name or
'participant_role' == $name
) {
$roles = CRM_Event_PseudoConstant::participantRole();
$values[$index] = $roles[$params[$name]];
}
- elseif ('participant_status_id' == $name OR
+ elseif ('participant_status_id' == $name or
'participant_status' == $name
) {
$status = CRM_Event_PseudoConstant::participantStatus();
@@ -1623,11 +1554,11 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
elseif (strpos($name, '-') !== FALSE) {
list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
$detailName = str_replace(' ', '_', $name);
- if (in_array($fieldName, array(
+ if (in_array($fieldName, [
'state_province',
'country',
'county',
- ))) {
+ ])) {
$values[$index] = $params[$detailName];
$idx = $detailName . '_id';
$values[$index] = $params[$idx];
@@ -1709,7 +1640,7 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
$customVal = $params[$name];
}
//take the custom field options
- $returnProperties = array($name => 1);
+ $returnProperties = [$name => 1];
$query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
if (!$skip) {
$displayValue = CRM_Core_BAO_CustomField::displayValue($customVal, $cfID);
@@ -1735,11 +1666,11 @@ public static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$
$url = CRM_Utils_System::fixURL($params[$name]);
$values[$index] = "{$params[$name]}";
}
- elseif (in_array($name, array(
+ elseif (in_array($name, [
'birth_date',
'deceased_date',
'participant_register_date',
- ))) {
+ ])) {
$values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
}
else {
@@ -1780,7 +1711,7 @@ public static function buildCustomProfile(
$skipCancel = TRUE
) {
- $customProfile = $additionalIDs = array();
+ $customProfile = $additionalIDs = [];
if (!$participantId) {
CRM_Core_Error::fatal(ts('Cannot find participant ID'));
}
@@ -1822,10 +1753,13 @@ public static function buildCustomProfile(
$isCustomProfile = TRUE;
$i = 1;
- $title = $groupTitles = array();
+ $title = $groupTitles = [];
foreach ($additionalIDs as $pId => $cId) {
//get the params submitted by participant.
- $participantParams = CRM_Utils_Array::value($pId, $values['params'], array());
+ $participantParams = NULL;
+ if (isset($values['params'])) {
+ $participantParams = CRM_Utils_Array::value($pId, $values['params'], []);
+ }
list($profilePre, $groupTitles) = self::buildCustomDisplay($preProfileID,
'additionalCustomPre',
@@ -1886,8 +1820,8 @@ public static function buildCustomProfile(
* @return array
*/
public static function getLocationEvents() {
- $events = array();
- $ret = array(
+ $events = [];
+ $ret = [
'loc_block_id',
'loc_block_id.address_id.name',
'loc_block_id.address_id.street_address',
@@ -1896,16 +1830,16 @@ public static function getLocationEvents() {
'loc_block_id.address_id.supplemental_address_3',
'loc_block_id.address_id.city',
'loc_block_id.address_id.state_province_id.name',
- );
+ ];
- $result = civicrm_api3('Event', 'get', array(
+ $result = civicrm_api3('Event', 'get', [
'check_permissions' => TRUE,
'return' => $ret,
- 'loc_block_id.address_id' => array('IS NOT NULL' => 1),
- 'options' => array(
+ 'loc_block_id.address_id' => ['IS NOT NULL' => 1],
+ 'options' => [
'limit' => 0,
- ),
- ));
+ ],
+ ]);
foreach ($result['values'] as $event) {
$address = '';
@@ -1990,6 +1924,7 @@ public static function validRegistrationDate(&$values) {
* @return boolean
* true if allow registration otherwise false
*/
+
/**
* @param $values
*
@@ -2002,7 +1937,7 @@ public static function showHideRegistrationLink($values) {
$alreadyRegistered = FALSE;
if ($contactID) {
- $params = array('contact_id' => $contactID);
+ $params = ['contact_id' => $contactID];
if ($eventId = CRM_Utils_Array::value('id', $values['event'])) {
$params['event_id'] = $eventId;
@@ -2027,6 +1962,7 @@ public static function showHideRegistrationLink($values) {
* Key/value participant info.
* @return boolean
*/
+
/**
* @param array $params
*
@@ -2055,47 +1991,139 @@ public static function checkRegistration($params) {
/**
* Make sure that the user has permission to access this event.
+ * FIXME: We have separate caches for checkPermission('permission') and getAllPermissions['permissions'] so they don't interfere.
+ * But it would be nice to clean this up some more.
*
* @param int $eventId
- * @param int $type
+ * @param int $permissionType
*
- * @return string
- * the permission that the user has (or null)
+ * @return bool|array
+ * Whether the user has permission for this event (or if eventId=NULL an array of permissions)
+ * @throws \CiviCRM_API3_Exception
*/
- public static function checkPermission($eventId = NULL, $type = CRM_Core_Permission::VIEW) {
- static $permissions = NULL;
-
- if (empty($permissions)) {
- $result = civicrm_api3('Event', 'get', array(
- 'check_permissions' => 1,
- 'return' => 'title',
- 'options' => array(
- 'limit' => 0,
- ),
- ));
- $allEvents = CRM_Utils_Array::collect('title', $result['values']);
-
- $result = civicrm_api3('Event', 'get', array(
- 'check_permissions' => 1,
- 'return' => 'title',
- 'created_id' => 'user_contact_id',
- 'options' => array(
- 'limit' => 0,
- ),
- ));
- $createdEvents = CRM_Utils_Array::collect('title', $result['values']);
+ public static function checkPermission($eventId = NULL, $permissionType = CRM_Core_Permission::VIEW) {
+ if (empty($eventId)) {
+ CRM_Core_Error::deprecatedFunctionWarning('CRM_Event_BAO_Event::getAllPermissions');
+ return self::getAllPermissions();
+ }
+
+ switch ($permissionType) {
+ case CRM_Core_Permission::EDIT:
+ // We also set the cached "view" permission to TRUE if "edit" is TRUE
+ if (isset(Civi::$statics[__CLASS__]['permission']['edit'][$eventId])) {
+ return Civi::$statics[__CLASS__]['permission']['edit'][$eventId];
+ }
+ Civi::$statics[__CLASS__]['permission']['edit'][$eventId] = FALSE;
+
+ list($allEvents, $createdEvents) = self::checkPermissionGetInfo($eventId);
+ // Note: for a multisite setup, a user with edit all events, can edit all events
+ // including those from other sites
+ if (($permissionType == CRM_Core_Permission::EDIT) && CRM_Core_Permission::check('edit all events')) {
+ Civi::$statics[__CLASS__]['permission']['edit'][$eventId] = TRUE;
+ Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
+ }
+ elseif (in_array($eventId, CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents))) {
+ Civi::$statics[__CLASS__]['permission']['edit'][$eventId] = TRUE;
+ Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
+ }
+ return Civi::$statics[__CLASS__]['permission']['edit'][$eventId];
+
+ case CRM_Core_Permission::VIEW:
+ if (isset(Civi::$statics[__CLASS__]['permission']['view'][$eventId])) {
+ return Civi::$statics[__CLASS__]['permission']['view'][$eventId];
+ }
+ Civi::$statics[__CLASS__]['permission']['view'][$eventId] = FALSE;
+
+ list($allEvents, $createdEvents) = self::checkPermissionGetInfo($eventId);
+ if (CRM_Core_Permission::check('access CiviEvent')) {
+ if (in_array($eventId, CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, array_keys($createdEvents)))) {
+ // User created this event so has permission to view it
+ return Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
+ }
+ if (CRM_Core_Permission::check('view event participants')) {
+ // User has permission to view all events
+ // use case: allow "view all events" but NOT "edit all events"
+ // so for a normal site allow users with these two permissions to view all events AND
+ // at the same time also allow any hook to override if needed.
+ if (in_array($eventId, CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, array_keys($allEvents)))) {
+ Civi::$statics[__CLASS__]['permission']['view'][$eventId] = TRUE;
+ }
+ }
+ }
+ return Civi::$statics[__CLASS__]['permission']['view'][$eventId];
+
+ case CRM_Core_Permission::DELETE:
+ if (isset(Civi::$statics[__CLASS__]['permission']['delete'][$eventId])) {
+ return Civi::$statics[__CLASS__]['permission']['delete'][$eventId];
+ }
+ Civi::$statics[__CLASS__]['permission']['delete'][$eventId] = FALSE;
+ if (CRM_Core_Permission::check('delete in CiviEvent')) {
+ Civi::$statics[__CLASS__]['permission']['delete'][$eventId] = TRUE;
+ }
+ return Civi::$statics[__CLASS__]['permission']['delete'][$eventId];
+
+ default:
+ return FALSE;
+ }
+ }
+
+ /**
+ * This is a helper for refactoring checkPermission
+ * FIXME: We should be able to get rid of these arrays, but that would require understanding how CRM_ACL_API::group actually works!
+ *
+ * @param int $eventId
+ *
+ * @return array $allEvents, $createdEvents
+ * @throws \CiviCRM_API3_Exception
+ */
+ private static function checkPermissionGetInfo($eventId = NULL) {
+ $params = [
+ 'check_permissions' => 1,
+ 'return' => 'id, created_id',
+ 'options' => ['limit' => 0],
+ ];
+ if ($eventId) {
+ $params['id'] = $eventId;
+ }
+
+ $allEvents = [];
+ $createdEvents = [];
+ $eventResult = civicrm_api3('Event', 'get', $params);
+ if ($eventResult['count'] > 0) {
+ $contactId = CRM_Core_Session::getLoggedInContactID();
+ foreach ($eventResult['values'] as $eventId => $eventDetail) {
+ $allEvents[$eventId] = $eventId;
+ if (isset($eventDetail['created_id']) && $contactId == $eventDetail['created_id']) {
+ $createdEvents[$eventId] = $eventId;
+ }
+ }
+ }
+ return [$allEvents, $createdEvents];
+ }
+
+ /**
+ * Make sure that the user has permission to access this event.
+ * TODO: This function needs refactoring / cleaning up after being split from checkPermissions()
+ *
+ * @return array
+ * Array of events with permissions (array_keys=permissions)
+ * @throws \CiviCRM_API3_Exception
+ */
+ public static function getAllPermissions() {
+ if (!isset(Civi::$statics[__CLASS__]['permissions'])) {
+ list($allEvents, $createdEvents) = self::checkPermissionGetInfo();
// Note: for a multisite setup, a user with edit all events, can edit all events
// including those from other sites
if (CRM_Core_Permission::check('edit all events')) {
- $permissions[CRM_Core_Permission::EDIT] = array_keys($allEvents);
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::EDIT] = array_keys($allEvents);
}
else {
- $permissions[CRM_Core_Permission::EDIT] = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents);
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::EDIT] = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $allEvents, $createdEvents);
}
if (CRM_Core_Permission::check('edit all events')) {
- $permissions[CRM_Core_Permission::VIEW] = array_keys($allEvents);
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::VIEW] = array_keys($allEvents);
}
else {
if (CRM_Core_Permission::check('access CiviEvent') &&
@@ -2106,25 +2134,21 @@ public static function checkPermission($eventId = NULL, $type = CRM_Core_Permiss
// at the same time also allow any hook to override if needed.
$createdEvents = array_keys($allEvents);
}
- $permissions[CRM_Core_Permission::VIEW] = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, $createdEvents);
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::VIEW] = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_event', $allEvents, $createdEvents);
}
- $permissions[CRM_Core_Permission::DELETE] = array();
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::DELETE] = [];
if (CRM_Core_Permission::check('delete in CiviEvent')) {
// Note: we want to restrict the scope of delete permission to
// events that are editable/viewable (usecase multisite).
// We can remove array_intersect once we have ACL support for delete functionality.
- $permissions[CRM_Core_Permission::DELETE] = array_intersect($permissions[CRM_Core_Permission::EDIT],
- $permissions[CRM_Core_Permission::VIEW]
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::DELETE] = array_intersect(Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::EDIT],
+ Civi::$statics[__CLASS__]['permissions'][CRM_Core_Permission::VIEW]
);
}
}
- if ($eventId) {
- return in_array($eventId, $permissions[$type]) ? TRUE : FALSE;
- }
-
- return $permissions;
+ return Civi::$statics[__CLASS__]['permissions'];
}
/**
@@ -2142,19 +2166,19 @@ public static function getFromEmailIds($eventId = NULL) {
if ($eventId) {
// add the email id configured for the event
- $params = array('id' => $eventId);
- $returnProperties = array('confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
- $eventEmail = array();
+ $params = ['id' => $eventId];
+ $returnProperties = ['confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm'];
+ $eventEmail = [];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $eventEmail, $returnProperties);
if (!empty($eventEmail['confirm_from_name']) && !empty($eventEmail['confirm_from_email'])) {
$eventEmailId = "{$eventEmail['confirm_from_name']} <{$eventEmail['confirm_from_email']}>";
$fromEmailValues['from_email_id'][$eventEmailId] = htmlspecialchars($eventEmailId);
- $fromEmailId = array(
+ $fromEmailId = [
'cc' => CRM_Utils_Array::value('cc_confirm', $eventEmail),
'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventEmail),
- );
+ ];
$fromEmailValues = array_merge($fromEmailValues, $fromEmailId);
}
}
@@ -2206,7 +2230,7 @@ public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
{$extraWhereClause}
GROUP BY participant.event_id";
- return (int) CRM_Core_DAO::singleValueQuery($query, array(1 => array($eventId, 'Positive')));
+ return (int) CRM_Core_DAO::singleValueQuery($query, [1 => [$eventId, 'Positive']]);
}
/**
@@ -2220,14 +2244,14 @@ public static function eventTotalSeats($eventId, $extraWhereClause = NULL) {
* Array of custom data defaults.
*/
public static function getTemplateDefaultValues($templateId) {
- $defaults = array();
+ $defaults = [];
if (!$templateId) {
return $defaults;
}
- $templateParams = array('id' => $templateId);
+ $templateParams = ['id' => $templateId];
CRM_Event_BAO_Event::retrieve($templateParams, $defaults);
- $fieldsToExclude = array(
+ $fieldsToExclude = [
'id',
'default_fee_id',
'default_discount_fee_id',
@@ -2235,7 +2259,7 @@ public static function getTemplateDefaultValues($templateId) {
'created_id',
'is_template',
'template_title',
- );
+ ];
$defaults = array_diff_key($defaults, array_flip($fieldsToExclude));
return $defaults;
}
@@ -2246,8 +2270,8 @@ public static function getTemplateDefaultValues($templateId) {
* @return object
*/
public static function get_sub_events($event_id) {
- $params = array('parent_event_id' => $event_id);
- $defaults = array();
+ $params = ['parent_event_id' => $event_id];
+ $defaults = [];
return CRM_Event_BAO_Event::retrieve($params, $defaults);
}
@@ -2260,15 +2284,15 @@ public static function get_sub_events($event_id) {
* Campaign id of that event.
*/
public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
- $params = array();
- $params[1] = array($eventID, 'Integer');
+ $params = [];
+ $params[1] = [$eventID, 'Integer'];
if (empty($eventCampaignID)) {
$query = "UPDATE civicrm_participant SET campaign_id = NULL WHERE event_id = %1";
}
else {
$query = "UPDATE civicrm_participant SET campaign_id = %2 WHERE event_id = %1";
- $params[2] = array($eventCampaignID, 'Integer');
+ $params[2] = [$eventCampaignID, 'Integer'];
}
CRM_Core_DAO::executeQuery($query, $params);
}
@@ -2283,8 +2307,8 @@ public static function updateParticipantCampaignID($eventID, $eventCampaignID) {
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
- $params = array();
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
+ $params = [];
// Special logic for fields whose options depend on context or properties
switch ($fieldName) {
case 'financial_type_id':
@@ -2296,4 +2320,32 @@ public static function buildOptions($fieldName, $context = NULL, $props = array(
return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
}
+ /**
+ * @return array
+ */
+ public static function getEntityRefFilters() {
+ return [
+ ['key' => 'event_type_id', 'value' => ts('Event Type')],
+ [
+ 'key' => 'start_date',
+ 'value' => ts('Start Date'),
+ 'options' => [
+ ['key' => '{">":"now"}', 'value' => ts('Upcoming')],
+ [
+ 'key' => '{"BETWEEN":["now - 3 month","now"]}',
+ 'value' => ts('Past 3 Months'),
+ ],
+ [
+ 'key' => '{"BETWEEN":["now - 6 month","now"]}',
+ 'value' => ts('Past 6 Months'),
+ ],
+ [
+ 'key' => '{"BETWEEN":["now - 1 year","now"]}',
+ 'value' => ts('Past Year'),
+ ],
+ ],
+ ],
+ ];
+ }
+
}
diff --git a/CRM/Event/BAO/Participant.php b/CRM/Event/BAO/Participant.php
index c8452b9e2df6..db4bf4f7c2c1 100644
--- a/CRM/Event/BAO/Participant.php
+++ b/CRM/Event/BAO/Participant.php
@@ -1,9 +1,9 @@
array('Registered', 'Cancelled'),
- 'Pending from incomplete transaction' => array('Registered', 'Cancelled'),
- 'On waitlist' => array('Cancelled', 'Pending from waitlist'),
- 'Pending from waitlist' => array('Registered', 'Cancelled'),
- 'Awaiting approval' => array('Cancelled', 'Pending from approval'),
- 'Pending from approval' => array('Registered', 'Cancelled'),
- );
+ public static $_statusTransitionsRules = [
+ 'Pending from pay later' => ['Registered', 'Cancelled'],
+ 'Pending from incomplete transaction' => ['Registered', 'Cancelled'],
+ 'On waitlist' => ['Cancelled', 'Pending from waitlist'],
+ 'Pending from waitlist' => ['Registered', 'Cancelled'],
+ 'Awaiting approval' => ['Cancelled', 'Pending from approval'],
+ 'Pending from approval' => ['Registered', 'Cancelled'],
+ ];
/**
*/
@@ -136,8 +136,6 @@ public static function &add(&$params) {
$participantBAO->save();
- $session = CRM_Core_Session::singleton();
-
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
if (!empty($params['id'])) {
@@ -170,7 +168,7 @@ public static function getValues(&$params, &$values, &$ids) {
$participant = new CRM_Event_BAO_Participant();
$participant->copyValues($params);
$participant->find();
- $participants = array();
+ $participants = [];
while ($participant->fetch()) {
$ids['participant'] = $participant->id;
CRM_Core_DAO::storeValues($participant, $values[$participant->id]);
@@ -203,9 +201,12 @@ public static function create(&$params) {
return $participant;
}
- if ((!CRM_Utils_Array::value('id', $params)) ||
+ // Log activity when creating new participant or changing status
+ if (empty($params['id']) ||
(isset($params['status_id']) && $params['status_id'] != $status)
) {
+ // Default status if not specified
+ $participant->status_id = $participant->status_id ?: self::fields()['participant_status_id']['default'];
CRM_Activity_BAO_Activity::addActivity($participant);
}
@@ -236,10 +237,10 @@ public static function create(&$params) {
}
$noteValue = NULL;
$hasNoteField = FALSE;
- foreach (array(
- 'note',
- 'participant_note',
- ) as $noteFld) {
+ foreach ([
+ 'note',
+ 'participant_note',
+ ] as $noteFld) {
if (array_key_exists($noteFld, $params)) {
$noteValue = $params[$noteFld];
$hasNoteField = TRUE;
@@ -248,14 +249,14 @@ public static function create(&$params) {
}
if ($noteId || $noteValue) {
if ($noteValue) {
- $noteParams = array(
+ $noteParams = [
'entity_table' => 'civicrm_participant',
'note' => $noteValue,
'entity_id' => $participant->id,
'contact_id' => $id,
'modified_date' => date('Ymd'),
- );
- $noteIDs = array();
+ ];
+ $noteIDs = [];
if ($noteId) {
$noteIDs['id'] = $noteId;
}
@@ -267,13 +268,13 @@ public static function create(&$params) {
}
// Log the information on successful add/edit of Participant data.
- $logParams = array(
+ $logParams = [
'entity_table' => 'civicrm_participant',
'entity_id' => $participant->id,
'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id),
'modified_id' => $id,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Log::add($logParams);
@@ -288,7 +289,7 @@ public static function create(&$params) {
"action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::check('edit event participants')) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home"
@@ -377,12 +378,12 @@ public static function eventFull(
$allStatusIds = array_keys($countedStatuses);
}
- $where = array(' event.id = %1 ');
+ $where = [' event.id = %1 '];
if (!$considerTestParticipant) {
$where[] = ' ( participant.is_test = 0 OR participant.is_test IS NULL ) ';
}
if (!empty($participantRoles)) {
- $escapedRoles = array();
+ $escapedRoles = [];
foreach (array_keys($participantRoles) as $participantRole) {
$escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
}
@@ -390,7 +391,7 @@ public static function eventFull(
$where[] = " participant.role_id IN ( '" . implode("', '", $escapedRoles) . "' ) ";
}
- $eventParams = array(1 => array($eventId, 'Positive'));
+ $eventParams = [1 => [$eventId, 'Positive']];
//in case any waiting, straight forward event is full.
if ($includeWaitingList && $onWaitlistStatusId) {
@@ -500,17 +501,17 @@ public static function eventFull(
*/
public static function priceSetOptionsCount(
$eventId,
- $skipParticipantIds = array(),
+ $skipParticipantIds = [],
$considerCounted = TRUE,
$considerWaiting = TRUE,
$considerTestParticipants = FALSE
) {
- $optionsCount = array();
+ $optionsCount = [];
if (!$eventId) {
return $optionsCount;
}
- $allStatusIds = array();
+ $allStatusIds = [];
if ($considerCounted) {
$countedStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
$allStatusIds = array_merge($allStatusIds, array_keys($countedStatuses));
@@ -547,11 +548,12 @@ public static function priceSetOptionsCount(
INNER JOIN civicrm_price_field_value value ON ( value.id = line.price_field_value_id )
INNER JOIN civicrm_price_field field ON ( value.price_field_id = field.id )
WHERE participant.event_id = %1
+ AND line.qty > 0
{$statusIdClause}
{$isTestClause}
{$skipParticipantClause}";
- $lineItem = CRM_Core_DAO::executeQuery($sql, array(1 => array($eventId, 'Positive')));
+ $lineItem = CRM_Core_DAO::executeQuery($sql, [1 => [$eventId, 'Positive']]);
while ($lineItem->fetch()) {
$count = $lineItem->count;
if (!$count) {
@@ -631,67 +633,67 @@ public static function &importableFields($contactType = 'Individual', $status =
if (!self::$_importableFields) {
if (!$onlyParticipant) {
if (!$status) {
- $fields = array('' => array('title' => ts('- do not import -')));
+ $fields = ['' => ['title' => ts('- do not import -')]];
}
else {
- $fields = array('' => array('title' => ts('- Participant Fields -')));
+ $fields = ['' => ['title' => ts('- Participant Fields -')]];
}
}
else {
- $fields = array();
+ $fields = [];
}
$tmpFields = CRM_Event_DAO_Participant::import();
- $note = array(
- 'participant_note' => array(
+ $note = [
+ 'participant_note' => [
'title' => ts('Participant Note'),
'name' => 'participant_note',
'headerPattern' => '/(participant.)?note$/i',
'data_type' => CRM_Utils_Type::T_TEXT,
- ),
- );
+ ],
+ ];
// Split status and status id into 2 fields
// Fixme: it would be better to leave as 1 field and intelligently handle both during import
- $participantStatus = array(
- 'participant_status' => array(
+ $participantStatus = [
+ 'participant_status' => [
'title' => ts('Participant Status'),
'name' => 'participant_status',
'data_type' => CRM_Utils_Type::T_STRING,
- ),
- );
+ ],
+ ];
$tmpFields['participant_status_id']['title'] = ts('Participant Status Id');
// Split role and role id into 2 fields
// Fixme: it would be better to leave as 1 field and intelligently handle both during import
- $participantRole = array(
- 'participant_role' => array(
+ $participantRole = [
+ 'participant_role' => [
'title' => ts('Participant Role'),
'name' => 'participant_role',
'data_type' => CRM_Utils_Type::T_STRING,
- ),
- );
+ ],
+ ];
$tmpFields['participant_role_id']['title'] = ts('Participant Role Id');
- $eventType = array(
- 'event_type' => array(
+ $eventType = [
+ 'event_type' => [
'title' => ts('Event Type'),
'name' => 'event_type',
'data_type' => CRM_Utils_Type::T_STRING,
- ),
- );
+ ],
+ ];
- $tmpContactField = $contactFields = array();
- $contactFields = array();
+ $tmpContactField = $contactFields = [];
+ $contactFields = [];
if (!$onlyParticipant) {
$contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => $contactType,
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
if (is_array($fieldsArray)) {
@@ -743,34 +745,34 @@ public static function &importableFields($contactType = 'Individual', $status =
public static function &exportableFields($checkPermission = TRUE) {
if (!self::$_exportableFields) {
if (!self::$_exportableFields) {
- self::$_exportableFields = array();
+ self::$_exportableFields = [];
}
$participantFields = CRM_Event_DAO_Participant::export();
$eventFields = CRM_Event_DAO_Event::export();
- $noteField = array(
- 'participant_note' => array(
+ $noteField = [
+ 'participant_note' => [
'title' => ts('Participant Note'),
'name' => 'participant_note',
'type' => CRM_Utils_Type::T_STRING,
- ),
- );
+ ],
+ ];
- $participantStatus = array(
- 'participant_status' => array(
+ $participantStatus = [
+ 'participant_status' => [
'title' => ts('Participant Status (label)'),
'name' => 'participant_status',
'type' => CRM_Utils_Type::T_STRING,
- ),
- );
+ ],
+ ];
- $participantRole = array(
- 'participant_role' => array(
+ $participantRole = [
+ 'participant_role' => [
'title' => ts('Participant Role (label)'),
'name' => 'participant_role',
'type' => CRM_Utils_Type::T_STRING,
- ),
- );
+ ],
+ ];
$participantFields['participant_status_id']['title'] .= ' (ID)';
$participantFields['participant_role_id']['title'] .= ' (ID)';
@@ -806,7 +808,7 @@ public static function participantDetails($participantId) {
";
$dao = CRM_Core_DAO::executeQuery($query);
- $details = array();
+ $details = [];
while ($dao->fetch()) {
$details['name'] = $dao->name;
$details['title'] = $dao->title;
@@ -884,22 +886,22 @@ public static function deleteParticipant($id) {
$transaction = new CRM_Core_Transaction();
//delete activity record
- $params = array(
+ $params = [
'source_record_id' => $id,
// activity type id for event registration
'activity_type_id' => 5,
- );
+ ];
CRM_Activity_BAO_Activity::deleteActivity($params);
// delete the participant payment record
// we need to do this since the cascaded constraints
// dont work with join tables
- $p = array('participant_id' => $id);
+ $p = ['participant_id' => $id];
CRM_Event_BAO_ParticipantPayment::deleteParticipantPayment($p);
// cleanup line items.
- $participantsId = array();
+ $participantsId = [];
$participantsId = self::getAdditionalParticipantIds($id);
$participantsId[] = $id;
CRM_Price_BAO_LineItem::deleteLineItems($participantsId, 'civicrm_participant');
@@ -918,10 +920,10 @@ public static function deleteParticipant($id) {
CRM_Utils_Hook::post('delete', 'Participant', $participant->id, $participant);
// delete the recently created Participant
- $participantRecent = array(
+ $participantRecent = [
'id' => $id,
'type' => 'Participant',
- );
+ ];
CRM_Utils_Recent::del($participantRecent);
@@ -943,17 +945,17 @@ public static function checkDuplicate($input, &$duplicates) {
$eventId = CRM_Utils_Array::value('event_id', $input);
$contactId = CRM_Utils_Array::value('contact_id', $input);
- $clause = array();
- $input = array();
+ $clause = [];
+ $input = [];
if ($eventId) {
$clause[] = "event_id = %1";
- $input[1] = array($eventId, 'Integer');
+ $input[1] = [$eventId, 'Integer'];
}
if ($contactId) {
$clause[] = "contact_id = %2";
- $input[2] = array($contactId, 'Integer');
+ $input[2] = [$contactId, 'Integer'];
}
if (empty($clause)) {
@@ -1017,7 +1019,7 @@ public static function fixEventLevel(&$eventLevel) {
* @return array
*/
public static function getAdditionalParticipantIds($primaryParticipantId, $excludeCancel = TRUE, $oldStatusId = NULL) {
- $additionalParticipantIds = array();
+ $additionalParticipantIds = [];
if (!$primaryParticipantId) {
return $additionalParticipantIds;
}
@@ -1059,21 +1061,21 @@ public static function getAdditionalParticipantIds($primaryParticipantId, $exclu
*/
public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID, $discountedPriceFieldOptionID, $feeLevel) {
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID, NULL);
- $params = array(
- 1 => array($priceSetId, 'Integer'),
- );
+ $params = [
+ 1 => [$priceSetId, 'Integer'],
+ ];
if ($discountedPriceFieldOptionID) {
$query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
WHERE cpf.price_set_id = %1 AND cpfv.label = (SELECT label from civicrm_price_field_value WHERE id = %2)";
- $params[2] = array($discountedPriceFieldOptionID, 'Integer');
+ $params[2] = [$discountedPriceFieldOptionID, 'Integer'];
}
else {
$feeLevel = current($feeLevel);
$query = "SELECT cpfv.amount FROM `civicrm_price_field_value` cpfv
LEFT JOIN civicrm_price_field cpf ON cpfv.price_field_id = cpf.id
WHERE cpf.price_set_id = %1 AND cpfv.label LIKE %2";
- $params[2] = array($feeLevel, 'String');
+ $params[2] = [$feeLevel, 'String'];
}
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -1090,7 +1092,7 @@ public static function getUnDiscountedAmountForEventPriceSetFieldValue($eventID,
* @return array
*/
public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
- $feeDetails = array();
+ $feeDetails = [];
if (!is_array($participantIds) || empty($participantIds)) {
return $feeDetails;
}
@@ -1124,8 +1126,8 @@ public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
$query = "$select $from $where";
$feeInfo = CRM_Core_DAO::executeQuery($query);
- $feeProperties = array('fee_level', 'fee_amount');
- $lineProperties = array(
+ $feeProperties = ['fee_level', 'fee_amount'];
+ $lineProperties = [
'lineId',
'label',
'qty',
@@ -1137,7 +1139,7 @@ public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
'participant_count',
'price_field_value_id',
'description',
- );
+ ];
while ($feeInfo->fetch()) {
if ($hasLineItems) {
foreach ($lineProperties as $property) {
@@ -1165,7 +1167,7 @@ public function getFeeDetails($participantIds, $hasLineItems = FALSE) {
* $displayName => $viewUrl
*/
public static function getAdditionalParticipants($primaryParticipantID) {
- $additionalParticipantIDs = array();
+ $additionalParticipantIDs = [];
$additionalParticipantIDs = self::getAdditionalParticipantIds($primaryParticipantID);
if (!empty($additionalParticipantIDs)) {
foreach ($additionalParticipantIDs as $additionalParticipantID) {
@@ -1212,10 +1214,10 @@ public static function updateParticipantStatus($participantID, $oldStatusID, $ne
if (!empty($cascadeAdditionalIds)) {
try {
foreach ($cascadeAdditionalIds as $id) {
- $participantParams = array(
+ $participantParams = [
'id' => $id,
'status_id' => $newStatusID,
- );
+ ];
civicrm_api3('Participant', 'create', $participantParams);
}
return TRUE;
@@ -1284,7 +1286,7 @@ public static function transitionParticipants(
}
//thumb rule is if we triggering primary participant need to triggered additional
- $allParticipantIds = $primaryANDAdditonalIds = array();
+ $allParticipantIds = $primaryANDAdditonalIds = [];
foreach ($participantIds as $id) {
$allParticipantIds[] = $id;
if (self::isPrimaryParticipant($id)) {
@@ -1306,11 +1308,11 @@ public static function transitionParticipants(
$allParticipantIds = array_unique($allParticipantIds);
//pull required participants, contacts, events data, if not in hand
- static $eventDetails = array();
- static $domainValues = array();
- static $contactDetails = array();
+ static $eventDetails = [];
+ static $domainValues = [];
+ static $contactDetails = [];
- $contactIds = $eventIds = $participantDetails = array();
+ $contactIds = $eventIds = $participantDetails = [];
$statusTypes = CRM_Event_PseudoConstant::participantStatus();
$participantRoles = CRM_Event_PseudoConstant::participantRole();
@@ -1325,7 +1327,7 @@ public static function transitionParticipants(
$query = "SELECT * FROM civicrm_participant WHERE id IN {$participantIdClause}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -1335,7 +1337,7 @@ public static function transitionParticipants(
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
if (!array_key_exists($dao->contact_id, $contactDetails)) {
$contactIds[$dao->contact_id] = $dao->contact_id;
}
@@ -1349,10 +1351,10 @@ public static function transitionParticipants(
if (empty($domainValues)) {
// making all tokens available to templates.
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
- 'domain' => array('name', 'phone', 'address', 'email'),
+ $tokens = [
+ 'domain' => ['name', 'phone', 'address', 'email'],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
@@ -1364,7 +1366,7 @@ public static function transitionParticipants(
// get the contact details.
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
FALSE, FALSE, NULL,
- array(),
+ [],
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
@@ -1376,14 +1378,14 @@ public static function transitionParticipants(
if (!empty($eventIds)) {
foreach ($eventIds as $eventId) {
//retrieve event information
- $eventParams = array('id' => $eventId);
+ $eventParams = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$eventId]);
//get default participant role.
$eventDetails[$eventId]['participant_role'] = CRM_Utils_Array::value($eventDetails[$eventId]['default_role_id'], $participantRoles);
//get the location info
- $locParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
+ $locParams = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event'];
$eventDetails[$eventId]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
}
}
@@ -1419,36 +1421,36 @@ public static function transitionParticipants(
//as we process additional w/ primary, there might be case if user
//select primary as well as additionals, so avoid double processing.
- $processedParticipantIds = array();
- $mailedParticipants = array();
+ $processedParticipantIds = [];
+ $mailedParticipants = [];
//send mails and update status.
foreach ($participantDetails as $participantId => $participantValues) {
- $updateParticipantIds = array();
+ $updateParticipantIds = [];
if (in_array($participantId, $processedParticipantIds)) {
continue;
}
//check is it primary and has additional.
if (array_key_exists($participantId, $primaryANDAdditonalIds)) {
- foreach ($primaryANDAdditonalIds[$participantId] as $additonalId) {
+ foreach ($primaryANDAdditonalIds[$participantId] as $additionalId) {
if ($emailType) {
- $mail = self::sendTransitionParticipantMail($additonalId,
- $participantDetails[$additonalId],
- $eventDetails[$participantDetails[$additonalId]['event_id']],
- $contactDetails[$participantDetails[$additonalId]['contact_id']],
+ $mail = self::sendTransitionParticipantMail($additionalId,
+ $participantDetails[$additionalId],
+ $eventDetails[$participantDetails[$additionalId]['event_id']],
+ $contactDetails[$participantDetails[$additionalId]['contact_id']],
$domainValues,
$emailType
);
//get the mail participant ids
if ($mail) {
- $mailedParticipants[$additonalId] = $contactDetails[$participantDetails[$additonalId]['contact_id']]['display_name'];
+ $mailedParticipants[$additionalId] = $contactDetails[$participantDetails[$additionalId]['contact_id']]['display_name'];
}
}
- $updateParticipantIds[] = $additonalId;
- $processedParticipantIds[] = $additonalId;
+ $updateParticipantIds[] = $additionalId;
+ $processedParticipantIds[] = $additionalId;
}
}
@@ -1483,10 +1485,10 @@ public static function transitionParticipants(
//return result for cron.
if ($returnResult) {
- $results = array(
+ $results = [
'mailedParticipants' => $mailedParticipants,
'updatedParticipantIds' => $processedParticipantIds,
- );
+ ];
return $results;
}
@@ -1553,11 +1555,11 @@ public static function sendTransitionParticipantMail(
}
list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'participant_' . strtolower($mailType),
'contactId' => $contactId,
- 'tplParams' => array(
+ 'tplParams' => [
'contact' => $contactDetails,
'domain' => $domainValues,
'participant' => $participantValues,
@@ -1568,32 +1570,29 @@ public static function sendTransitionParticipantMail(
'isExpired' => $mailType == 'Expired',
'isConfirm' => $mailType == 'Confirm',
'checksumValue' => $checksumValue,
- ),
+ ],
'from' => $receiptFrom,
'toName' => $participantName,
'toEmail' => $toEmail,
'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
- )
+ ]
);
// 3. create activity record.
if ($mailSent) {
$now = date('YmdHis');
$activityType = 'Event Registration';
- $activityParams = array(
+ $activityParams = [
'subject' => $subject,
'source_contact_id' => $contactId,
'source_record_id' => $participantId,
- 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
- $activityType,
- 'name'
- ),
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
'activity_date_time' => CRM_Utils_Date::isoToMysql($now),
'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']),
'is_test' => $participantValues['is_test'],
'status_id' => 2,
- );
+ ];
if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
@@ -1615,7 +1614,7 @@ public static function sendTransitionParticipantMail(
*/
public function updateStatusMessage($participantId, $statusChangeTo, $fromStatusId) {
$statusMsg = NULL;
- $results = self::transitionParticipants(array($participantId),
+ $results = self::transitionParticipants([$participantId],
$statusChangeTo, $fromStatusId, TRUE
);
@@ -1628,10 +1627,10 @@ public function updateStatusMessage($participantId, $statusChangeTo, $fromStatus
array_key_exists($processedId, $results['mailedParticipants'])
) {
$statusMsg .= ' ' . ts("Participant status has been updated to '%1'. An email has been sent to %2.",
- array(
+ [
1 => $allStatuses[$statusChangeTo],
2 => $results['mailedParticipants'][$processedId],
- )
+ ]
);
}
}
@@ -1669,9 +1668,9 @@ public static function eventFullMessage($eventId, $participantId = NULL) {
$emptySeats = self::eventFull($eventId, FALSE, FALSE);
if (is_string($emptySeats) && $emptySeats !== NULL) {
$maxParticipants = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'max_participants');
- $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", array(
- 1 => $maxParticipants,
- )) . ' ';
+ $eventfullMsg = ts("This event currently has the maximum number of participants registered (%1). However, you can still override this limit and register additional participants using this form.", [
+ 1 => $maxParticipants,
+ ]) . ' ';
}
$hasWaiting = FALSE;
@@ -1693,10 +1692,10 @@ public static function eventFullMessage($eventId, $participantId = NULL) {
);
$eventfullMsg .= ts("There are %2 people currently on the waiting list for this event. You can view waitlisted registrations here, or you can continue and register additional participants using this form.",
- array(
+ [
1 => $viewWaitListUrl,
2 => $waitListedCount,
- )
+ ]
);
}
@@ -1737,9 +1736,9 @@ public static function isPrimaryParticipant($participantId) {
*/
public static function getValidAdditionalIds($participantId, $oldStatusId, $newStatusId) {
- $additionalParticipantIds = array();
+ $additionalParticipantIds = [];
- static $participantStatuses = array();
+ static $participantStatuses = [];
if (empty($participantStatuses)) {
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
@@ -1782,7 +1781,7 @@ public static function getContactParticipantCount($contactID) {
*/
public static function getParticipantIds($contributionId, $excludeCancelled = FALSE) {
- $ids = array();
+ $ids = [];
if (!$contributionId) {
return $ids;
}
@@ -1797,9 +1796,9 @@ public static function getParticipantIds($contributionId, $excludeCancelled = FA
// get additional participant ids (including cancelled)
while ($participantPayment->fetch()) {
- $ids = array_merge($ids, array_merge(array(
+ $ids = array_merge($ids, array_merge([
$participantPayment->participant_id,
- ), self::getAdditionalParticipantIds($participantPayment->participant_id,
+ ], self::getAdditionalParticipantIds($participantPayment->participant_id,
$excludeCancelled
)));
}
@@ -1818,7 +1817,7 @@ public static function getParticipantIds($contributionId, $excludeCancelled = FA
*/
public static function getAdditionalParticipantUrl($participantIds) {
foreach ($participantIds as $value) {
- $links = array();
+ $links = [];
$details = self::participantDetails($value);
$viewUrl = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=view&reset=1&id={$value}&cid={$details['cid']}"
@@ -1844,7 +1843,7 @@ public static function getAdditionalParticipantUrl($participantIds) {
* @param int $discountedPriceFieldOptionID
* ID of the civicrm_price_field_value field for the discount id.
*/
- public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID) {
+ public static function createDiscountTrxn($eventID, $contributionParams, $feeLevel, $discountedPriceFieldOptionID = NULL) {
$financialTypeID = $contributionParams['contribution']->financial_type_id;
$total_amount = $contributionParams['total_amount'];
@@ -1897,26 +1896,23 @@ public static function addActivityForSelection($participantId, $activityType) {
$date = CRM_Utils_Date::currentDBDate();
$event = CRM_Event_BAO_Event::getEvents(0, $eventId);
$subject = sprintf("Registration selections changed for %s", CRM_Utils_Array::value($eventId, $event));
- $targetCid = $contactId;
- $srcRecId = $participantId;
// activity params
- $activityParams = array(
- 'source_contact_id' => $targetCid,
- 'source_record_id' => $srcRecId,
+ $activityParams = [
+ 'source_contact_id' => $contactId,
+ 'source_record_id' => $participantId,
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
'subject' => $subject,
'activity_date_time' => $date,
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
'skipRecentView' => TRUE,
- );
+ ];
// create activity with target contacts
- $session = CRM_Core_Session::singleton();
- $id = $session->get('userID');
+ $id = CRM_Core_Session::singleton()->getLoggedInContactID();;
if ($id) {
$activityParams['source_contact_id'] = $id;
- $activityParams['target_contact_id'][] = $targetCid;
+ $activityParams['target_contact_id'][] = $contactId;
}
// @todo use api & also look at duplication of similar methods.
CRM_Activity_BAO_Activity::create($activityParams);
@@ -1934,8 +1930,8 @@ public static function addActivityForSelection($participantId, $activityType) {
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
- $params = array('condition' => array());
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
+ $params = ['condition' => []];
if ($fieldName == 'status_id' && $context != 'validate') {
// Get rid of cart-related option if disabled
@@ -1957,9 +1953,9 @@ public static function formatFieldsAndSetProfileDefaults($contactId, &$form) {
if (!$contactId) {
return;
}
- $fields = array();
+ $fields = [];
if (!empty($form->_fields)) {
- $removeCustomFieldTypes = array('Participant');
+ $removeCustomFieldTypes = ['Participant'];
foreach ($form->_fields as $name => $dontCare) {
if ((substr($name, 0, 7) == 'custom_' && !$form->_allowConfirmation
diff --git a/CRM/Event/BAO/ParticipantPayment.php b/CRM/Event/BAO/ParticipantPayment.php
index 40cba7d8a4c8..cb12a2ddc1d6 100644
--- a/CRM/Event/BAO/ParticipantPayment.php
+++ b/CRM/Event/BAO/ParticipantPayment.php
@@ -1,9 +1,9 @@
copyValues($params);
- if (isset($ids['id'])) {
- $participantPayment->id = CRM_Utils_Array::value('id', $ids);
+ if ($id) {
+ $participantPayment->id = $id;
}
else {
$participantPayment->find(TRUE);
}
$participantPayment->save();
- if (isset($ids['id'])) {
- CRM_Utils_Hook::post('edit', 'ParticipantPayment', $ids['id'], $participantPayment);
+ if (empty($participantPayment->contribution_id)) {
+ // For an id update contribution_id may be unknown. We want it
+ // further down so perhaps get it before the hooks.
+ $participantPayment->find(TRUE);
+ }
+ if ($id) {
+ CRM_Utils_Hook::post('edit', 'ParticipantPayment', $participantPayment->id, $participantPayment);
}
else {
- CRM_Utils_Hook::post('create', 'ParticipantPayment', NULL, $participantPayment);
+ CRM_Utils_Hook::post('create', 'ParticipantPayment', $participantPayment->id, $participantPayment);
}
//generally if people are creating participant_payments via the api they won't be setting the line item correctly - we can't help them if they are doing complex transactions
// but if they have a single line item for the contribution we can assume it should refer to the participant line
- $lineItemCount = CRM_Core_DAO::singleValueQuery("select count(*) FROM civicrm_line_item WHERE contribution_id = %1", array(
- 1 => array(
- $participantPayment->contribution_id,
- 'Integer',
- ),
- ));
+ $lineItemCount = CRM_Core_DAO::singleValueQuery("select count(*) FROM civicrm_line_item WHERE contribution_id = %1", [
+ 1 => [
+ $participantPayment->contribution_id,
+ 'Integer',
+ ],
+ ]);
if ($lineItemCount == 1) {
$sql = "UPDATE civicrm_line_item li
SET entity_table = 'civicrm_participant', entity_id = %1
WHERE contribution_id = %2 AND entity_table = 'civicrm_contribution'";
- CRM_Core_DAO::executeQuery($sql, array(
- 1 => array($participantPayment->participant_id, 'Integer'),
- 2 => array($participantPayment->contribution_id, 'Integer'),
- ));
+ CRM_Core_DAO::executeQuery($sql, [
+ 1 => [$participantPayment->participant_id, 'Integer'],
+ 2 => [$participantPayment->contribution_id, 'Integer'],
+ ]);
}
return $participantPayment;
diff --git a/CRM/Event/BAO/ParticipantStatusType.php b/CRM/Event/BAO/ParticipantStatusType.php
index 434e02762dfe..a897d21cc34f 100644
--- a/CRM/Event/BAO/ParticipantStatusType.php
+++ b/CRM/Event/BAO/ParticipantStatusType.php
@@ -1,9 +1,9 @@
fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
@@ -174,7 +172,7 @@ public static function process($params) {
'end_date' => $dao->end_date,
'expiration_time' => $dao->expiration_time,
'requires_approval' => $dao->requires_approval,
- );
+ ];
}
if (!empty($participantDetails)) {
@@ -199,7 +197,7 @@ public static function process($params) {
//lets get the transaction mechanism.
$transaction = new CRM_Core_Transaction();
- $ids = array($participantId);
+ $ids = [$participantId];
$expiredId = array_search('Expired', $expiredStatuses);
$results = CRM_Event_BAO_Participant::transitionParticipants($ids, $expiredId, $values['status_id'], TRUE, TRUE);
$transaction->commit();
@@ -249,7 +247,7 @@ public static function process($params) {
//get the additional participant if any.
$additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
- $allIds = array($participantId);
+ $allIds = [$participantId];
if (!empty($additionalIds)) {
$allIds = array_merge($allIds, $additionalIds);
}
@@ -260,7 +258,7 @@ public static function process($params) {
if (($requiredSpaces <= $eventOpenSpaces) || ($eventOpenSpaces === NULL)) {
$transaction = new CRM_Core_Transaction();
- $ids = array($participantId);
+ $ids = [$participantId];
$updateStatusId = array_search('Pending from waitlist', $pendingStatuses);
//lets take a call to make pending or need approval
@@ -321,7 +319,7 @@ public static function process($params) {
}
}
- return array('is_error' => 0, 'messages' => $returnMessages);
+ return ['is_error' => 0, 'messages' => $returnMessages];
}
}
diff --git a/CRM/Event/BAO/Query.php b/CRM/Event/BAO/Query.php
index c542cff51d34..5f8e8bf00023 100644
--- a/CRM/Event/BAO/Query.php
+++ b/CRM/Event/BAO/Query.php
@@ -1,9 +1,9 @@
_element['participant_role_id'] = 1;
$query->_tables['civicrm_participant'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
- $query->_pseudoConstantsSelect['participant_role_id'] = array(
+ $query->_pseudoConstantsSelect['participant_role_id'] = [
'pseudoField' => 'participant_role_id',
'idCol' => 'participant_role_id',
- );
+ ];
}
//add participant_role
@@ -166,10 +166,10 @@ public static function select(&$query) {
$query->_element['participant_role'] = 1;
$query->_tables['participant_role'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
- $query->_pseudoConstantsSelect['participant_role'] = array(
+ $query->_pseudoConstantsSelect['participant_role'] = [
'pseudoField' => 'participant_role',
'idCol' => 'participant_role',
- );
+ ];
}
//add register date
@@ -187,10 +187,10 @@ public static function select(&$query) {
//participant note
if (!empty($query->_returnProperties['participant_note'])) {
- $query->_select['participant_note'] = "civicrm_note.note as participant_note";
+ $query->_select['participant_note'] = "participant_note.note as participant_note";
$query->_element['participant_note'] = 1;
$query->_tables['participant_note'] = 1;
- $query->_whereTables['civicrm_note'] = 1;
+ $query->_whereTables['participant_note'] = 1;
}
if (!empty($query->_returnProperties['participant_is_pay_later'])) {
@@ -226,7 +226,6 @@ public static function select(&$query) {
}
}
-
/**
* @param $query
*/
@@ -305,7 +304,7 @@ public static function whereClauseSingle(&$values, &$query) {
$thisEventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($value, 'civicrm_event');
if ($thisEventHasParent) {
$getAllConnections = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($thisEventHasParent, 'civicrm_event');
- $allEventIds = array();
+ $allEventIds = [];
foreach ($getAllConnections as $key => $val) {
$allEventIds[] = $val['id'];
}
@@ -334,17 +333,19 @@ public static function whereClauseSingle(&$values, &$query) {
);
$isTest = $value ? 'a Test' : 'not a Test';
- $query->_qill[$grouping][] = ts("Participant is %1", array(1 => $isTest));
+ $query->_qill[$grouping][] = ts("Participant is %1", [1 => $isTest]);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
}
return;
case 'participant_fee_id':
+ $val_regexp = [];
foreach ($value as $k => &$val) {
$val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
+ $val_regexp[$k] = CRM_Core_DAO::escapeString(preg_quote(trim($val)));
$val = CRM_Core_DAO::escapeString(trim($val));
}
- $feeLabel = implode('|', $value);
+ $feeLabel = implode('|', $val_regexp);
$query->_where[$grouping][] = "civicrm_participant.fee_level REGEXP '{$feeLabel}'";
$query->_qill[$grouping][] = ts("Fee level") . " IN " . implode(', ', $value);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
@@ -372,7 +373,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'participant_registered_by_id':
$qillName = $name;
- if (in_array($name, array(
+ if (in_array($name, [
'participant_status_id',
'participant_source',
'participant_id',
@@ -382,8 +383,7 @@ public static function whereClauseSingle(&$values, &$query) {
'participant_is_pay_later',
'participant_campaign_id',
'participant_registered_by_id',
- ))
- ) {
+ ])) {
$name = str_replace('participant_', '', $name);
if ($name == 'is_pay_later') {
$qillName = $name;
@@ -402,7 +402,7 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name", $op, $value, $dataType);
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
@@ -427,7 +427,7 @@ public static function whereClauseSingle(&$values, &$query) {
}
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
@@ -446,13 +446,11 @@ public static function whereClauseSingle(&$values, &$query) {
case 'event_type_id':
case 'event_title':
$qillName = $name;
- if (in_array($name, array(
- 'event_id',
- 'event_title',
- 'event_is_public',
- )
- )
- ) {
+ if (in_array($name, [
+ 'event_id',
+ 'event_title',
+ 'event_is_public',
+ ])) {
$name = str_replace('event_', '', $name);
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
@@ -462,9 +460,16 @@ public static function whereClauseSingle(&$values, &$query) {
if (!array_key_exists($qillName, $fields)) {
break;
}
- list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Event', $name, $value, $op, array('check_permission' => $checkPermission));
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
+ list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Event', $name, $value, $op, ['check_permission' => $checkPermission]);
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$qillName]['title'], 2 => $op, 3 => $value]);
return;
+
+ case 'participant_note':
+ $query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
+ $query->_tables['participant_note'] = $query->_whereTables['participant_note'] = 1;
+ $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('participant_note.note', $op, $value, 'String');
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $fields[$name]['title'], 2 => $op, 3 => $value]);
+ break;
}
}
@@ -493,8 +498,8 @@ public static function from($name, $mode, $side) {
break;
case 'participant_note':
- $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_participant' AND
- civicrm_participant.id = civicrm_note.entity_id )";
+ $from .= " $side JOIN civicrm_note participant_note ON ( participant_note.entity_table = 'civicrm_participant' AND
+ civicrm_participant.id = participant_note.entity_id )";
break;
case 'participant_status':
@@ -527,7 +532,7 @@ public static function defaultReturnProperties(
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_EVENT) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -553,7 +558,7 @@ public static function defaultReturnProperties(
'participant_fee_currency' => 1,
'participant_registered_by_id' => 1,
'participant_campaign_id' => 1,
- );
+ ];
if ($includeCustomFields) {
// also get all the custom participant properties
@@ -580,27 +585,25 @@ public static function buildSearchForm(&$form) {
$form->assign('dataURLEventFee', $dataURLEventFee);
- $form->addEntityRef('event_id', ts('Event Name'), array(
- 'entity' => 'event',
- 'placeholder' => ts('- any -'),
- 'multiple' => 1,
- 'select' => array('minimumInputLength' => 0),
- )
- );
- $form->addEntityRef('event_type_id', ts('Event Type'), array(
- 'entity' => 'option_value',
- 'placeholder' => ts('- any -'),
- 'select' => array('minimumInputLength' => 0),
- 'api' => array(
- 'params' => array('option_group_id' => 'event_type'),
- ),
- )
- );
+ $form->addEntityRef('event_id', ts('Event Name'), [
+ 'entity' => 'Event',
+ 'placeholder' => ts('- any -'),
+ 'multiple' => 1,
+ 'select' => ['minimumInputLength' => 0],
+ ]);
+ $form->addEntityRef('event_type_id', ts('Event Type'), [
+ 'entity' => 'OptionValue',
+ 'placeholder' => ts('- any -'),
+ 'select' => ['minimumInputLength' => 0],
+ 'api' => [
+ 'params' => ['option_group_id' => 'event_type'],
+ ],
+ ]);
$obj = new CRM_Report_Form_Event_ParticipantListing();
$form->add('select', 'participant_fee_id',
ts('Fee Level'),
$obj->getPriceLevels(),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -'))
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
);
CRM_Core_Form_Date::buildDateRange($form, 'event', 1, '_start_date_low', '_end_date_high', ts('From'), FALSE);
@@ -609,44 +612,44 @@ public static function buildSearchForm(&$form) {
$form->addElement('hidden', 'event_date_range_error');
$form->addElement('hidden', 'participant_date_range_error');
- $form->addFormRule(array('CRM_Event_BAO_Query', 'formRule'), $form);
+ $form->addFormRule(['CRM_Event_BAO_Query', 'formRule'], $form);
- $form->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', array(1 => '%1')));
+ $form->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', [1 => '%1']));
$form->addSelect('participant_status_id',
- array(
+ [
'entity' => 'participant',
'label' => ts('Participant Status'),
'multiple' => 'multiple',
'option_url' => NULL,
'placeholder' => ts('- any -'),
- )
+ ]
);
$form->addSelect('participant_role_id',
- array(
+ [
'entity' => 'participant',
'label' => ts('Participant Role'),
'multiple' => 'multiple',
'option_url' => NULL,
'placeholder' => ts('- any -'),
- )
+ ]
);
$form->addYesNo('participant_test', ts('Participant is a Test?'), TRUE);
$form->addYesNo('participant_is_pay_later', ts('Participant is Pay Later?'), TRUE);
- $form->addElement('text', 'participant_fee_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
- $form->addElement('text', 'participant_fee_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
+ $form->addElement('text', 'participant_fee_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
+ $form->addElement('text', 'participant_fee_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('participant_fee_amount_low', ts('Please enter a valid money value.'), 'money');
$form->addRule('participant_fee_amount_high', ts('Please enter a valid money value.'), 'money');
- self::addCustomFormFields($form, array('Participant', 'Event'));
+ self::addCustomFormFields($form, ['Participant', 'Event']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'participant_campaign_id');
$form->assign('validCiviEvent', TRUE);
- $form->setDefaults(array('participant_test' => 0));
+ $form->setDefaults(['participant_test' => 0]);
}
/**
@@ -655,7 +658,7 @@ public static function buildSearchForm(&$form) {
public static function tableNames(&$tables) {
//add participant table
if (!empty($tables['civicrm_event'])) {
- $tables = array_merge(array('civicrm_participant' => 1), $tables);
+ $tables = array_merge(['civicrm_participant' => 1], $tables);
}
}
@@ -671,7 +674,7 @@ public static function tableNames(&$tables) {
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
if ((empty($fields['event_start_date_low']) || empty($fields['event_end_date_high'])) && (empty($fields['participant_register_date_low']) || empty($fields['participant_register_date_high']))) {
return TRUE;
diff --git a/CRM/Event/Badge.php b/CRM/Event/Badge.php
index 5791e72e392e..953c61b5fdb8 100644
--- a/CRM/Event/Badge.php
+++ b/CRM/Event/Badge.php
@@ -1,7 +1,7 @@
style = array(
+ $this->style = [
'width' => 0.1,
'cap' => 'round',
'join' => 'round',
'dash' => '2,2',
- 'color' => array(0, 0, 200),
- );
+ 'color' => [0, 0, 200],
+ ];
$this->format = '5160';
$this->imgExtension = 'png';
$this->imgRes = 300;
@@ -88,7 +89,7 @@ public function run(&$participants) {
$this->event = self::retrieveEvent($eventID);
//call function to create labels
self::createLabels($participants);
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
@@ -123,9 +124,9 @@ public function getImageFileName($eventID, $img = FALSE) {
// CRM-13235 - leverage the Smarty path to get all templates directories
$template = CRM_Core_Smarty::singleton();
if (isset($template->template_dir) && $template->template_dir) {
- $dirs = is_array($template->template_dir) ? $template->template_dir : array($template->template_dir);
+ $dirs = is_array($template->template_dir) ? $template->template_dir : [$template->template_dir];
foreach ($dirs as $dir) {
- foreach (array("$dir/$path/$eventID/$img", "$dir/$path/$img") as $imgFile) {
+ foreach (["$dir/$path/$eventID/$img", "$dir/$path/$img"] as $imgFile) {
if (file_exists($imgFile)) {
return $imgFile;
}
@@ -147,15 +148,15 @@ public function printBackground($img = FALSE) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
if ($this->debug) {
- $this->pdf->Rect($x, $y, $this->pdf->width, $this->pdf->height, 'D', array(
- 'all' => array(
- 'width' => 1,
- 'cap' => 'round',
- 'join' => 'round',
- 'dash' => '2,10',
- 'color' => array(255, 0, 0),
- ),
- ));
+ $this->pdf->Rect($x, $y, $this->pdf->width, $this->pdf->height, 'D', [
+ 'all' => [
+ 'width' => 1,
+ 'cap' => 'round',
+ 'join' => 'round',
+ 'dash' => '2,10',
+ 'color' => [255, 0, 0],
+ ],
+ ]);
}
$img = $this->getImageFileName($this->event->id, $img);
if ($img) {
diff --git a/CRM/Event/Badge/Logo.php b/CRM/Event/Badge/Logo.php
index b6ca8b1bf216..4ac357ec2521 100644
--- a/CRM/Event/Badge/Logo.php
+++ b/CRM/Event/Badge/Logo.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Badge_Logo
*/
class CRM_Event_Badge_Logo extends CRM_Event_Badge {
+
/**
*/
public function __construct() {
@@ -13,7 +14,7 @@ public function __construct() {
$ph = 297;
$h = 50;
$w = 75;
- $this->format = array(
+ $this->format = [
'name' => 'Sigel 3C',
'paper-size' => 'A4',
'metric' => 'mm',
@@ -26,7 +27,7 @@ public function __construct() {
'width' => $w,
'height' => $h,
'font-size' => 12,
- );
+ ];
$this->lMarginLogo = 20;
$this->tMarginName = 20;
// $this->setDebug ();
@@ -39,13 +40,13 @@ public function generateLabel($participant) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
$this->printBackground(TRUE);
- $this->pdf->SetLineStyle(array(
- 'width' => 0.1,
- 'cap' => 'round',
- 'join' => 'round',
- 'dash' => '2,2',
- 'color' => array(0, 0, 200),
- ));
+ $this->pdf->SetLineStyle([
+ 'width' => 0.1,
+ 'cap' => 'round',
+ 'join' => 'round',
+ 'dash' => '2,2',
+ 'color' => [0, 0, 200],
+ ]);
$this->pdf->SetFontSize(8);
$this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y);
diff --git a/CRM/Event/Badge/Logo5395.php b/CRM/Event/Badge/Logo5395.php
index 411dfc74c59e..2343909174f5 100644
--- a/CRM/Event/Badge/Logo5395.php
+++ b/CRM/Event/Badge/Logo5395.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Badge_Logo5395
*/
class CRM_Event_Badge_Logo5395 extends CRM_Event_Badge {
+
/**
*/
public function __construct() {
@@ -13,7 +14,7 @@ public function __construct() {
$ph = 297;
$h = 59.2;
$w = 85.7;
- $this->format = array(
+ $this->format = [
'name' => 'Avery 5395',
'paper-size' => 'A4',
'metric' => 'mm',
@@ -26,7 +27,7 @@ public function __construct() {
'width' => $w,
'height' => $h,
'font-size' => 12,
- );
+ ];
$this->lMarginLogo = 20;
$this->tMarginName = 20;
// $this->setDebug ();
@@ -39,13 +40,13 @@ public function generateLabel($participant) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
$this->printBackground(TRUE);
- $this->pdf->SetLineStyle(array(
- 'width' => 0.1,
- 'cap' => 'round',
- 'join' => 'round',
- 'dash' => '2,2',
- 'color' => array(0, 0, 200),
- ));
+ $this->pdf->SetLineStyle([
+ 'width' => 0.1,
+ 'cap' => 'round',
+ 'join' => 'round',
+ 'dash' => '2,2',
+ 'color' => [0, 0, 200],
+ ]);
$this->pdf->SetFontSize(9);
$this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y);
diff --git a/CRM/Event/Badge/NameTent.php b/CRM/Event/Badge/NameTent.php
index ee38f5848a30..f2d4990bc3ed 100644
--- a/CRM/Event/Badge/NameTent.php
+++ b/CRM/Event/Badge/NameTent.php
@@ -1,9 +1,9 @@
tMargin = 0;
$w = $pw - 2 * $this->lMargin;
$h = $ph - 2 * $this->tMargin;
- $this->format = array(
+ $this->format = [
'name' => 'A4 horiz',
'paper-size' => 'A4',
'metric' => 'mm',
@@ -62,7 +63,7 @@ public function __construct() {
'width' => $w,
'height' => $h,
'font-size' => 36,
- );
+ ];
// $this->setDebug ();
}
diff --git a/CRM/Event/Badge/Simple.php b/CRM/Event/Badge/Simple.php
index 8a5825b1a246..a9fcb36ff573 100644
--- a/CRM/Event/Badge/Simple.php
+++ b/CRM/Event/Badge/Simple.php
@@ -1,9 +1,9 @@
$event_in_cart */
- public $events_in_carts = array();
+ /**
+ * event_in_cart_id => $event_in_cart
+ * @var array
+ */
+ public $events_in_carts = [];
/**
* @param array $params
@@ -32,10 +35,10 @@ public function add_event($event_id) {
return $event_in_cart;
}
- $params = array(
+ $params = [
'event_id' => $event_id,
'event_cart_id' => $this->id,
- );
+ ];
$event_in_cart = CRM_Event_Cart_BAO_EventInCart::create($params);
$event_in_cart->load_associations($this);
$this->events_in_carts[$event_in_cart->event_id] = $event_in_cart;
@@ -81,7 +84,7 @@ public static function create($params) {
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_by_id($id) {
- return self::find_by_params(array('id' => $id));
+ return self::find_by_params(['id' => $id]);
}
/**
@@ -127,12 +130,12 @@ public static function find_or_create_for_current_session() {
}
if ($cart === FALSE) {
if (is_null($userID)) {
- $cart = self::create(array());
+ $cart = self::create([]);
}
else {
$cart = self::find_uncompleted_by_user_id($userID);
if ($cart === FALSE) {
- $cart = self::create(array('user_id' => $userID));
+ $cart = self::create(['user_id' => $userID]);
}
}
$session->set('event_cart_id', $cart->id);
@@ -146,7 +149,7 @@ public static function find_or_create_for_current_session() {
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_uncompleted_by_id($id) {
- return self::find_by_params(array('id' => $id, 'completed' => 0));
+ return self::find_by_params(['id' => $id, 'completed' => 0]);
}
/**
@@ -155,7 +158,7 @@ public static function find_uncompleted_by_id($id) {
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_uncompleted_by_user_id($user_id) {
- return self::find_by_params(array('user_id' => $user_id, 'completed' => 0));
+ return self::find_by_params(['user_id' => $user_id, 'completed' => 0]);
}
/**
@@ -163,7 +166,7 @@ public static function find_uncompleted_by_user_id($user_id) {
*/
public function get_main_events_in_carts() {
//return CRM_Event_Cart_BAO_EventInCart::find_all_by_params( array('main_conference_event_id'
- $all = array();
+ $all = [];
foreach ($this->events_in_carts as $event_in_cart) {
if (!$event_in_cart->is_child_event()) {
$all[] = $event_in_cart;
@@ -178,7 +181,7 @@ public function get_main_events_in_carts() {
* @return array
*/
public function get_events_in_carts_by_main_event_id($main_conference_event_id) {
- $all = array();
+ $all = [];
if (!$main_conference_event_id) {
return $all;
}
@@ -215,7 +218,7 @@ public static function compare_event_dates($event_in_cart_1, $event_in_cart_2) {
* @return array
*/
public function get_subparticipants($main_participant) {
- $subparticipants = array();
+ $subparticipants = [];
foreach ($this->events_in_carts as $event_in_cart) {
if ($event_in_cart->is_child_event($main_participant->event_id)) {
foreach ($event_in_cart->participants as $participant) {
@@ -256,7 +259,7 @@ public function &get_event_in_cart_by_id($event_in_cart_id) {
* @return array
*/
public function get_main_event_participants() {
- $participants = array();
+ $participants = [];
foreach ($this->get_main_events_in_carts() as $event_in_cart) {
$participants = array_merge($participants, $event_in_cart->participants);
}
@@ -321,21 +324,20 @@ public function get_participant_index_from_id($participant_id) {
public static function retrieve(&$params, &$values) {
$cart = self::find_by_params($params);
if ($cart === FALSE) {
- CRM_Core_Error::fatal(ts('Could not find cart matching %1', array(1 => var_export($params, TRUE))));
+ CRM_Core_Error::fatal(ts('Could not find cart matching %1', [1 => var_export($params, TRUE)]));
}
CRM_Core_DAO::storeValues($cart, $values);
return $values;
}
-
/**
* @param int $from_cart_id
*/
public function adopt_participants($from_cart_id) {
- $params = array(
- 1 => array($this->id, 'Integer'),
- 2 => array($from_cart_id, 'Integer'),
- );
+ $params = [
+ 1 => [$this->id, 'Integer'],
+ 2 => [$from_cart_id, 'Integer'],
+ ];
$sql = "UPDATE civicrm_participant SET cart_id='%1' WHERE cart_id='%2'";
CRM_Core_DAO::executeQuery($sql, $params);
diff --git a/CRM/Event/Cart/BAO/Conference.php b/CRM/Event/Cart/BAO/Conference.php
index d332cfe70633..fd2c3f49dfba 100644
--- a/CRM/Event/Cart/BAO/Conference.php
+++ b/CRM/Event/Cart/BAO/Conference.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_BAO_Conference
*/
class CRM_Event_Cart_BAO_Conference {
+
/**
* XXX assumes we don't allow a contact to register for the same conference more than once
* XXX flattens the object tree for convenient templating
@@ -28,9 +29,9 @@ public static function get_participant_sessions($main_event_participant_id) {
slot.weight,
sub_event.start_date
EOS;
- $sql_args = array(1 => array($main_event_participant_id, 'Integer'));
+ $sql_args = [1 => [$main_event_participant_id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($sql, $sql_args);
- $smarty_sessions = array();
+ $smarty_sessions = [];
while ($dao->fetch()) {
$smarty_sessions[] = get_object_vars($dao);
}
diff --git a/CRM/Event/Cart/BAO/EventInCart.php b/CRM/Event/Cart/BAO/EventInCart.php
index 457b12dcac28..7dd79ec72523 100644
--- a/CRM/Event/Cart/BAO/EventInCart.php
+++ b/CRM/Event/Cart/BAO/EventInCart.php
@@ -8,7 +8,7 @@ class CRM_Event_Cart_BAO_EventInCart extends CRM_Event_Cart_DAO_EventInCart impl
public $event;
public $event_cart;
public $location = NULL;
- public $participants = array();
+ public $participants = [];
/**
* Class constructor.
@@ -55,10 +55,10 @@ public static function create(&$params) {
*/
public function delete($useWhere = FALSE) {
$this->load_associations();
- $contacts_to_delete = array();
+ $contacts_to_delete = [];
foreach ($this->participants as $participant) {
- $defaults = array();
- $params = array('id' => $participant->contact_id);
+ $defaults = [];
+ $params = ['id' => $participant->contact_id];
$temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
if ($temporary_contact->is_deleted) {
@@ -78,7 +78,7 @@ public function delete($useWhere = FALSE) {
* @return array
*/
public static function find_all_by_event_cart_id($event_cart_id) {
- return self::find_all_by_params(array('event_cart_id' => $event_cart_id));
+ return self::find_all_by_params(['event_cart_id' => $event_cart_id]);
}
/**
@@ -89,7 +89,7 @@ public static function find_all_by_event_cart_id($event_cart_id) {
public static function find_all_by_params($params) {
$event_in_cart = new CRM_Event_Cart_BAO_EventInCart();
$event_in_cart->copyValues($params);
- $result = array();
+ $result = [];
if ($event_in_cart->find()) {
while ($event_in_cart->fetch()) {
$result[$event_in_cart->event_id] = clone($event_in_cart);
@@ -104,7 +104,7 @@ public static function find_all_by_params($params) {
* @return bool|CRM_Event_Cart_BAO_EventInCart
*/
public static function find_by_id($id) {
- return self::find_by_params(array('id' => $id));
+ return self::find_by_params(['id' => $id]);
}
/**
@@ -127,7 +127,7 @@ public static function find_by_params($params) {
* @param int $contact_id
*/
public function remove_participant_by_contact_id($contact_id) {
- $to_remove = array();
+ $to_remove = [];
foreach ($this->participants as $participant) {
if ($participant->contact_id == $contact_id) {
$to_remove[$participant->id] = 1;
@@ -171,8 +171,8 @@ public function load_associations($event_cart = NULL) {
return;
}
$this->assocations_loaded = TRUE;
- $params = array('id' => $this->event_id);
- $defaults = array();
+ $params = ['id' => $this->event_id];
+ $defaults = [];
$this->event = CRM_Event_BAO_Event::retrieve($params, $defaults);
if ($event_cart != NULL) {
@@ -192,7 +192,7 @@ public function load_associations($event_cart = NULL) {
public function load_location() {
if ($this->location == NULL) {
- $location_params = array('entity_id' => $this->event_id, 'entity_table' => 'civicrm_event');
+ $location_params = ['entity_id' => $this->event_id, 'entity_table' => 'civicrm_event'];
$this->location = CRM_Core_BAO_Location::getValues($location_params, TRUE);
}
}
@@ -201,7 +201,7 @@ public function load_location() {
* @return array
*/
public function not_waiting_participants() {
- $result = array();
+ $result = [];
foreach ($this->participants as $participant) {
if (!$participant->must_wait) {
$result[] = $participant;
@@ -224,14 +224,13 @@ public function num_waiting_participants() {
return count($this->waiting_participants());
}
-
/**
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset) {
- return array_key_exists(array_merge($this->fields(), array('main_conference_event_id')), $offset);
+ return array_key_exists(array_merge($this->fields(), ['main_conference_event_id']), $offset);
}
/**
@@ -270,7 +269,7 @@ public function offsetUnset($offset) {
* @return array
*/
public function waiting_participants() {
- $result = array();
+ $result = [];
foreach ($this->participants as $participant) {
if ($participant->must_wait) {
$result[] = $participant;
@@ -290,18 +289,18 @@ public static function get_registration_link($event_id) {
$event_in_cart = $cart->get_event_in_cart_by_event_id($event_id);
if ($event_in_cart) {
- return array(
- 'label' => "Remove from Cart",
+ return [
+ 'label' => ts("Remove from Cart"),
'path' => 'civicrm/event/remove_from_cart',
'query' => "reset=1&id={$event_id}",
- );
+ ];
}
else {
- return array(
- 'label' => "Add to Cart",
+ return [
+ 'label' => ts("Add to Cart"),
'path' => 'civicrm/event/add_to_cart',
'query' => "reset=1&id={$event_id}",
- );
+ ];
}
}
diff --git a/CRM/Event/Cart/BAO/MerParticipant.php b/CRM/Event/Cart/BAO/MerParticipant.php
index e0385666d9b6..9717dea04b53 100644
--- a/CRM/Event/Cart/BAO/MerParticipant.php
+++ b/CRM/Event/Cart/BAO/MerParticipant.php
@@ -1,9 +1,9 @@
CRM_Utils_Array::value('id', $params),
'role_id' => self::get_attendee_role_id(),
'status_id' => self::get_pending_in_cart_status_id(),
@@ -63,7 +63,7 @@ public static function create(&$params) {
//'registered_by_id' =>
//'discount_amount' =>
//'fee_level' => $params['fee_level'],
- );
+ ];
$participant = CRM_Event_BAO_Participant::create($participantParams);
if (is_a($participant, 'CRM_Core_Error')) {
@@ -102,7 +102,7 @@ public static function find_all_by_cart_id($event_cart_id) {
if ($event_cart_id == NULL) {
return NULL;
}
- return self::find_all_by_params(array('cart_id' => $event_cart_id));
+ return self::find_all_by_params(['cart_id' => $event_cart_id]);
}
/**
@@ -115,7 +115,7 @@ public static function find_all_by_event_and_cart_id($event_id, $event_cart_id)
if ($event_cart_id == NULL) {
return NULL;
}
- return self::find_all_by_params(array('event_id' => $event_id, 'cart_id' => $event_cart_id));
+ return self::find_all_by_params(['event_id' => $event_id, 'cart_id' => $event_cart_id]);
}
/**
@@ -126,7 +126,7 @@ public static function find_all_by_event_and_cart_id($event_id, $event_cart_id)
public static function find_all_by_params($params) {
$participant = new CRM_Event_BAO_Participant();
$participant->copyValues($params);
- $result = array();
+ $result = [];
if ($participant->find()) {
while ($participant->fetch()) {
$result[] = new CRM_Event_Cart_BAO_MerParticipant(clone($participant));
@@ -141,7 +141,7 @@ public static function find_all_by_params($params) {
* @return mixed
*/
public static function get_by_id($id) {
- $results = self::find_all_by_params(array('id' => $id));
+ $results = self::find_all_by_params(['id' => $id]);
return array_pop($results);
}
diff --git a/CRM/Event/Cart/Controller/Checkout.php b/CRM/Event/Cart/Controller/Checkout.php
index 84ed049823b6..a00044bdda63 100644
--- a/CRM/Event/Cart/Controller/Checkout.php
+++ b/CRM/Event/Cart/Controller/Checkout.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Controller_Checkout
*/
class CRM_Event_Cart_Controller_Checkout extends CRM_Core_Controller {
+
/**
* @param null $title
* @param bool|int $action
diff --git a/CRM/Event/Cart/DAO/Cart.php b/CRM/Event/Cart/DAO/Cart.php
index 568bb3f0e1c0..893b1ba406dd 100644
--- a/CRM/Event/Cart/DAO/Cart.php
+++ b/CRM/Event/Cart/DAO/Cart.php
@@ -1,165 +1,155 @@
__table = 'civicrm_event_carts';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'user_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'user_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'cart_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'cart_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Cart ID') ,
- 'description' => 'Cart Id',
- 'required' => true,
+ 'title' => ts('Cart ID'),
+ 'description' => ts('Cart Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_event_carts.id',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
- ) ,
- 'user_id' => array(
+ ],
+ 'user_id' => [
'name' => 'user_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Created By') ,
- 'description' => 'FK to civicrm_contact who created this cart',
+ 'title' => ts('Created By'),
+ 'description' => ts('FK to civicrm_contact who created this cart'),
+ 'where' => 'civicrm_event_carts.user_id',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'completed' => array(
+ ],
+ 'completed' => [
'name' => 'completed',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Complete?') ,
+ 'title' => ts('Complete?'),
+ 'where' => 'civicrm_event_carts.completed',
+ 'default' => '0',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -167,10 +157,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event_carts', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -178,15 +169,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event_carts', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/Cart/DAO/EventInCart.php b/CRM/Event/Cart/DAO/EventInCart.php
index 3178c52bdee4..41654c3d24f5 100644
--- a/CRM/Event/Cart/DAO/EventInCart.php
+++ b/CRM/Event/Cart/DAO/EventInCart.php
@@ -1,169 +1,159 @@
__table = 'civicrm_events_in_carts';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_id', 'civicrm_event', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_cart_id', 'civicrm_event_carts', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'event_id', 'civicrm_event', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'event_cart_id', 'civicrm_event_carts', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'event_in_cart_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'event_in_cart_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event In Cart') ,
- 'description' => 'Event In Cart Id',
- 'required' => true,
+ 'title' => ts('Event In Cart'),
+ 'description' => ts('Event In Cart Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_events_in_carts.id',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
- ) ,
- 'event_id' => array(
+ ],
+ 'event_id' => [
'name' => 'event_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event') ,
- 'description' => 'FK to Event ID',
+ 'title' => ts('Event'),
+ 'description' => ts('FK to Event ID'),
+ 'where' => 'civicrm_events_in_carts.event_id',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Event',
- ) ,
- 'event_cart_id' => array(
+ ],
+ 'event_cart_id' => [
'name' => 'event_cart_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event In Cart') ,
- 'description' => 'FK to Event Cart ID',
+ 'title' => ts('Event In Cart'),
+ 'description' => ts('FK to Event Cart ID'),
+ 'where' => 'civicrm_events_in_carts.event_cart_id',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
'FKClassName' => 'CRM_Event_Cart_DAO_Cart',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -171,10 +161,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'events_in_carts', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'events_in_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -182,15 +173,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'events_in_carts', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'events_in_carts', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/Cart/Form/Cart.php b/CRM/Event/Cart/Form/Cart.php
index 3f4f23a31930..6e16ac7a31a6 100644
--- a/CRM/Event/Cart/Form/Cart.php
+++ b/CRM/Event/Cart/Form/Cart.php
@@ -21,13 +21,13 @@ public function preProcess() {
$this->assignBillingType();
- $event_titles = array();
+ $event_titles = [];
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$event_titles[] = $event_in_cart->event->title;
}
- $this->description = ts("Online Registration for %1", array(1 => implode(", ", $event_titles)));
+ $this->description = ts("Online Registration for %1", [1 => implode(", ", $event_titles)]);
if (!isset($this->discounts)) {
- $this->discounts = array();
+ $this->discounts = [];
}
}
@@ -47,11 +47,11 @@ public function stub_out_and_inherit() {
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
if (empty($event_in_cart->participants)) {
- $participant_params = array(
+ $participant_params = [
'cart_id' => $this->cart->id,
'event_id' => $event_in_cart->event_id,
'contact_id' => self::find_or_create_contact($this->getContactID()),
- );
+ ];
$participant = CRM_Event_Cart_BAO_MerParticipant::create($participant_params);
$participant->save();
$event_in_cart->add_participant($participant);
@@ -128,7 +128,7 @@ public function getContactID() {
* @return mixed|null
*/
public static function find_contact($fields) {
- return CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE);
+ return CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
}
/**
@@ -137,22 +137,22 @@ public static function find_contact($fields) {
*
* @return int|mixed|null
*/
- public static function find_or_create_contact($registeringContactID = NULL, $fields = array()) {
+ public static function find_or_create_contact($registeringContactID = NULL, $fields = []) {
$contact_id = self::find_contact($fields);
if ($contact_id) {
return $contact_id;
}
- $contact_params = array(
+ $contact_params = [
'email-Primary' => CRM_Utils_Array::value('email', $fields, NULL),
'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL),
'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL),
'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, TRUE),
- );
- $no_fields = array();
+ ];
+ $no_fields = [];
$contact_id = CRM_Contact_BAO_Contact::createProfileContact($contact_params, $no_fields, NULL);
if (!$contact_id) {
- CRM_Core_Error::displaySessionError("Could not create or match a contact with that email address. Please contact the webmaster.");
+ CRM_Core_Session::setStatus(ts("Could not create or match a contact with that email address. Please contact the webmaster."), '', 'error');
}
return $contact_id;
}
diff --git a/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php b/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php
index f1299e3553cc..57e28b704550 100644
--- a/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php
+++ b/CRM/Event/Cart/Form/Checkout/ConferenceEvents.php
@@ -5,13 +5,13 @@
*/
class CRM_Event_Cart_Form_Checkout_ConferenceEvents extends CRM_Event_Cart_Form_Cart {
public $conference_event = NULL;
- public $events_by_slot = array();
+ public $events_by_slot = [];
public $main_participant = NULL;
public $contact_id = NULL;
public function preProcess() {
parent::preProcess();
- $matches = array();
+ $matches = [];
preg_match("/.*_(\d+)_(\d+)/", $this->getAttribute('name'), $matches);
$event_id = $matches[1];
$participant_id = $matches[2];
@@ -43,7 +43,7 @@ public function preProcess() {
$events->query($query);
while ($events->fetch()) {
if (!array_key_exists($events->slot_label, $this->events_by_slot)) {
- $this->events_by_slot[$events->slot_label] = array();
+ $this->events_by_slot[$events->slot_label] = [];
}
$this->events_by_slot[$events->slot_label][] = clone($events);
}
@@ -55,13 +55,13 @@ public function buildQuickForm() {
//jquery_ui_add('ui.dialog');
$slot_index = -1;
- $slot_fields = array();
- $session_options = array();
- $defaults = array();
+ $slot_fields = [];
+ $session_options = [];
+ $defaults = [];
$previous_event_choices = $this->cart->get_subparticipants($this->main_participant);
foreach ($this->events_by_slot as $slot_name => $events) {
$slot_index++;
- $slot_buttons = array();
+ $slot_buttons = [];
$group_name = "slot_$slot_index";
foreach ($events as $event) {
$seats_available = $this->checkEventCapacity($event->id);
@@ -70,12 +70,12 @@ public function buildQuickForm() {
$slot_buttons[] = $radio;
$event_description = ($event_is_full ? $event->event_full_text . "
" : '') . $event->description;
- $session_options[$radio->getAttribute('id')] = array(
+ $session_options[$radio->getAttribute('id')] = [
'session_title' => $event->title,
'session_description' => $event_description,
'session_full' => $event_is_full,
'event_id' => $event->id,
- );
+ ];
foreach ($previous_event_choices as $choice) {
if ($choice->event_id == $event->id) {
$defaults[$group_name] = $event->id;
@@ -95,18 +95,18 @@ public function buildQuickForm() {
$this->assign('slot_fields', $slot_fields);
$this->assign('session_options', json_encode($session_options));
- $buttons = array();
- $buttons[] = array(
+ $buttons = [];
+ $buttons[] = [
'name' => ts('Go Back'),
'spacing' => '  ',
'type' => 'back',
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'isDefault' => TRUE,
'name' => ts('Continue'),
'spacing' => ' ',
'type' => 'next',
- );
+ ];
$this->addButtons($buttons);
}
@@ -134,7 +134,7 @@ public function postProcess() {
}
$event_in_cart = $this->cart->add_event($session_event_id);
- $values = array();
+ $values = [];
CRM_Core_DAO::storeValues($this->main_participant, $values);
$values['id'] = NULL;
$values['event_id'] = $event_in_cart->event_id;
diff --git a/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php b/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php
index c47306a84049..45767901189b 100644
--- a/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php
+++ b/CRM/Event/Cart/Form/Checkout/ParticipantsAndPrices.php
@@ -24,7 +24,7 @@ public function preProcess() {
* Build quick form.
*/
public function buildQuickForm() {
- $this->price_fields_for_event = array();
+ $this->price_fields_for_event = [];
foreach ($this->cart->get_main_event_participants() as $participant) {
$form = new CRM_Event_Cart_Form_MerParticipant($participant);
$form->appendQuickForm($this);
@@ -37,20 +37,20 @@ public function buildQuickForm() {
$this->assign('events_in_carts', $this->cart->get_main_events_in_carts());
$this->assign('price_fields_for_event', $this->price_fields_for_event);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
if ($this->cid) {
- $params = array('id' => $this->cid);
+ $params = ['id' => $this->cid];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
- $contact_values = array();
+ $contact_values = [];
CRM_Core_DAO::storeValues($contact, $contact_values);
$this->assign('contact', $contact_values);
}
@@ -81,7 +81,7 @@ public static function primary_email_from_contact($contact) {
* @return array
*/
public function build_price_options($event) {
- $price_fields_for_event = array();
+ $price_fields_for_event = [];
$base_field_name = "event_{$event->id}_amount";
$price_set_id = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $event->id);
//CRM-14492 display admin fields only if user is admin
@@ -128,7 +128,7 @@ public function validate() {
$priceField->price_set_id = $price_set_id;
$priceField->find();
- $check = array();
+ $check = [];
while ($priceField->fetch()) {
if (!empty($fields["event_{$event_in_cart->event_id}_price_{$priceField->id}"])) {
@@ -141,7 +141,7 @@ public function validate() {
$this->_errors['_qf_default'] = ts("Select at least one option from Price Levels.");
}
- $lineItem = array();
+ $lineItem = [];
if (is_array($this->_values['fee']['fields'])) {
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee']['fields'], $fields, $lineItem);
//XXX total...
@@ -151,6 +151,11 @@ public function validate() {
}
}
+ // Validate if participant is already registered
+ if ($event_in_cart->event->allow_same_participant_emails) {
+ continue;
+ }
+
foreach ($event_in_cart->participants as $mer_participant) {
$participant_fields = $fields['event'][$event_in_cart->event_id]['participant'][$mer_participant->id];
//TODO what to do when profile responses differ for the same contact?
@@ -165,11 +170,11 @@ public function validate() {
while ($participant->fetch()) {
if (array_key_exists($participant->status_id, $statusTypes)) {
$form = $mer_participant->get_form();
- $this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", array(
- 1 => $participant_fields['email'],
- 2 => $event_in_cart->event->title,
- 3 => $event_in_cart->event->start_date,
- ));
+ $this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", [
+ 1 => $participant_fields['email'],
+ 2 => $event_in_cart->event->title,
+ 3 => $event_in_cart->event->start_date,
+ ]);
}
}
}
@@ -186,7 +191,7 @@ public function validate() {
public function setDefaultValues() {
$this->loadCart();
- $defaults = array();
+ $defaults = [];
foreach ($this->cart->get_main_event_participants() as $participant) {
$form = $participant->get_form();
if (empty($participant->email)
@@ -194,8 +199,8 @@ public function setDefaultValues() {
&& ($participant->get_participant_index() == 1)
&& ($this->cid != 0)
) {
- $defaults = array();
- $params = array('id' => $this->cid);
+ $defaults = [];
+ $params = ['id' => $this->cid];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
$participant->contact_id = $this->cid;
$participant->save();
@@ -246,7 +251,7 @@ public function postProcess() {
return;
}
// XXX de facto primary key
- $email_to_contact_id = array();
+ $email_to_contact_id = [];
foreach ($this->_submitValues['event'] as $event_id => $participants) {
foreach ($participants['participant'] as $participant_id => $fields) {
if (array_key_exists($fields['email'], $email_to_contact_id)) {
@@ -259,8 +264,8 @@ public function postProcess() {
$participant = $this->cart->get_event_in_cart_by_event_id($event_id)->get_participant_by_id($participant_id);
if ($participant->contact_id && $contact_id != $participant->contact_id) {
- $defaults = array();
- $params = array('id' => $participant->contact_id);
+ $defaults = [];
+ $params = ['id' => $participant->contact_id];
$temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
foreach ($this->cart->get_subparticipants($participant) as $subparticipant) {
@@ -280,14 +285,14 @@ public function postProcess() {
}
//TODO security check that participant ids are already in this cart
- $participant_params = array(
+ $participant_params = [
'id' => $participant_id,
'cart_id' => $this->cart->id,
'event_id' => $event_id,
'contact_id' => $contact_id,
//'registered_by_id' => $this->cart->user_id,
'email' => $fields['email'],
- );
+ ];
$participant = new CRM_Event_Cart_BAO_MerParticipant($participant_params);
$participant->save();
$this->cart->add_participant_to_cart($participant);
diff --git a/CRM/Event/Cart/Form/Checkout/Payment.php b/CRM/Event/Cart/Form/Checkout/Payment.php
index 59f843ad461e..143096e35258 100644
--- a/CRM/Event/Cart/Form/Checkout/Payment.php
+++ b/CRM/Event/Cart/Form/Checkout/Payment.php
@@ -8,7 +8,7 @@ class CRM_Event_Cart_Form_Checkout_Payment extends CRM_Event_Cart_Form_Cart {
public $financial_type_id;
public $description;
public $line_items;
- public $_fields = array();
+ public $_fields = [];
public $_paymentProcessor;
public $total;
public $sub_total;
@@ -31,7 +31,7 @@ public function registerParticipant($params, &$participant, $event) {
// handle register date CRM-4320
$registerDate = date('YmdHis');
- $participantParams = array(
+ $participantParams = [
'id' => $participant->id,
'event_id' => $event->id,
'register_date' => $registerDate,
@@ -42,7 +42,7 @@ public function registerParticipant($params, &$participant, $event) {
//XXX why is this a ref to participant and not contact?:
//'registered_by_id' => $this->payer_contact_id,
'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
- );
+ ];
if ($participant->must_wait) {
$participant_status = 'On waitlist';
@@ -69,11 +69,11 @@ public function registerParticipant($params, &$participant, $event) {
if (self::is_administrator()) {
if (!empty($params['note'])) {
- $note_params = array(
+ $note_params = [
'participant_id' => $participant->id,
'contact_id' => self::getContactID(),
'note' => $params['note'],
- );
+ ];
CRM_Event_BAO_Participant::update_note($note_params);
}
}
@@ -82,49 +82,48 @@ public function registerParticipant($params, &$participant, $event) {
$participant->save();
if (!empty($params['contributionID'])) {
- $payment_params = array(
+ $payment_params = [
'participant_id' => $participant->id,
'contribution_id' => $params['contributionID'],
- );
- $ids = array();
- CRM_Event_BAO_ParticipantPayment::create($payment_params, $ids);
+ ];
+ CRM_Event_BAO_ParticipantPayment::create($payment_params);
}
$transaction->commit();
- $event_values = array();
+ $event_values = [];
CRM_Core_DAO::storeValues($event, $event_values);
- $location = array();
+ $location = [];
if (CRM_Utils_Array::value('is_show_location', $event_values) == 1) {
- $locationParams = array(
+ $locationParams = [
'entity_id' => $participant->event_id,
'entity_table' => 'civicrm_event',
- );
+ ];
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
CRM_Core_BAO_Address::fixAddress($location['address'][1]);
}
list($pre_id, $post_id) = CRM_Event_Cart_Form_MerParticipant::get_profile_groups($participant->event_id);
- $payer_values = array(
+ $payer_values = [
'email' => '',
'name' => '',
- );
+ ];
if ($this->payer_contact_id) {
$payer_contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
- $payer_values = array(
+ $payer_values = [
'email' => $payer_contact_details[1],
'name' => $payer_contact_details[0],
- );
+ ];
}
- $values = array(
- 'params' => array($participant->id => $participantParams),
+ $values = [
+ 'params' => [$participant->id => $participantParams],
'event' => $event_values,
'location' => $location,
'custom_pre_id' => $pre_id,
'custom_post_id' => $post_id,
'payer' => $payer_values,
- );
+ ];
CRM_Event_BAO_Event::sendMail($participant->contact_id, $values, $participant->id);
return $participant;
@@ -176,6 +175,10 @@ public function buildPaymentFields() {
);
$this->assign('pay_later_instructions', $this->pay_later_receipt);
}
+
+ // Event Cart does not support multiple payment processors
+ // so we cannot call $this->preProcessPaymentOptions();
+ CRM_Financial_Form_Payment::addCreditCardJs($this->_paymentProcessor['id']);
}
/**
@@ -183,7 +186,7 @@ public function buildPaymentFields() {
*/
public function buildQuickForm() {
- $this->line_items = array();
+ $this->line_items = [];
$this->sub_total = 0;
$this->_price_values = $this->getValuesForPage('ParticipantsAndPrices');
@@ -201,18 +204,18 @@ public function buildQuickForm() {
$this->assign('line_items', $this->line_items);
$this->assign('sub_total', $this->sub_total);
$this->assign('total', $this->total);
- $buttons = array();
- $buttons[] = array(
+ $buttons = [];
+ $buttons[] = [
'name' => ts('Go Back'),
'spacing' => '  ',
'type' => 'back',
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'isDefault' => TRUE,
'name' => ts('Complete Transaction'),
'spacing' => ' ',
'type' => 'next',
- );
+ ];
if ($this->total) {
$this->add('text', 'billing_contact_email', 'Billing Email', '', TRUE);
@@ -220,22 +223,22 @@ public function buildQuickForm() {
}
if (self::is_administrator()) {
$this->add('textarea', 'note', 'Note');
- $this->add('text', 'source', 'Source', array('size' => 80));
- $instruments = array();
+ $this->add('text', 'source', 'Source', ['size' => 80]);
+ $instruments = [];
CRM_Core_OptionGroup::getAssoc('payment_instrument', $instruments, TRUE);
- $options = array();
+ $options = [];
foreach ($instruments as $type) {
$options[] = $this->createElement('radio', NULL, '', $type['label'], $type['value']);
}
$this->addGroup($options, 'payment_type', ts("Alternative Payment Type"));
- $this->add('text', 'check_number', ts('Check No.'), array('size' => 20));
+ $this->add('text', 'check_number', ts('Check No.'), ['size' => 20]);
$this->addElement('checkbox', 'is_pending', ts('Create a pending registration'));
$this->assign('administrator', TRUE);
}
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Event_Cart_Form_Checkout_Payment', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Cart_Form_Checkout_Payment', 'formRule'], $this);
if ($this->payment_required) {
$this->buildPaymentFields();
@@ -253,7 +256,7 @@ public function process_event_line_item(&$event_in_cart, $class = NULL) {
$price_set_id = CRM_Price_BAO_PriceSet::getFor("civicrm_event", $event_in_cart->event_id);
$amount_level = NULL;
if ($price_set_id) {
- $event_price_values = array();
+ $event_price_values = [];
foreach ($this->_price_values as $key => $value) {
if (preg_match("/event_{$event_in_cart->event_id}_(price.*)/", $key, $matches)) {
$event_price_values[$matches[1]] = $value;
@@ -261,7 +264,7 @@ public function process_event_line_item(&$event_in_cart, $class = NULL) {
}
$price_sets = CRM_Price_BAO_PriceSet::getSetDetail($price_set_id, TRUE);
$price_set = $price_sets[$price_set_id];
- $price_set_amount = array();
+ $price_set_amount = [];
CRM_Price_BAO_PriceSet::processAmount($price_set['fields'], $event_price_values, $price_set_amount);
$discountCode = $this->_price_values['discountcode'];
if (!empty($discountCode)) {
@@ -300,21 +303,21 @@ public function process_event_line_item(&$event_in_cart, $class = NULL) {
public function add_line_item($event_in_cart, $class = NULL) {
$amount = 0;
$cost = 0;
- $not_waiting_participants = array();
+ $not_waiting_participants = [];
foreach ($event_in_cart->not_waiting_participants() as $participant) {
$amount += $participant->cost;
$cost = max($cost, $participant->cost);
- $not_waiting_participants[] = array(
+ $not_waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
- $waiting_participants = array();
+ $waiting_participants = [];
foreach ($event_in_cart->waiting_participants() as $participant) {
- $waiting_participants[] = array(
+ $waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
- $this->line_items[] = array(
+ $this->line_items[] = [
'amount' => $amount,
'cost' => $cost,
'event' => $event_in_cart->event,
@@ -323,21 +326,11 @@ public function add_line_item($event_in_cart, $class = NULL) {
'num_waiting_participants' => count($waiting_participants),
'waiting_participants' => $waiting_participants,
'class' => $class,
- );
+ ];
$this->sub_total += $amount;
}
- /**
- * Get default from address.
- *
- * @return mixed
- */
- public function getDefaultFrom() {
- $values = CRM_Core_OptionGroup::values('from_email_address');
- return $values[1];
- }
-
/**
* Send email receipt.
*
@@ -355,19 +348,19 @@ public function emailReceipt($events_in_cart, $params) {
$country->find();
$country->fetch();
foreach ($this->line_items as & $line_item) {
- $location_params = array('entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event');
+ $location_params = ['entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event'];
$line_item['location'] = CRM_Core_BAO_Location::getValues($location_params, TRUE);
CRM_Core_BAO_Address::fixAddress($line_item['location']['address'][1]);
}
- $send_template_params = array(
+ $send_template_params = [
'table' => 'civicrm_msg_template',
'contactId' => $this->payer_contact_id,
- 'from' => $this->getDefaultFrom(),
+ 'from' => current(CRM_Core_BAO_Domain::getNameAndEmail(TRUE, TRUE)),
'groupName' => 'msg_tpl_workflow_event',
'isTest' => FALSE,
'toEmail' => $contact_details[1],
'toName' => $contact_details[0],
- 'tplParams' => array(
+ 'tplParams' => [
'billing_name' => "{$params['billing_first_name']} {$params['billing_last_name']}",
'billing_city' => $params["billing_city-{$this->_bltID}"],
'billing_country' => $country->name,
@@ -387,11 +380,11 @@ public function emailReceipt($events_in_cart, $params) {
'transaction_date' => $params['trxn_date'],
'is_pay_later' => $this->is_pay_later,
'pay_later_receipt' => $this->pay_later_receipt,
- ),
+ ],
'valueName' => 'event_registration_receipt',
'PDFFilename' => ts('confirmation') . '.pdf',
- );
- $template_params_to_copy = array(
+ ];
+ $template_params_to_copy = [
'billing_name',
'billing_city',
'billing_country',
@@ -401,7 +394,7 @@ public function emailReceipt($events_in_cart, $params) {
'credit_card_exp_date',
'credit_card_type',
'credit_card_number',
- );
+ ];
foreach ($template_params_to_copy as $template_param_to_copy) {
$this->set($template_param_to_copy, $send_template_params['tplParams'][$template_param_to_copy]);
}
@@ -419,7 +412,7 @@ public function emailReceipt($events_in_cart, $params) {
* @return array|bool
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($self->payment_required && empty($self->_submitValues['is_pay_later'])) {
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
@@ -468,8 +461,8 @@ public function postProcess() {
$main_participants = $this->cart->get_main_event_participants();
foreach ($main_participants as $participant) {
- $defaults = array();
- $ids = array('contact_id' => $participant->contact_id);
+ $defaults = [];
+ $ids = ['contact_id' => $participant->contact_id];
$contact = CRM_Contact_BAO_Contact::retrieve($ids, $defaults);
$contact->is_deleted = 0;
$contact->save();
@@ -477,18 +470,18 @@ public function postProcess() {
$trxn_prefix = 'VR';
if (array_key_exists('billing_contact_email', $params)) {
- $this->payer_contact_id = self::find_or_create_contact($this->getContactID(), array(
+ $this->payer_contact_id = self::find_or_create_contact($this->getContactID(), [
'email' => $params['billing_contact_email'],
'first_name' => $params['billing_first_name'],
'last_name' => $params['billing_last_name'],
'is_deleted' => FALSE,
- ));
+ ]);
$ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$this->payer_contact_id,
'contact_type'
);
- $billing_fields = array(
+ $billing_fields = [
"billing_first_name" => 1,
"billing_middle_name" => 1,
"billing_last_name" => 1,
@@ -499,7 +492,7 @@ public function postProcess() {
"billing_country_id-{$this->_bltID}" => 1,
"address_name-{$this->_bltID}" => 1,
"email-{$this->_bltID}" => 1,
- );
+ ];
$params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
@@ -513,6 +506,8 @@ public function postProcess() {
$ctype,
TRUE
);
+
+ $params['contact_id'] = $this->payer_contact_id;
}
$params['now'] = date('YmdHis');
@@ -532,11 +527,11 @@ public function postProcess() {
$contribution_statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$params['payment_instrument_id'] = NULL;
if (!empty($params['is_pay_later'])) {
- $params['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name');
+ $params['payment_instrument_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Check');
$trxn_prefix = 'CK';
}
else {
- $params['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', 'Credit Card', 'name');
+ $params['payment_instrument_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Credit Card');
}
if ($this->is_pay_later && empty($params['payment_completed'])) {
$params['contribution_status_id'] = array_search('Pending', $contribution_statuses);
@@ -558,7 +553,7 @@ public function postProcess() {
// n.b. we need to process the subparticipants before main event
// participants so that session attendance can be included in the email
$main_participants = $this->cart->get_main_event_participants();
- $this->all_participants = array();
+ $this->all_participants = [];
foreach ($main_participants as $main_participant) {
$this->all_participants = array_merge($this->all_participants, $this->cart->get_subparticipants($main_participant));
}
@@ -625,11 +620,11 @@ public function make_payment(&$params) {
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/cart_checkout', "_qf_Payment_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE));
}
- $trxnDetails = array(
+ $trxnDetails = [
'trxn_id' => $result['trxn_id'],
'trxn_date' => $result['now'],
'currency' => CRM_Utils_Array::value('currencyID', $result),
- );
+ ];
return $trxnDetails;
}
@@ -658,7 +653,7 @@ public function record_contribution(&$mer_participant, &$params, $event) {
$payer = $params['participant_contact_id'];
}
- $contribParams = array(
+ $contribParams = [
'contact_id' => $payer,
'financial_type_id' => $params['financial_type_id'],
'receive_date' => $params['now'],
@@ -674,16 +669,13 @@ public function record_contribution(&$mer_participant, &$params, $event) {
'payment_instrument_id' => $params['payment_instrument_id'],
'check_number' => CRM_Utils_Array::value('check_number', $params),
'skipLineItem' => 1,
- );
+ ];
if (is_array($this->_paymentProcessor)) {
$contribParams['payment_processor'] = $this->_paymentProcessor['id'];
}
- $contribution = &CRM_Contribute_BAO_Contribution::add($contribParams);
- if (is_a($contribution, 'CRM_Core_Error')) {
- CRM_Core_Error::fatal(ts("There was an error creating a contribution record for your event. Please report this error to the webmaster. Details: %1", array(1 => $contribution->getMessages($contribution))));
- }
+ $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
$mer_participant->contribution_id = $contribution->id;
$params['contributionID'] = $contribution->id;
@@ -694,9 +686,9 @@ public function record_contribution(&$mer_participant, &$params, $event) {
* Save data to session.
*/
public function saveDataToSession() {
- $session_line_items = array();
+ $session_line_items = [];
foreach ($this->line_items as $line_item) {
- $session_line_item = array();
+ $session_line_item = [];
$session_line_item['amount'] = $line_item['amount'];
$session_line_item['cost'] = $line_item['cost'];
$session_line_item['event_id'] = $line_item['event']->id;
@@ -727,7 +719,7 @@ public function setDefaultValues() {
$defaults["billing_country_id-{$this->_bltID}"] = $default_country->id;
if (self::getContactID() && !self::is_administrator()) {
- $params = array('id' => self::getContactID());
+ $params = ['id' => self::getContactID()];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
foreach ($contact->email as $email) {
@@ -775,7 +767,7 @@ public function setDefaultValues() {
*/
protected function apply_discount($discountCode, &$price_set_amount, &$cost, $event_id) {
//need better way to determine if cividiscount installed
- $autoDiscount = array();
+ $autoDiscount = [];
$sql = "select is_active from civicrm_extension where name like 'CiviDiscount%'";
$dao = CRM_Core_DAO::executeQuery($sql, '');
while ($dao->fetch()) {
diff --git a/CRM/Event/Cart/Form/Checkout/ThankYou.php b/CRM/Event/Cart/Form/Checkout/ThankYou.php
index 0b1b8d10b42c..991e3724e99e 100644
--- a/CRM/Event/Cart/Form/Checkout/ThankYou.php
+++ b/CRM/Event/Cart/Form/Checkout/ThankYou.php
@@ -15,17 +15,17 @@ public function buildLineItems() {
foreach ($line_items as $line_item) {
$event_in_cart = $this->cart->get_event_in_cart_by_event_id($line_item['event_id']);
- $not_waiting_participants = array();
+ $not_waiting_participants = [];
foreach ($event_in_cart->not_waiting_participants() as $participant) {
- $not_waiting_participants[] = array(
+ $not_waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
- $waiting_participants = array();
+ $waiting_participants = [];
foreach ($event_in_cart->waiting_participants() as $participant) {
- $waiting_participants[] = array(
+ $waiting_participants[] = [
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
- );
+ ];
}
$line_item['event'] = $event_in_cart->event;
@@ -43,9 +43,9 @@ public function buildLineItems() {
}
public function buildQuickForm() {
- $defaults = array();
- $ids = array();
- $template_params_to_copy = array(
+ $defaults = [];
+ $ids = [];
+ $template_params_to_copy = [
'billing_name',
'billing_city',
'billing_country',
@@ -55,7 +55,7 @@ public function buildQuickForm() {
'credit_card_exp_date',
'credit_card_type',
'credit_card_number',
- );
+ ];
foreach ($template_params_to_copy as $template_param_to_copy) {
$this->assign($template_param_to_copy, $this->get($template_param_to_copy));
}
diff --git a/CRM/Event/Cart/Form/MerParticipant.php b/CRM/Event/Cart/Form/MerParticipant.php
index b618e7886023..ef45df9b54fe 100644
--- a/CRM/Event/Cart/Form/MerParticipant.php
+++ b/CRM/Event/Cart/Form/MerParticipant.php
@@ -19,7 +19,7 @@ public function __construct($participant) {
* @param CRM_Core_Form $form
*/
public function appendQuickForm(&$form) {
- $textarea_size = array('size' => 30, 'maxlength' => 60);
+ $textarea_size = ['size' => 30, 'maxlength' => 60];
$form->add('text', $this->email_field_name(), ts('Email Address'), $textarea_size, TRUE);
list(
@@ -33,12 +33,12 @@ public function appendQuickForm(&$form) {
foreach ($custom_fields_post as $key => $field) {
CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, $this->participant->id);
}
- $custom = CRM_Utils_Array::value('custom', $form->getTemplate()->_tpl_vars, array());
- $form->assign('custom', array_merge($custom, array(
+ $custom = CRM_Utils_Array::value('custom', $form->getTemplate()->_tpl_vars, []);
+ $form->assign('custom', array_merge($custom, [
$this->html_field_name('customPre') => $custom_fields_pre,
$this->html_field_name('customPost') => $custom_fields_post,
$this->html_field_name('number') => $this->name(),
- )));
+ ]));
}
/**
@@ -47,11 +47,11 @@ public function appendQuickForm(&$form) {
* @return array
*/
public static function get_profile_groups($event_id) {
- $ufJoinParams = array(
+ $ufJoinParams = [
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent',
'entity_id' => $event_id,
- );
+ ];
$group_ids = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
return $group_ids;
}
@@ -62,7 +62,7 @@ public static function get_profile_groups($event_id) {
public function get_participant_custom_data_fields() {
list($custom_pre_id, $custom_post_id) = self::get_profile_groups($this->participant->event_id);
- $pre_fields = $post_fields = array();
+ $pre_fields = $post_fields = [];
if ($custom_pre_id && CRM_Core_BAO_UFGroup::filterUFGroups($custom_pre_id, $this->participant->contact_id)) {
$pre_fields = CRM_Core_BAO_UFGroup::getFields($custom_pre_id, FALSE, CRM_Core_Action::ADD);
}
@@ -70,7 +70,7 @@ public function get_participant_custom_data_fields() {
$post_fields = CRM_Core_BAO_UFGroup::getFields($custom_post_id, FALSE, CRM_Core_Action::ADD);
}
- return array($pre_fields, $post_fields);
+ return [$pre_fields, $post_fields];
}
/**
@@ -113,7 +113,7 @@ public function name() {
*
* @return CRM_Event_Cart_Form_MerParticipant
*/
- static public function get_form($participant) {
+ public static function get_form($participant) {
return new CRM_Event_Cart_Form_MerParticipant($participant);
}
@@ -121,12 +121,12 @@ static public function get_form($participant) {
* @return array
*/
public function setDefaultValues() {
- $defaults = array(
+ $defaults = [
$this->html_field_name('email') => $this->participant->email,
- );
+ ];
list($custom_fields_pre, $custom_fields_post) = $this->get_participant_custom_data_fields($this->participant->event_id);
$all_fields = $custom_fields_pre + $custom_fields_post;
- $flat = array();
+ $flat = [];
CRM_Core_BAO_UFGroup::setProfileDefaults($this->participant->contact_id, $all_fields, $flat);
foreach ($flat as $name => $field) {
$defaults["field[{$this->participant->id}][{$name}]"] = $field;
diff --git a/CRM/Event/Cart/Page/AddToCart.php b/CRM/Event/Cart/Page/AddToCart.php
index 045d77dbc7ea..494a594e6e6f 100644
--- a/CRM/Event/Cart/Page/AddToCart.php
+++ b/CRM/Event/Cart/Page/AddToCart.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_AddToCart
*/
class CRM_Event_Cart_Page_AddToCart extends CRM_Core_Page {
+
/**
* This function takes care of all the things common to all pages.
*
@@ -21,10 +22,10 @@ public function run() {
$event_in_cart = $cart->add_event($this->_id);
$url = CRM_Utils_System::url('civicrm/event/view_cart');
- CRM_Utils_System::setUFMessage(ts("%1 has been added to your cart. View your cart.", array(
- 1 => $event_in_cart->event->title,
- 2 => $url,
- )));
+ CRM_Utils_System::setUFMessage(ts("%1 has been added to your cart. View your cart.", [
+ 1 => $event_in_cart->event->title,
+ 2 => $url,
+ ]));
$transaction->commit();
diff --git a/CRM/Event/Cart/Page/CheckoutAJAX.php b/CRM/Event/Cart/Page/CheckoutAJAX.php
index 73f0982923ab..19c7b8559b35 100644
--- a/CRM/Event/Cart/Page/CheckoutAJAX.php
+++ b/CRM/Event/Cart/Page/CheckoutAJAX.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_CheckoutAJAX
*/
class CRM_Event_Cart_Page_CheckoutAJAX {
+
public function add_participant_to_cart() {
$transaction = new CRM_Core_Transaction();
$cart_id = CRM_Utils_Request::retrieve('cart_id', 'Integer');
@@ -11,11 +12,11 @@ public function add_participant_to_cart() {
$cart = CRM_Event_Cart_BAO_Cart::find_by_id($cart_id);
- $params_array = array(
+ $params_array = [
'cart_id' => $cart->id,
'contact_id' => CRM_Event_Cart_Form_Cart::find_or_create_contact(),
'event_id' => $event_id,
- );
+ ];
//XXX security?
$participant = CRM_Event_Cart_BAO_MerParticipant::create($params_array);
diff --git a/CRM/Event/Cart/Page/RemoveFromCart.php b/CRM/Event/Cart/Page/RemoveFromCart.php
index b9d7efbec483..90f6554f902f 100644
--- a/CRM/Event/Cart/Page/RemoveFromCart.php
+++ b/CRM/Event/Cart/Page/RemoveFromCart.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_RemoveFromCart
*/
class CRM_Event_Cart_Page_RemoveFromCart extends CRM_Core_Page {
+
/**
* This function takes care of all the things common to all pages.
*
@@ -17,7 +18,7 @@ public function run() {
$event_in_cart = $cart->get_event_in_cart_by_event_id($this->_id);
$removed_event = $cart->remove_event_in_cart($event_in_cart->id);
$removed_event_title = $removed_event->event->title;
- CRM_Core_Session::setStatus(ts("%1 has been removed from your cart.", array(1 => $removed_event_title)), '', 'success');
+ CRM_Core_Session::setStatus(ts("%1 has been removed from your cart.", [1 => $removed_event_title]), '', 'success');
$transaction->commit();
return CRM_Utils_System::redirect($_SERVER['HTTP_REFERER']);
}
diff --git a/CRM/Event/Cart/Page/ViewCart.php b/CRM/Event/Cart/Page/ViewCart.php
index 84e20dd64e2d..b2a0a7ce0bdb 100644
--- a/CRM/Event/Cart/Page/ViewCart.php
+++ b/CRM/Event/Cart/Page/ViewCart.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_Page_ViewCart
*/
class CRM_Event_Cart_Page_ViewCart extends CRM_Core_Page {
+
/**
* @return string
*/
diff --git a/CRM/Event/Cart/StateMachine/Checkout.php b/CRM/Event/Cart/StateMachine/Checkout.php
index 337a68a8cb88..3ca22852815a 100644
--- a/CRM/Event/Cart/StateMachine/Checkout.php
+++ b/CRM/Event/Cart/StateMachine/Checkout.php
@@ -4,6 +4,7 @@
* Class CRM_Event_Cart_StateMachine_Checkout
*/
class CRM_Event_Cart_StateMachine_Checkout extends CRM_Core_StateMachine {
+
/**
* @param object $controller
* @param const|int $action
@@ -17,7 +18,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
CRM_Core_Error::statusBounce(ts("You don't have any events in you cart. Please add some events."), CRM_Utils_System::url('civicrm/event'));
}
- $pages = array();
+ $pages = [];
$is_monetary = FALSE;
$is_conference = FALSE;
foreach ($cart->events_in_carts as $event_in_cart) {
@@ -29,10 +30,10 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
foreach ($cart->events_in_carts as $event_in_cart) {
if ($event_in_cart->is_parent_event()) {
foreach ($event_in_cart->participants as $participant) {
- $pages["CRM_Event_Cart_Form_Checkout_ConferenceEvents_{$event_in_cart->event_id}_{$participant->id}"] = array(
+ $pages["CRM_Event_Cart_Form_Checkout_ConferenceEvents_{$event_in_cart->event_id}_{$participant->id}"] = [
'className' => 'CRM_Event_Cart_Form_Checkout_ConferenceEvents',
'title' => "Select {$event_in_cart->event->title} Events For {$participant->email}",
- );
+ ];
}
}
}
diff --git a/CRM/Event/Controller/Registration.php b/CRM/Event/Controller/Registration.php
index 7d0d9cded48d..6a1bf9fabd53 100644
--- a/CRM/Event/Controller/Registration.php
+++ b/CRM/Event/Controller/Registration.php
@@ -1,9 +1,9 @@
__table = 'civicrm_event';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'loc_block_id', 'civicrm_loc_block', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'dedupe_rule_group_id', 'civicrm_dedupe_rule_group', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'loc_block_id', 'civicrm_loc_block', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'dedupe_rule_group_id', 'civicrm_dedupe_rule_group', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event ID') ,
- 'description' => 'Event',
- 'required' => true,
+ 'title' => ts('Event ID'),
+ 'description' => ts('Event'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_event.id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'event_title' => array(
+ ],
+ 'event_title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Event Title') ,
- 'description' => 'Event Title (e.g. Fall Fundraiser Dinner)',
+ 'title' => ts('Event Title'),
+ 'description' => ts('Event Title (e.g. Fall Fundraiser Dinner)'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.title',
'headerPattern' => '/(event.)?title$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'summary' => array(
+ ],
+ ],
+ 'summary' => [
'name' => 'summary',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Event Summary') ,
- 'description' => 'Brief summary of event. Text and html allowed. Displayed on Event Registration form and can be used on other CMS pages which need an event summary.',
+ 'title' => ts('Event Summary'),
+ 'description' => ts('Brief summary of event. Text and html allowed. Displayed on Event Registration form and can be used on other CMS pages which need an event summary.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.summary',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'event_description' => array(
+ ],
+ ],
+ 'event_description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Event Description') ,
- 'description' => 'Full description of event. Text and html allowed. Displayed on built-in Event Information screens.',
+ 'title' => ts('Event Description'),
+ 'description' => ts('Full description of event. Text and html allowed. Displayed on built-in Event Information screens.'),
'rows' => 8,
'cols' => 60,
+ 'where' => 'civicrm_event.description',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'event_type_id' => array(
+ ],
+ ],
+ 'event_type_id' => [
'name' => 'event_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event Type') ,
- 'description' => 'Event Type ID.Implicit FK to civicrm_option_value where option_group = event_type.',
+ 'title' => ts('Event Type'),
+ 'description' => ts('Event Type ID.Implicit FK to civicrm_option_value where option_group = event_type.'),
+ 'where' => 'civicrm_event.event_type_id',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'event_type',
'optionEditPath' => 'civicrm/admin/options/event_type',
- )
- ) ,
- 'participant_listing_id' => array(
+ ]
+ ],
+ 'participant_listing_id' => [
'name' => 'participant_listing_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Listing') ,
- 'description' => 'Should we expose the participant list? Implicit FK to civicrm_option_value where option_group = participant_listing.',
+ 'title' => ts('Participant Listing'),
+ 'description' => ts('Should we expose the participant list? Implicit FK to civicrm_option_value where option_group = participant_listing.'),
+ 'where' => 'civicrm_event.participant_listing_id',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'participant_listing',
'optionEditPath' => 'civicrm/admin/options/participant_listing',
- )
- ) ,
- 'is_public' => array(
+ ]
+ ],
+ 'is_public' => [
'name' => 'is_public',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Event Public') ,
- 'description' => 'Public events will be included in the iCal feeds. Access to private event information may be limited using ACLs.',
+ 'title' => ts('Is Event Public'),
+ 'description' => ts('Public events will be included in the iCal feeds. Access to private event information may be limited using ACLs.'),
+ 'where' => 'civicrm_event.is_public',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'event_start_date' => array(
+ ],
+ ],
+ 'event_start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Event Start Date') ,
- 'description' => 'Date and time that event starts.',
- 'import' => true,
+ 'title' => ts('Event Start Date'),
+ 'description' => ts('Date and time that event starts.'),
+ 'import' => TRUE,
'where' => 'civicrm_event.start_date',
'headerPattern' => '/^start|(s(tart\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'event_end_date' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'event_end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Event End Date') ,
- 'description' => 'Date and time that event ends. May be NULL if no defined end date/time',
- 'import' => true,
+ 'title' => ts('Event End Date'),
+ 'description' => ts('Date and time that event ends. May be NULL if no defined end date/time'),
+ 'import' => TRUE,
'where' => 'civicrm_event.end_date',
'headerPattern' => '/^end|(e(nd\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'is_online_registration' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'is_online_registration' => [
'name' => 'is_online_registration',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Online Registration') ,
- 'description' => 'If true, include registration link on Event Info page.',
+ 'title' => ts('Is Online Registration'),
+ 'description' => ts('If true, include registration link on Event Info page.'),
+ 'where' => 'civicrm_event.is_online_registration',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'registration_link_text' => array(
+ ],
+ ],
+ 'registration_link_text' => [
'name' => 'registration_link_text',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Event Registration Link Text') ,
- 'description' => 'Text for link to Event Registration form which is displayed on Event Information screen when is_online_registration is true.',
+ 'title' => ts('Event Registration Link Text'),
+ 'description' => ts('Text for link to Event Registration form which is displayed on Event Information screen when is_online_registration is true.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.registration_link_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'registration_start_date' => array(
+ ],
+ ],
+ 'registration_start_date' => [
'name' => 'registration_start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Registration Start Date') ,
- 'description' => 'Date and time that online registration starts.',
+ 'title' => ts('Registration Start Date'),
+ 'description' => ts('Date and time that online registration starts.'),
+ 'where' => 'civicrm_event.registration_start_date',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'registration_end_date' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'registration_end_date' => [
'name' => 'registration_end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Registration End Date') ,
- 'description' => 'Date and time that online registration ends.',
+ 'title' => ts('Registration End Date'),
+ 'description' => ts('Date and time that online registration ends.'),
+ 'where' => 'civicrm_event.registration_end_date',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'max_participants' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'max_participants' => [
'name' => 'max_participants',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Participants') ,
- 'description' => 'Maximum number of registered participants to allow. After max is reached, a custom Event Full message is displayed. If NULL, allow unlimited number of participants.',
+ 'title' => ts('Max Participants'),
+ 'description' => ts('Maximum number of registered participants to allow. After max is reached, a custom Event Full message is displayed. If NULL, allow unlimited number of participants.'),
+ 'where' => 'civicrm_event.max_participants',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'event_full_text' => array(
+ ],
+ ],
+ 'event_full_text' => [
'name' => 'event_full_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Event Information') ,
- 'description' => 'Message to display on Event Information page and INSTEAD OF Event Registration form if maximum participants are signed up. Can include email address/info about getting on a waiting list, etc. Text and html allowed.',
+ 'title' => ts('Event Information'),
+ 'description' => ts('Message to display on Event Information page and INSTEAD OF Event Registration form if maximum participants are signed up. Can include email address/info about getting on a waiting list, etc. Text and html allowed.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.event_full_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_monetary' => array(
+ ],
+ ],
+ 'is_monetary' => [
'name' => 'is_monetary',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is this a PAID event?') ,
- 'description' => 'If true, one or more fee amounts must be set and a Payment Processor must be configured for Online Event Registration.',
+ 'title' => ts('Is this a PAID event?'),
+ 'description' => ts('If true, one or more fee amounts must be set and a Payment Processor must be configured for Online Event Registration.'),
+ 'where' => 'civicrm_event.is_monetary',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'financial_type_id' => array(
+ ],
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'Financial type assigned to paid event registrations for this event. Required if is_monetary is true.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('Financial type assigned to paid event registrations for this event. Required if is_monetary is true.'),
+ 'where' => 'civicrm_event.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'payment_processor' => array(
+ ]
+ ],
+ 'payment_processor' => [
'name' => 'payment_processor',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor') ,
- 'description' => 'Payment Processors configured for this Event (if is_monetary is true)',
+ 'title' => ts('Payment Processor'),
+ 'description' => ts('Payment Processors configured for this Event (if is_monetary is true)'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.payment_processor',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_payment_processor',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'is_map' => array(
+ ]
+ ],
+ 'is_map' => [
'name' => 'is_map',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Map Enabled') ,
- 'description' => 'Include a map block on the Event Information page when geocode info is available and a mapping provider has been specified?',
+ 'title' => ts('Map Enabled'),
+ 'description' => ts('Include a map block on the Event Information page when geocode info is available and a mapping provider has been specified?'),
+ 'where' => 'civicrm_event.is_map',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this Event enabled or disabled/cancelled?',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this Event enabled or disabled/cancelled?'),
+ 'where' => 'civicrm_event.is_active',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'fee_label' => array(
+ ],
+ ],
+ 'fee_label' => [
'name' => 'fee_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Fee Label') ,
+ 'title' => ts('Fee Label'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.fee_label',
'headerPattern' => '/^fee|(f(ee\s)?label)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_show_location' => array(
+ ],
+ ],
+ 'is_show_location' => [
'name' => 'is_show_location',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('show location') ,
- 'description' => 'If true, show event location.',
+ 'title' => ts('show location'),
+ 'description' => ts('If true, show event location.'),
+ 'where' => 'civicrm_event.is_show_location',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'loc_block_id' => array(
+ ],
+ ],
+ 'loc_block_id' => [
'name' => 'loc_block_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Location Block ID') ,
- 'description' => 'FK to Location Block ID',
+ 'title' => ts('Location Block ID'),
+ 'description' => ts('FK to Location Block ID'),
+ 'where' => 'civicrm_event.loc_block_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_LocBlock',
- ) ,
- 'default_role_id' => array(
+ ],
+ 'default_role_id' => [
'name' => 'default_role_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Default Role') ,
- 'description' => 'Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.',
- 'import' => true,
+ 'title' => ts('Default Role'),
+ 'description' => ts('Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.'),
+ 'import' => TRUE,
'where' => 'civicrm_event.default_role_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'participant_role',
'optionEditPath' => 'civicrm/admin/options/participant_role',
- )
- ) ,
- 'intro_text' => array(
+ ]
+ ],
+ 'intro_text' => [
'name' => 'intro_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Introductory Message') ,
- 'description' => 'Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.',
+ 'title' => ts('Introductory Message'),
+ 'description' => ts('Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.intro_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'footer_text' => array(
+ ],
+ ],
+ 'footer_text' => [
'name' => 'footer_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Footer Message') ,
- 'description' => 'Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.',
+ 'title' => ts('Footer Message'),
+ 'description' => ts('Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.footer_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_title' => array(
+ ],
+ ],
+ 'confirm_title' => [
'name' => 'confirm_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Confirmation Title') ,
- 'description' => 'Title for Confirmation page.',
+ 'title' => ts('Confirmation Title'),
+ 'description' => ts('Title for Confirmation page.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.confirm_title',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'confirm_text' => array(
+ ],
+ ],
+ 'confirm_text' => [
'name' => 'confirm_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Confirm Text') ,
- 'description' => 'Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.',
+ 'title' => ts('Confirm Text'),
+ 'description' => ts('Introductory message for Event Registration page. Text and html allowed. Displayed at the top of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.confirm_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_footer_text' => array(
+ ],
+ ],
+ 'confirm_footer_text' => [
'name' => 'confirm_footer_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Footer Text') ,
- 'description' => 'Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.',
+ 'title' => ts('Footer Text'),
+ 'description' => ts('Footer message for Event Registration page. Text and html allowed. Displayed at the bottom of Event Registration form.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.confirm_footer_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_email_confirm' => array(
+ ],
+ ],
+ 'is_email_confirm' => [
'name' => 'is_email_confirm',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is confirm email') ,
- 'description' => 'If true, confirmation is automatically emailed to contact on successful registration.',
+ 'title' => ts('Is confirm email'),
+ 'description' => ts('If true, confirmation is automatically emailed to contact on successful registration.'),
+ 'where' => 'civicrm_event.is_email_confirm',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'confirm_email_text' => array(
+ ],
+ ],
+ 'confirm_email_text' => [
'name' => 'confirm_email_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Confirmation Email Text') ,
- 'description' => 'text to include above standard event info on confirmation email. emails are text-only, so do not allow html for now',
+ 'title' => ts('Confirmation Email Text'),
+ 'description' => ts('text to include above standard event info on confirmation email. emails are text-only, so do not allow html for now'),
'rows' => 4,
'cols' => 50,
+ 'where' => 'civicrm_event.confirm_email_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'confirm_from_name' => array(
+ ],
+ ],
+ 'confirm_from_name' => [
'name' => 'confirm_from_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Confirm From Name') ,
- 'description' => 'FROM email name used for confirmation emails.',
+ 'title' => ts('Confirm From Name'),
+ 'description' => ts('FROM email name used for confirmation emails.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.confirm_from_name',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'confirm_from_email' => array(
+ ],
+ ],
+ 'confirm_from_email' => [
'name' => 'confirm_from_email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Confirm From Email') ,
- 'description' => 'FROM email address used for confirmation emails.',
+ 'title' => ts('Confirm From Email'),
+ 'description' => ts('FROM email address used for confirmation emails.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.confirm_from_email',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'cc_confirm' => array(
+ ],
+ ],
+ 'cc_confirm' => [
'name' => 'cc_confirm',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Cc Confirm') ,
- 'description' => 'comma-separated list of email addresses to cc each time a confirmation is sent',
+ 'title' => ts('Cc Confirm'),
+ 'description' => ts('comma-separated list of email addresses to cc each time a confirmation is sent'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.cc_confirm',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'bcc_confirm' => array(
+ ],
+ ],
+ 'bcc_confirm' => [
'name' => 'bcc_confirm',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Bcc Confirm') ,
- 'description' => 'comma-separated list of email addresses to bcc each time a confirmation is sent',
+ 'title' => ts('Bcc Confirm'),
+ 'description' => ts('comma-separated list of email addresses to bcc each time a confirmation is sent'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.bcc_confirm',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'default_fee_id' => array(
+ ],
+ ],
+ 'default_fee_id' => [
'name' => 'default_fee_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Default Fee ID') ,
- 'description' => 'FK to civicrm_option_value.',
+ 'title' => ts('Default Fee ID'),
+ 'description' => ts('FK to civicrm_option_value.'),
+ 'where' => 'civicrm_event.default_fee_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'default_discount_fee_id' => array(
+ ],
+ 'default_discount_fee_id' => [
'name' => 'default_discount_fee_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Default Discount Fee ID') ,
- 'description' => 'FK to civicrm_option_value.',
+ 'title' => ts('Default Discount Fee ID'),
+ 'description' => ts('FK to civicrm_option_value.'),
+ 'where' => 'civicrm_event.default_discount_fee_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'thankyou_title' => array(
+ ],
+ 'thankyou_title' => [
'name' => 'thankyou_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('ThankYou Title') ,
- 'description' => 'Title for ThankYou page.',
+ 'title' => ts('ThankYou Title'),
+ 'description' => ts('Title for ThankYou page.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.thankyou_title',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'thankyou_text' => array(
+ ],
+ ],
+ 'thankyou_text' => [
'name' => 'thankyou_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('ThankYou Text') ,
- 'description' => 'ThankYou Text.',
+ 'title' => ts('ThankYou Text'),
+ 'description' => ts('ThankYou Text.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.thankyou_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'thankyou_footer_text' => array(
+ ],
+ ],
+ 'thankyou_footer_text' => [
'name' => 'thankyou_footer_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Footer Text') ,
- 'description' => 'Footer message.',
+ 'title' => ts('Footer Text'),
+ 'description' => ts('Footer message.'),
'rows' => 6,
'cols' => 50,
+ 'where' => 'civicrm_event.thankyou_footer_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_pay_later' => array(
+ ],
+ ],
+ 'is_pay_later' => [
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Pay Later Allowed') ,
- 'description' => 'if true - allows the user to send payment directly to the org later',
+ 'title' => ts('Pay Later Allowed'),
+ 'description' => ts('if true - allows the user to send payment directly to the org later'),
+ 'where' => 'civicrm_event.is_pay_later',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'pay_later_text' => array(
+ ],
+ ],
+ 'pay_later_text' => [
'name' => 'pay_later_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Pay Later Text') ,
- 'description' => 'The text displayed to the user in the main form',
+ 'title' => ts('Pay Later Text'),
+ 'description' => ts('The text displayed to the user in the main form'),
+ 'where' => 'civicrm_event.pay_later_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'pay_later_receipt' => array(
+ ],
+ ],
+ 'pay_later_receipt' => [
'name' => 'pay_later_receipt',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Pay Later Receipt Text') ,
- 'description' => 'The receipt sent to the user instead of the normal receipt text',
+ 'title' => ts('Pay Later Receipt Text'),
+ 'description' => ts('The receipt sent to the user instead of the normal receipt text'),
+ 'where' => 'civicrm_event.pay_later_receipt',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_partial_payment' => array(
+ ],
+ ],
+ 'is_partial_payment' => [
'name' => 'is_partial_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Partial Payments Enabled') ,
- 'description' => 'is partial payment enabled for this event',
+ 'title' => ts('Partial Payments Enabled'),
+ 'description' => ts('is partial payment enabled for this event'),
+ 'where' => 'civicrm_event.is_partial_payment',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'initial_amount_label' => array(
+ ],
+ ],
+ 'initial_amount_label' => [
'name' => 'initial_amount_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Initial Amount Label') ,
- 'description' => 'Initial amount label for partial payment',
+ 'title' => ts('Initial Amount Label'),
+ 'description' => ts('Initial amount label for partial payment'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_event.initial_amount_label',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'initial_amount_help_text' => array(
+ ],
+ ],
+ 'initial_amount_help_text' => [
'name' => 'initial_amount_help_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Initial Amount Help Text') ,
- 'description' => 'Initial amount help text for partial payment',
+ 'title' => ts('Initial Amount Help Text'),
+ 'description' => ts('Initial amount help text for partial payment'),
+ 'where' => 'civicrm_event.initial_amount_help_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'min_initial_amount' => array(
+ ],
+ ],
+ 'min_initial_amount' => [
'name' => 'min_initial_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Minimum Initial Amount') ,
- 'description' => 'Minimum initial amount for partial payment',
- 'precision' => array(
+ 'title' => ts('Minimum Initial Amount'),
+ 'description' => ts('Minimum initial amount for partial payment'),
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_event.min_initial_amount',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_multiple_registrations' => array(
+ ],
+ ],
+ 'is_multiple_registrations' => [
'name' => 'is_multiple_registrations',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Allow Multiple Registrations') ,
- 'description' => 'if true - allows the user to register multiple participants for event',
+ 'title' => ts('Allow Multiple Registrations'),
+ 'description' => ts('if true - allows the user to register multiple participants for event'),
+ 'where' => 'civicrm_event.is_multiple_registrations',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'max_additional_participants' => array(
+ ],
+ ],
+ 'max_additional_participants' => [
'name' => 'max_additional_participants',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum number of additional participants per registration') ,
- 'description' => 'Maximum number of additional participants that can be registered on a single booking',
+ 'title' => ts('Maximum number of additional participants per registration'),
+ 'description' => ts('Maximum number of additional participants that can be registered on a single booking'),
+ 'where' => 'civicrm_event.max_additional_participants',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'allow_same_participant_emails' => array(
+ ],
+ 'allow_same_participant_emails' => [
'name' => 'allow_same_participant_emails',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Does Event allow multiple registrations from same email address?') ,
- 'description' => 'if true - allows the user to register multiple registrations from same email address.',
+ 'title' => ts('Does Event allow multiple registrations from same email address?'),
+ 'description' => ts('if true - allows the user to register multiple registrations from same email address.'),
+ 'where' => 'civicrm_event.allow_same_participant_emails',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'has_waitlist' => array(
+ ],
+ ],
+ 'has_waitlist' => [
'name' => 'has_waitlist',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Waitlist Enabled') ,
- 'description' => 'Whether the event has waitlist support.',
+ 'title' => ts('Waitlist Enabled'),
+ 'description' => ts('Whether the event has waitlist support.'),
+ 'where' => 'civicrm_event.has_waitlist',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'requires_approval' => array(
+ ],
+ ],
+ 'requires_approval' => [
'name' => 'requires_approval',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Requires Approval') ,
- 'description' => 'Whether participants require approval before they can finish registering.',
+ 'title' => ts('Requires Approval'),
+ 'description' => ts('Whether participants require approval before they can finish registering.'),
+ 'where' => 'civicrm_event.requires_approval',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'expiration_time' => array(
+ ],
+ ],
+ 'expiration_time' => [
'name' => 'expiration_time',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Expiration Time') ,
- 'description' => 'Expire pending but unconfirmed registrations after this many hours.',
+ 'title' => ts('Expiration Time'),
+ 'description' => ts('Expire pending but unconfirmed registrations after this many hours.'),
+ 'where' => 'civicrm_event.expiration_time',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'allow_selfcancelxfer' => array(
+ ],
+ ],
+ 'allow_selfcancelxfer' => [
'name' => 'allow_selfcancelxfer',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Allow Self-service Cancellation or Transfer') ,
- 'description' => 'Allow self service cancellation or transfer for event?',
+ 'title' => ts('Allow Self-service Cancellation or Transfer'),
+ 'description' => ts('Allow self service cancellation or transfer for event?'),
+ 'where' => 'civicrm_event.allow_selfcancelxfer',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'selfcancelxfer_time' => array(
+ ],
+ ],
+ 'selfcancelxfer_time' => [
'name' => 'selfcancelxfer_time',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Self-service Cancellation or Transfer Time') ,
- 'description' => 'Number of hours prior to event start date to allow self-service cancellation or transfer.',
+ 'title' => ts('Self-service Cancellation or Transfer Time'),
+ 'description' => ts('Number of hours prior to event start date to allow self-service cancellation or transfer.'),
+ 'where' => 'civicrm_event.selfcancelxfer_time',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'waitlist_text' => array(
+ ],
+ ],
+ 'waitlist_text' => [
'name' => 'waitlist_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Waitlist Text') ,
- 'description' => 'Text to display when the event is full, but participants can signup for a waitlist.',
+ 'title' => ts('Waitlist Text'),
+ 'description' => ts('Text to display when the event is full, but participants can signup for a waitlist.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.waitlist_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'approval_req_text' => array(
+ ],
+ ],
+ 'approval_req_text' => [
'name' => 'approval_req_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Approval Req Text') ,
- 'description' => 'Text to display when the approval is required to complete registration for an event.',
+ 'title' => ts('Approval Req Text'),
+ 'description' => ts('Text to display when the approval is required to complete registration for an event.'),
'rows' => 4,
'cols' => 60,
+ 'where' => 'civicrm_event.approval_req_text',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'is_template' => array(
+ ],
+ ],
+ 'is_template' => [
'name' => 'is_template',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is an Event Template') ,
- 'description' => 'whether the event has template',
- 'required' => true,
+ 'title' => ts('Is an Event Template'),
+ 'description' => ts('whether the event has template'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_event.is_template',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'template_title' => array(
+ ],
+ ],
+ 'template_title' => [
'name' => 'template_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Event Template Title') ,
- 'description' => 'Event Template Title',
+ 'title' => ts('Event Template Title'),
+ 'description' => ts('Event Template Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.template_title',
'headerPattern' => '/(template.)?title$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'created_id' => array(
+ ],
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Created By Contact ID') ,
- 'description' => 'FK to civicrm_contact, who created this event',
+ 'title' => ts('Created By Contact ID'),
+ 'description' => ts('FK to civicrm_contact, who created this event'),
+ 'where' => 'civicrm_event.created_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Event Created Date') ,
- 'description' => 'Date and time that event was created.',
+ 'title' => ts('Event Created Date'),
+ 'description' => ts('Date and time that event was created.'),
+ 'where' => 'civicrm_event.created_date',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_event.currency',
'headerPattern' => '/cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/i',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'campaign_id' => array(
+ ]
+ ],
+ 'campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this event has been created.',
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this event has been created.'),
+ 'where' => 'civicrm_event.campaign_id',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'is_share' => array(
+ ]
+ ],
+ 'is_share' => [
'name' => 'is_share',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is shared through social media') ,
- 'description' => 'Can people share the event through social media?',
+ 'title' => ts('Is shared through social media'),
+ 'description' => ts('Can people share the event through social media?'),
+ 'where' => 'civicrm_event.is_share',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_confirm_enabled' => array(
+ ],
+ ],
+ 'is_confirm_enabled' => [
'name' => 'is_confirm_enabled',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is the booking confirmation screen enabled?') ,
- 'description' => 'If false, the event booking confirmation screen gets skipped',
+ 'title' => ts('Is the booking confirmation screen enabled?'),
+ 'description' => ts('If false, the event booking confirmation screen gets skipped'),
+ 'where' => 'civicrm_event.is_confirm_enabled',
'default' => '1',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'parent_event_id' => array(
+ ],
+ ],
+ 'parent_event_id' => [
'name' => 'parent_event_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Parent Event ID') ,
- 'description' => 'Implicit FK to civicrm_event: parent event',
+ 'title' => ts('Parent Event ID'),
+ 'description' => ts('Implicit FK to civicrm_event: parent event'),
+ 'where' => 'civicrm_event.parent_event_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'slot_label_id' => array(
+ ],
+ ],
+ 'slot_label_id' => [
'name' => 'slot_label_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Subevent Slot Label ID') ,
- 'description' => 'Subevent slot label. Implicit FK to civicrm_option_value where option_group = conference_slot.',
+ 'title' => ts('Subevent Slot Label ID'),
+ 'description' => ts('Subevent slot label. Implicit FK to civicrm_option_value where option_group = conference_slot.'),
+ 'where' => 'civicrm_event.slot_label_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'dedupe_rule_group_id' => array(
+ ],
+ ],
+ 'dedupe_rule_group_id' => [
'name' => 'dedupe_rule_group_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Dedupe Rule') ,
- 'description' => 'Rule to use when matching registrations for this event',
+ 'title' => ts('Dedupe Rule'),
+ 'description' => ts('Rule to use when matching registrations for this event'),
+ 'where' => 'civicrm_event.dedupe_rule_group_id',
'default' => 'NULL',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
'FKClassName' => 'CRM_Dedupe_DAO_RuleGroup',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_dedupe_rule_group',
'keyColumn' => 'id',
'labelColumn' => 'title',
'nameColumn' => 'name',
- )
- ) ,
- 'is_billing_required' => array(
+ ]
+ ],
+ 'is_billing_required' => [
'name' => 'is_billing_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is billing block required') ,
- 'description' => 'if true than billing block is required this event',
+ 'title' => ts('Is billing block required'),
+ 'description' => ts('if true than billing block is required this event'),
+ 'where' => 'civicrm_event.is_billing_required',
+ 'default' => '0',
'table_name' => 'civicrm_event',
'entity' => 'Event',
'bao' => 'CRM_Event_BAO_Event',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -1556,10 +1683,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -1567,40 +1695,46 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_event_type_id' => array(
+ $indices = [
+ 'index_event_type_id' => [
'name' => 'index_event_type_id',
- 'field' => array(
+ 'field' => [
0 => 'event_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_event::0::event_type_id',
- ) ,
- 'index_participant_listing_id' => array(
+ ],
+ 'index_participant_listing_id' => [
'name' => 'index_participant_listing_id',
- 'field' => array(
+ 'field' => [
0 => 'participant_listing_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_event::0::participant_listing_id',
- ) ,
- 'index_parent_event_id' => array(
+ ],
+ 'index_parent_event_id' => [
'name' => 'index_parent_event_id',
- 'field' => array(
+ 'field' => [
0 => 'parent_event_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_event::0::parent_event_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/DAO/Participant.php b/CRM/Event/DAO/Participant.php
index 9142d60ba405..fc7aaccb3840 100644
--- a/CRM/Event/DAO/Participant.php
+++ b/CRM/Event/DAO/Participant.php
@@ -1,97 +1,82 @@
__table = 'civicrm_participant';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_id', 'civicrm_event', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_participant_status_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'registered_by_id', 'civicrm_participant', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'discount_id', 'civicrm_discount', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'cart_id', 'civicrm_event_carts', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'transferred_to_contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'event_id', 'civicrm_event', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'status_id', 'civicrm_participant_status_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'registered_by_id', 'civicrm_participant', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'discount_id', 'civicrm_discount', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'cart_id', 'civicrm_event_carts', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'transferred_to_contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'participant_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'participant_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant ID') ,
- 'description' => 'Participant Id',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Participant ID'),
+ 'description' => ts('Participant Id'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.id',
'headerPattern' => '/(^(participant(.)?)?id$)/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_contact_id' => array(
+ ],
+ 'participant_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.contact_id',
'headerPattern' => '/contact(.?id)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'event_id' => array(
+ ],
+ 'event_id' => [
'name' => 'event_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event') ,
- 'description' => 'FK to Event ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Event'),
+ 'description' => ts('FK to Event ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.event_id',
'headerPattern' => '/event id$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Event',
- ) ,
- 'participant_status_id' => array(
+ ],
+ 'participant_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Status') ,
- 'description' => 'Participant status ID. FK to civicrm_participant_status_type. Default of 1 should map to status = Registered.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Participant Status'),
+ 'description' => ts('Participant status ID. FK to civicrm_participant_status_type. Default of 1 should map to status = Registered.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_participant.status_id',
'headerPattern' => '/(participant.)?(status)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_ParticipantStatusType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_participant_status_type',
'keyColumn' => 'id',
'labelColumn' => 'label',
- )
- ) ,
- 'participant_role_id' => array(
+ ]
+ ],
+ 'participant_role_id' => [
'name' => 'role_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Role') ,
- 'description' => 'Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.',
+ 'title' => ts('Participant Role'),
+ 'description' => ts('Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant.role_id',
'headerPattern' => '/(participant.)?(role)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- 'html' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_TRIMMED,
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'participant_role',
'optionEditPath' => 'civicrm/admin/options/participant_role',
- )
- ) ,
- 'participant_register_date' => array(
+ ]
+ ],
+ 'participant_register_date' => [
'name' => 'register_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Register date') ,
- 'description' => 'When did contact register for event?',
- 'import' => true,
+ 'title' => ts('Register date'),
+ 'description' => ts('When did contact register for event?'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.register_date',
'headerPattern' => '/^(r(egister\s)?date)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'participant_source' => array(
+ ],
+ ],
+ 'participant_source' => [
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Source') ,
- 'description' => 'Source of this event registration.',
+ 'title' => ts('Participant Source'),
+ 'description' => ts('Source of this event registration.'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant.source',
'headerPattern' => '/(participant.)?(source)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_fee_level' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'participant_fee_level' => [
'name' => 'fee_level',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Fee level') ,
- 'description' => 'Populate with the label (text) associated with a fee level for paid events with multiple levels. Note that
+ 'title' => ts('Fee level'),
+ 'description' => ts('Populate with the label (text) associated with a fee level for paid events with multiple levels. Note that
we store the label value and not the key
- ',
- 'import' => true,
+ '),
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_level',
'headerPattern' => '/^(f(ee\s)?level)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_is_test' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_BOOKEND,
+ ],
+ 'participant_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.is_test',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_is_pay_later' => array(
+ ],
+ 'participant_is_pay_later' => [
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Pay Later') ,
- 'import' => true,
+ 'title' => ts('Is Pay Later'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.is_pay_later',
'headerPattern' => '/(is.)?(pay(.)?later)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_fee_amount' => array(
+ ],
+ 'participant_fee_amount' => [
'name' => 'fee_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Fee Amount') ,
- 'description' => 'actual processor fee if known - may be 0.',
- 'precision' => array(
+ 'title' => ts('Fee Amount'),
+ 'description' => ts('actual processor fee if known - may be 0.'),
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_amount',
'headerPattern' => '/fee(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'participant_registered_by_id' => array(
+ ],
+ 'participant_registered_by_id' => [
'name' => 'registered_by_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Registered By ID') ,
- 'description' => 'FK to Participant ID',
- 'import' => true,
+ 'title' => ts('Registered By ID'),
+ 'description' => ts('FK to Participant ID'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.registered_by_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Participant',
- ) ,
- 'participant_discount_id' => array(
+ ],
+ 'participant_discount_id' => [
'name' => 'discount_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Discount ID') ,
- 'description' => 'FK to Discount ID',
+ 'title' => ts('Discount ID'),
+ 'description' => ts('FK to Discount ID'),
+ 'where' => 'civicrm_participant.discount_id',
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Discount',
- ) ,
- 'participant_fee_currency' => array(
+ ],
+ 'participant_fee_currency' => [
'name' => 'fee_currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Fee Currency') ,
- 'description' => '3 character string, value derived from config setting.',
+ 'title' => ts('Fee Currency'),
+ 'description' => ts('3 character string, value derived from config setting.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant.fee_currency',
'headerPattern' => '/(fee)?.?cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/i',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'participant_campaign_id' => array(
+ ]
+ ],
+ 'participant_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this participant has been registered.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this participant has been registered.'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'discount_amount' => array(
+ ]
+ ],
+ 'discount_amount' => [
'name' => 'discount_amount',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Discount Amount') ,
- 'description' => 'Discount Amount',
+ 'title' => ts('Discount Amount'),
+ 'description' => ts('Discount Amount'),
+ 'where' => 'civicrm_participant.discount_amount',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'cart_id' => array(
+ ],
+ 'cart_id' => [
'name' => 'cart_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Event Cart ID') ,
- 'description' => 'FK to civicrm_event_carts',
+ 'title' => ts('Event Cart ID'),
+ 'description' => ts('FK to civicrm_event_carts'),
+ 'where' => 'civicrm_participant.cart_id',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_Cart_DAO_Cart',
- ) ,
- 'must_wait' => array(
+ ],
+ 'must_wait' => [
'name' => 'must_wait',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Must Wait on List') ,
- 'description' => 'On Waiting List',
+ 'title' => ts('Must Wait on List'),
+ 'description' => ts('On Waiting List'),
+ 'where' => 'civicrm_participant.must_wait',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
- ) ,
- 'transferred_to_contact_id' => array(
+ ],
+ 'transferred_to_contact_id' => [
'name' => 'transferred_to_contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Transferred to Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'import' => true,
+ 'title' => ts('Transferred to Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'import' => TRUE,
'where' => 'civicrm_participant.transferred_to_contact_id',
'headerPattern' => '/transfer(.?id)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -565,10 +561,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -576,32 +573,38 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_status_id' => array(
+ $indices = [
+ 'index_status_id' => [
'name' => 'index_status_id',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_participant::0::status_id',
- ) ,
- 'index_role_id' => array(
+ ],
+ 'index_role_id' => [
'name' => 'index_role_id',
- 'field' => array(
+ 'field' => [
0 => 'role_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_participant::0::role_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/DAO/ParticipantPayment.php b/CRM/Event/DAO/ParticipantPayment.php
index ca92fc99c0f9..39843364b0cb 100644
--- a/CRM/Event/DAO/ParticipantPayment.php
+++ b/CRM/Event/DAO/ParticipantPayment.php
@@ -1,171 +1,161 @@
__table = 'civicrm_participant_payment';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'participant_id', 'civicrm_participant', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'participant_id', 'civicrm_participant', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment ID') ,
- 'description' => 'Participant Payment Id',
- 'required' => true,
+ 'title' => ts('Payment ID'),
+ 'description' => ts('Participant Payment Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_payment.id',
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
- ) ,
- 'participant_id' => array(
+ ],
+ 'participant_id' => [
'name' => 'participant_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant ID') ,
- 'description' => 'Participant Id (FK)',
- 'required' => true,
+ 'title' => ts('Participant ID'),
+ 'description' => ts('Participant Id (FK)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_payment.participant_id',
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Participant',
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution') ,
- 'description' => 'FK to contribution table.',
- 'required' => true,
+ 'title' => ts('Contribution'),
+ 'description' => ts('FK to contribution table.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_payment.contribution_id',
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -173,10 +163,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_payment', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -184,26 +175,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_payment', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contribution_participant' => array(
+ $indices = [
+ 'UI_contribution_participant' => [
'name' => 'UI_contribution_participant',
- 'field' => array(
+ 'field' => [
0 => 'contribution_id',
1 => 'participant_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_participant_payment::1::contribution_id::participant_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/DAO/ParticipantStatusType.php b/CRM/Event/DAO/ParticipantStatusType.php
index a902d4432f76..e04f88ced3fb 100644
--- a/CRM/Event/DAO/ParticipantStatusType.php
+++ b/CRM/Event/DAO/ParticipantStatusType.php
@@ -1,274 +1,272 @@
__table = 'civicrm_participant_status_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Status Type ID') ,
- 'description' => 'unique participant status type id',
- 'required' => true,
+ 'title' => ts('Participant Status Type ID'),
+ 'description' => ts('unique participant status type id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_status_type.id',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'participant_status' => array(
+ ],
+ 'participant_status' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Status') ,
- 'description' => 'non-localized name of the status type',
+ 'title' => ts('Participant Status'),
+ 'description' => ts('non-localized name of the status type'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_participant_status_type.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Status Label') ,
- 'description' => 'localized label for display of this status type',
+ 'title' => ts('Participant Status Label'),
+ 'description' => ts('localized label for display of this status type'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_participant_status_type.label',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 1,
- ) ,
- 'class' => array(
+ ],
+ 'class' => [
'name' => 'class',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Participant Status Class') ,
- 'description' => 'the general group of status type this one belongs to',
+ 'title' => ts('Participant Status Class'),
+ 'description' => ts('the general group of status type this one belongs to'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_participant_status_type.class',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Event_PseudoConstant::participantStatusClassOptions',
- )
- ) ,
- 'is_reserved' => array(
+ ]
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Participant Status Is Reserved?>') ,
- 'description' => 'whether this is a status type required by the system',
+ 'title' => ts('Participant Status Is Reserved?>'),
+ 'description' => ts('whether this is a status type required by the system'),
+ 'where' => 'civicrm_participant_status_type.is_reserved',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Participant Status is Active') ,
- 'description' => 'whether this status type is active',
+ 'title' => ts('Participant Status is Active'),
+ 'description' => ts('whether this status type is active'),
+ 'where' => 'civicrm_participant_status_type.is_active',
'default' => '1',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'is_counted' => array(
+ ],
+ 'is_counted' => [
'name' => 'is_counted',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Participant Status Counts?') ,
- 'description' => 'whether this status type is counted against event size limit',
+ 'title' => ts('Participant Status Counts?'),
+ 'description' => ts('whether this status type is counted against event size limit'),
+ 'where' => 'civicrm_participant_status_type.is_counted',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'weight' => array(
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'controls sort order',
- 'required' => true,
+ 'title' => ts('Order'),
+ 'description' => ts('controls sort order'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_participant_status_type.weight',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- ) ,
- 'visibility_id' => array(
+ ],
+ 'visibility_id' => [
'name' => 'visibility_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Participant Status Visibility') ,
- 'description' => 'whether the status type is visible to the public, an implicit foreign key to option_value.value related to the `visibility` option_group',
+ 'title' => ts('Participant Status Visibility'),
+ 'description' => ts('whether the status type is visible to the public, an implicit foreign key to option_value.value related to the `visibility` option_group'),
+ 'where' => 'civicrm_participant_status_type.visibility_id',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'visibility',
'optionEditPath' => 'civicrm/admin/options/visibility',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -276,10 +274,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_status_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_status_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -287,15 +286,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_status_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_status_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Event/Form/EventFees.php b/CRM/Event/Form/EventFees.php
index 216f97ce258d..f5972943bfde 100644
--- a/CRM/Event/Form/EventFees.php
+++ b/CRM/Event/Form/EventFees.php
@@ -1,9 +1,9 @@
_eventId) {
//get receipt text and financial type
- $returnProperities = array('confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date');
- $details = array();
+ $returnProperities = ['confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date'];
+ $details = [];
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
if (!empty($details[$form->_eventId]['financial_type_id'])) {
$defaults[$form->_pId]['financial_type_id'] = $details[$form->_eventId]['financial_type_id'];
@@ -84,12 +84,12 @@ public static function setDefaultValues(&$form) {
}
if ($form->_pId) {
- $ids = array();
- $params = array('id' => $form->_pId);
+ $ids = [];
+ $params = ['id' => $form->_pId];
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
if ($form->_action == CRM_Core_Action::UPDATE) {
- $discounts = array();
+ $discounts = [];
if (!empty($form->_values['discount'])) {
foreach ($form->_values['discount'] as $key => $value) {
$value = current($value);
@@ -113,7 +113,7 @@ public static function setDefaultValues(&$form) {
$defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
}
- list($defaults[$form->_pId]['receive_date'], $defaults[$form->_pId]['receive_date_time']) = CRM_Utils_Date::setDateDefaults();
+ $defaults[$form->_pId]['receive_date'] = date('Y-m-d H:i:s');
}
//CRM-11601 we should keep the record contribution
@@ -139,12 +139,6 @@ public static function setDefaultValues(&$form) {
$billingDefaults = $form->getProfileDefaults('Billing', $form->_contactId);
$defaults[$form->_pId] = array_merge($defaults[$form->_pId], $billingDefaults);
-
- // // hack to simplify credit card entry for testing
- // $defaults[$form->_pId]['credit_card_type'] = 'Visa';
- // $defaults[$form->_pId]['credit_card_number'] = '4807731747657838';
- // $defaults[$form->_pId]['cvv2'] = '000';
- // $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
}
// if user has selected discount use that to set default
@@ -179,11 +173,11 @@ public static function setDefaultValues(&$form) {
if ($priceSetId) {
// get price set default values, CRM-4090
if (in_array(get_class($form),
- array(
+ [
'CRM_Event_Form_Participant',
'CRM_Event_Form_Registration_Register',
'CRM_Event_Form_Registration_AdditionalParticipant',
- )
+ ]
)) {
$priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
if (!empty($priceSetValues)) {
@@ -230,19 +224,14 @@ public static function setDefaultValues(&$form) {
$contribution = new CRM_Contribute_DAO_Contribution();
$contribution->id = $contriId;
$contribution->find(TRUE);
- foreach (array(
- 'financial_type_id',
- 'payment_instrument_id',
- 'contribution_status_id',
- 'receive_date',
- 'total_amount',
- ) as $f) {
- if ($f == 'receive_date') {
- list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->$f);
- }
- else {
- $defaults[$form->_pId][$f] = $contribution->$f;
- }
+ foreach ([
+ 'financial_type_id',
+ 'payment_instrument_id',
+ 'contribution_status_id',
+ 'receive_date',
+ 'total_amount',
+ ] as $f) {
+ $defaults[$form->_pId][$f] = $contribution->$f;
}
}
return $defaults[$form->_pId];
@@ -258,7 +247,7 @@ public static function setDefaultValues(&$form) {
* @return array
*/
public static function setDefaultPriceSet($participantID, $eventID = NULL, $includeQtyZero = TRUE) {
- $defaults = array();
+ $defaults = [];
if (!$eventID && $participantID) {
$eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'event_id');
}
@@ -279,7 +268,7 @@ public static function setDefaultPriceSet($participantID, $eventID = NULL, $incl
!CRM_Utils_System::isNull($lineItems[$participantID])
) {
- $priceFields = $htmlTypes = $optionValues = array();
+ $priceFields = $htmlTypes = $optionValues = [];
foreach ($lineItems[$participantID] as $lineId => $items) {
$priceFieldId = CRM_Utils_Array::value('price_field_id', $items);
$priceOptionId = CRM_Utils_Array::value('price_field_value_id', $items);
@@ -349,7 +338,7 @@ public static function buildQuickForm(&$form) {
// make sure this is for backoffice registration.
if ($form->getName() == 'Participant') {
$eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $form->_pId);
- $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, array('id' => 'hidden_eventFullMsg'));
+ $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, ['id' => 'hidden_eventFullMsg']);
}
}
@@ -363,14 +352,14 @@ public static function buildQuickForm(&$form) {
}
if ($form->_isPaidEvent) {
- $params = array('id' => $form->_eventId);
+ $params = ['id' => $form->_eventId];
CRM_Event_BAO_Event::retrieve($params, $event);
//retrieve custom information
- $form->_values = array();
+ $form->_values = [];
CRM_Event_Form_Registration::initEventFee($form, $event['id']);
CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
- $lineItem = array();
+ $lineItem = [];
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
@@ -384,7 +373,7 @@ public static function buildQuickForm(&$form) {
$form->assign('totalTaxAmount', $totalTaxAmount);
}
$form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
- $discounts = array();
+ $discounts = [];
if (!empty($form->_values['discount'])) {
foreach ($form->_values['discount'] as $key => $value) {
$value = current($value);
@@ -393,11 +382,11 @@ public static function buildQuickForm(&$form) {
$element = $form->add('select', 'discount_id',
ts('Discount Set'),
- array(
+ [
0 => ts('- select -'),
- ) + $discounts,
+ ] + $discounts,
FALSE,
- array('class' => "crm-select2")
+ ['class' => "crm-select2"]
);
if ($form->_online) {
@@ -415,7 +404,7 @@ public static function buildQuickForm(&$form) {
CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE, self::getDefaultPaymentInstrumentId());
if (!$form->_mode) {
$form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
- array('onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);")
+ ['onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);"]
);
// Check permissions for financial type first
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
@@ -427,15 +416,15 @@ public static function buildQuickForm(&$form) {
$form->add('select', 'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialTypes
+ ['' => ts('- select -')] + $financialTypes
);
- $form->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
+ $form->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
$form->add('select', 'payment_instrument_id',
ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
- FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
);
// don't show transaction id in batch update mode
$path = CRM_Utils_System::currentPath();
@@ -443,7 +432,7 @@ public static function buildQuickForm(&$form) {
if ($path != 'civicrm/contact/search/basic') {
$form->add('text', 'trxn_id', ts('Transaction ID'));
$form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
- 'objectExists', array('CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id')
+ 'objectExists', ['CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id']
);
$form->assign('showTransactionId', TRUE);
}
@@ -471,7 +460,7 @@ public static function buildQuickForm(&$form) {
$form->addElement('checkbox',
'send_receipt',
ts('Send Confirmation?'), NULL,
- array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
+ ['onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"]
);
$form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
diff --git a/CRM/Event/Form/ManageEvent.php b/CRM/Event/Form/ManageEvent.php
index d285a74cc704..cd013d81cc3a 100644
--- a/CRM/Event/Form/ManageEvent.php
+++ b/CRM/Event/Form/ManageEvent.php
@@ -1,9 +1,9 @@
_single = TRUE;
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $eventInfo);
// its an update mode, do a permission check
@@ -203,12 +205,12 @@ public function preProcess() {
$ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id');
$ufCreate = CRM_ACL_API::group(CRM_Core_Permission::CREATE, NULL, 'civicrm_uf_group', $ufGroups);
$ufEdit = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_uf_group', $ufGroups);
- $checkPermission = array(
- array(
+ $checkPermission = [
+ [
'administer CiviCRM',
'manage event profiles',
- ),
- );
+ ],
+ ];
if (CRM_Core_Permission::check($checkPermission) || !empty($ufCreate) || !empty($ufEdit)) {
$this->assign('perm', TRUE);
}
@@ -218,7 +220,7 @@ public function preProcess() {
// Set Done button URL and breadcrumb. Templates go back to Manage Templates,
// otherwise go to Manage Event for new event or ManageEventEdit if event if exists.
- $breadCrumb = array();
+ $breadCrumb = [];
if (!$this->_isTemplate) {
if ($this->_id) {
$this->_doneUrl = CRM_Utils_System::url(CRM_Utils_System::currentPath(),
@@ -229,22 +231,22 @@ public function preProcess() {
$this->_doneUrl = CRM_Utils_System::url('civicrm/event/manage',
'reset=1'
);
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Manage Events'),
'url' => $this->_doneUrl,
- ),
- );
+ ],
+ ];
}
}
else {
$this->_doneUrl = CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1');
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Manage Event Templates'),
'url' => $this->_doneUrl,
- ),
- );
+ ],
+ ];
}
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -255,15 +257,15 @@ public function preProcess() {
* For edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$this->_campaignID = CRM_Utils_Array::value('campaign_id', $defaults);
}
elseif ($this->_templateId) {
- $params = array('id' => $this->_templateId);
+ $params = ['id' => $this->_templateId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$defaults['is_template'] = $this->_isTemplate;
$defaults['template_id'] = $defaults['id'];
@@ -303,44 +305,44 @@ public function buildQuickForm() {
}
if ($this->_single) {
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and Done'),
'spacing' => ' ',
'subName' => 'done',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
else {
- $buttons = array();
+ $buttons = [];
if (!$this->_first) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'back',
'name' => ts('Previous'),
'spacing' => ' ',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- );
- $buttons[] = array(
+ ];
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
}
@@ -357,7 +359,7 @@ public function endPostProcess() {
switch ($className) {
case 'Event':
$attributes = $this->getVar('_attributes');
- $subPage = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
+ $subPage = CRM_Utils_Request::retrieveComponent($attributes);
break;
case 'EventInfo':
@@ -374,7 +376,7 @@ public function endPostProcess() {
}
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
- array(1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className))
+ [1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className)]
), ts('Saved'), 'success');
$config = CRM_Core_Config::singleton();
@@ -423,7 +425,7 @@ public function getTemplateFileName() {
*/
public static function addProfileEditScripts() {
CRM_UF_Page_ProfileEditor::registerProfileScripts();
- CRM_UF_Page_ProfileEditor::registerSchemas(array('IndividualModel', 'ParticipantModel'));
+ CRM_UF_Page_ProfileEditor::registerSchemas(['IndividualModel', 'ParticipantModel']);
}
}
diff --git a/CRM/Event/Form/ManageEvent/Conference.php b/CRM/Event/Form/ManageEvent/Conference.php
index f15b66cb4b4e..2a47fa85c904 100644
--- a/CRM/Event/Form/ManageEvent/Conference.php
+++ b/CRM/Event/Form/ManageEvent/Conference.php
@@ -1,9 +1,9 @@
add('select',
'slot_label_id',
ts('Conference Slot'),
- array(
+ [
'' => ts('- select -'),
- ) + $slots,
+ ] + $slots,
FALSE
);
- $this->addEntityRef('parent_event_id', ts('Parent Event'), array(
- 'entity' => 'event',
- 'placeholder' => ts('- any -'),
- 'select' => array('minimumInputLength' => 0),
- )
- );
+ $this->addEntityRef('parent_event_id', ts('Parent Event'), [
+ 'entity' => 'Event',
+ 'placeholder' => ts('- any -'),
+ 'select' => ['minimumInputLength' => 0],
+ ]);
parent::buildQuickForm();
}
diff --git a/CRM/Event/Form/ManageEvent/Delete.php b/CRM/Event/Form/ManageEvent/Delete.php
index e74c31f70ffe..9259d1d7b4fb 100644
--- a/CRM/Event/Form/ManageEvent/Delete.php
+++ b/CRM/Event/Form/ManageEvent/Delete.php
@@ -1,9 +1,9 @@
assign('title', $this->_title);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => $this->_isTemplate ? ts('Delete Event Template') : ts('Delete Event'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -91,17 +91,17 @@ public function postProcess() {
if ($participant->find()) {
$searchURL = CRM_Utils_System::url('civicrm/event/search', 'reset=1');
CRM_Core_Session::setStatus(ts('This event cannot be deleted because there are participant records linked to it. If you want to delete this event, you must first find the participants linked to this event and delete them. You can use use CiviEvent >> Find Participants page .',
- array(1 => $searchURL)
+ [1 => $searchURL]
), ts('Deletion Error'), 'error');
return;
}
CRM_Event_BAO_Event::del($this->_id);
if ($this->_isTemplate) {
- CRM_Core_Session::setStatus(ts("'%1' has been deleted.", array(1 => $this->_title)), ts('Template Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("'%1' has been deleted.", [1 => $this->_title]), ts('Template Deleted'), 'success');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1'));
}
else {
- CRM_Core_Session::setStatus(ts("'%1' has been deleted.", array(1 => $this->_title)), ts('Event Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("'%1' has been deleted.", [1 => $this->_title]), ts('Event Deleted'), 'success');
}
}
diff --git a/CRM/Event/Form/ManageEvent/EventInfo.php b/CRM/Event/Form/ManageEvent/EventInfo.php
index 4c665a3d2972..31317c09aa8d 100644
--- a/CRM/Event/Form/ManageEvent/EventInfo.php
+++ b/CRM/Event/Form/ManageEvent/EventInfo.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'settings');
if ($this->_id) {
$this->assign('entityID', $this->_id);
@@ -112,11 +114,7 @@ public function setDefaultValues() {
$defaults['event_full_text'] = CRM_Utils_Array::value('event_full_text', $defaults, ts('This event is currently full.'));
$defaults['waitlist_text'] = CRM_Utils_Array::value('waitlist_text', $defaults, ts('This event is currently full. However you can register now and get added to a waiting list. You will be notified if spaces become available.'));
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value('start_date', $defaults), 'activityDateTime');
-
- if (!empty($defaults['end_date'])) {
- list($defaults['end_date'], $defaults['end_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['end_date'], 'activityDateTime');
- }
+ $defaults['template_id'] = $this->_templateId;
return $defaults;
}
@@ -142,11 +140,11 @@ public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::ADD) {
$eventTemplates = CRM_Event_PseudoConstant::eventTemplates();
if (CRM_Utils_System::isNull($eventTemplates) && !$this->_isTemplate) {
- $url = CRM_Utils_System::url('civicrm/admin/eventTemplate', array('reset' => 1));
- CRM_Core_Session::setStatus(ts('If you find that you are creating multiple events with similar settings, you may want to use the Event Templates feature to streamline your workflow.', array(1 => $url)), ts('Tip'), 'info');
+ $url = CRM_Utils_System::url('civicrm/admin/eventTemplate', ['reset' => 1]);
+ CRM_Core_Session::setStatus(ts('If you find that you are creating multiple events with similar settings, you may want to use the Event Templates feature to streamline your workflow.', [1 => $url]), ts('Tip'), 'info');
}
if (!CRM_Utils_System::isNull($eventTemplates)) {
- $this->add('select', 'template_id', ts('From Template'), array('' => ts('- select -')) + $eventTemplates, FALSE, array('class' => 'crm-select2 huge'));
+ $this->add('select', 'template_id', ts('From Template'), ['' => ts('- select -')] + $eventTemplates, FALSE, ['class' => 'crm-select2 huge']);
}
// Make sure this form redirects properly
$this->preventAjaxSubmit();
@@ -156,7 +154,7 @@ public function buildQuickForm() {
$this->add('text', 'title', ts('Event Title'), $attributes['event_title'], !$this->_isTemplate);
$this->addSelect('event_type_id',
- array('onChange' => "CRM.buildCustomData( 'Event', this.value );"),
+ ['onChange' => "CRM.buildCustomData( 'Event', this.value );"],
TRUE
);
@@ -167,28 +165,28 @@ public function buildQuickForm() {
}
CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
- $this->addSelect('default_role_id', array(), TRUE);
+ $this->addSelect('default_role_id', [], TRUE);
- $this->addSelect('participant_listing_id', array('placeholder' => ts('Disabled'), 'option_url' => NULL));
+ $this->addSelect('participant_listing_id', ['placeholder' => ts('Disabled'), 'option_url' => NULL]);
$this->add('textarea', 'summary', ts('Event Summary'), $attributes['summary']);
- $this->add('wysiwyg', 'description', ts('Complete Description'), $attributes['event_description'] + array('preset' => 'civievent'));
+ $this->add('wysiwyg', 'description', ts('Complete Description'), $attributes['event_description'] + ['preset' => 'civievent']);
$this->addElement('checkbox', 'is_public', ts('Public Event'));
$this->addElement('checkbox', 'is_share', ts('Allow sharing through social media?'));
$this->addElement('checkbox', 'is_map', ts('Include Map to Event Location'));
- $this->addDateTime('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDateTime'));
- $this->addDateTime('end_date', ts('End Date / Time'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'start_date', ts('Start'), [], !$this->_isTemplate, ['time' => TRUE]);
+ $this->add('datepicker', 'end_date', ts('End'), [], FALSE, ['time' => TRUE]);
- $this->add('text', 'max_participants', ts('Max Number of Participants'),
- array('onchange' => "if (this.value != '') {cj('#id-waitlist').show(); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false); showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); return;} else {cj('#id-event_full, #id-waitlist, #id-waitlist-text').hide(); return;}")
+ $this->add('number', 'max_participants', ts('Max Number of Participants'),
+ ['onchange' => "if (this.value != '') {cj('#id-waitlist').show(); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false); showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); return;} else {cj('#id-event_full, #id-waitlist, #id-waitlist-text').hide(); return;}"]
);
$this->addRule('max_participants', ts('Max participants should be a positive number'), 'positiveInteger');
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
$waitlist = 0;
if (in_array('On waitlist', $participantStatuses) and in_array('Pending from waitlist', $participantStatuses)) {
- $this->addElement('checkbox', 'has_waitlist', ts('Offer a Waitlist?'), NULL, array('onclick' => "showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false);"));
+ $this->addElement('checkbox', 'has_waitlist', ts('Offer a Waitlist?'), NULL, ['onclick' => "showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false);"]);
$this->add('textarea', 'waitlist_text', ts('Waitlist Message'), $attributes['waitlist_text']);
$waitlist = 1;
}
@@ -198,7 +196,7 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_active', ts('Is this Event Active?'));
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_EventInfo', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_EventInfo', 'formRule']);
parent::buildQuickForm();
}
@@ -212,19 +210,10 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values) {
- $errors = array();
+ $errors = [];
- if (!$values['is_template']) {
- if (CRM_Utils_System::isNull($values['start_date'])) {
- $errors['start_date'] = ts('Start Date and Time are required fields');
- }
- else {
- $start = CRM_Utils_Date::processDate($values['start_date']);
- $end = CRM_Utils_Date::processDate($values['end_date']);
- if (($end < $start) && ($end != 0)) {
- $errors['end_date'] = ts('End date should be after Start date.');
- }
- }
+ if (!empty($values['end_date']) && ($values['end_date'] < $values['start_date'])) {
+ $errors['end_date'] = ts('End date should be after Start date.');
}
//CRM-4286
@@ -242,11 +231,8 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
//format params
- $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
- $params['end_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $params),
- CRM_Utils_Array::value('end_date_time', $params),
- TRUE
- );
+ $params['start_date'] = CRM_Utils_Array::value('start_date', $params);
+ $params['end_date'] = CRM_Utils_Array::value('end_date', $params);
$params['has_waitlist'] = CRM_Utils_Array::value('has_waitlist', $params, FALSE);
$params['is_map'] = CRM_Utils_Array::value('is_map', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
@@ -268,11 +254,12 @@ public function postProcess() {
$params = array_merge(CRM_Event_BAO_Event::getTemplateDefaultValues($params['template_id']), $params);
}
- $event = CRM_Event_BAO_Event::create($params);
-
// now that we have the event’s id, do some more template-based stuff
if (!empty($params['template_id'])) {
- CRM_Event_BAO_Event::copy($params['template_id'], $event, TRUE);
+ $event = CRM_Event_BAO_Event::copy($params['template_id'], $params);
+ }
+ else {
+ $event = CRM_Event_BAO_Event::create($params);
}
$this->set('id', $event->id);
@@ -287,7 +274,7 @@ public function postProcess() {
$url = 'civicrm/event/manage';
$urlParams = 'reset=1';
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
- array(1 => $this->getTitle())
+ [1 => $this->getTitle()]
), ts('Saved'), 'success');
}
diff --git a/CRM/Event/Form/ManageEvent/Fee.php b/CRM/Event/Form/ManageEvent/Fee.php
index beaeb885bfaa..3a02919e228b 100644
--- a/CRM/Event/Form/ManageEvent/Fee.php
+++ b/CRM/Event/Form/ManageEvent/Fee.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'fee');
}
/**
@@ -68,13 +71,13 @@ public function preProcess() {
* For edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
- $parentDefaults = parent::setDefaultValues();
+ parent::setDefaultValues();
$eventId = $this->_id;
- $params = array();
- $defaults = array();
+ $params = [];
+ $defaults = [];
if (isset($eventId)) {
- $params = array('id' => $eventId);
+ $params = ['id' => $eventId];
}
CRM_Event_BAO_Event::retrieve($params, $defaults);
@@ -91,7 +94,7 @@ public function setDefaultValues() {
if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
$this->assign('isQuick', $isQuick);
$priceField = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceSetId, 'id', 'price_set_id');
- $options = array();
+ $options = [];
$priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($priceField, $options, 'weight', TRUE);
$defaults['price_field_id'] = $priceField;
$countRow = 0;
@@ -115,17 +118,15 @@ public function setDefaultValues() {
$discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($this->_id, 'civicrm_event');
if (!empty($discountedEvent)) {
$defaults['is_discount'] = $i = 1;
- $totalLables = $maxSize = $defaultDiscounts = array();
+ $totalLables = $maxSize = $defaultDiscounts = [];
foreach ($discountedEvent as $optionGroupId) {
$defaults['discount_price_set'][] = $optionGroupId;
- $name = $defaults["discount_name[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $optionGroupId, 'title');
-
- list($defaults["discount_start_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
- 'start_date', 'price_set_id'
- ));
- list($defaults["discount_end_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
- 'end_date', 'price_set_id'
- ));
+ $defaults["discount_name[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $optionGroupId, 'title');
+
+ $defaults["discount_start_date[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
+ 'start_date', 'price_set_id');
+ $defaults["discount_end_date[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
+ 'end_date', 'price_set_id');
$defaultDiscounts[] = CRM_Price_BAO_PriceSet::getSetDetail($optionGroupId);
$i++;
}
@@ -228,12 +229,12 @@ public function setDefaultValues() {
}
$this->_showHide->addToTemplate();
$this->assign('inDate', $this->_inDate);
-
if (!empty($defaults['payment_processor'])) {
- $defaults['payment_processor'] = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',',
+ $defaults['payment_processor'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
$defaults['payment_processor']
- );
+ ), '1');
}
+
return $defaults;
}
@@ -241,12 +242,11 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
-
$this->addYesNo('is_monetary',
ts('Paid Event'),
NULL,
NULL,
- array('onclick' => "return showHideByValue('is_monetary','0','event-fees','block','radio',false);")
+ ['onclick' => "return showHideByValue('is_monetary','0','event-fees','block','radio',false);"]
);
//add currency element.
@@ -255,15 +255,11 @@ public function buildQuickForm() {
$paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor();
$this->assign('paymentProcessor', $paymentProcessor);
-
- $this->addEntityRef('payment_processor', ts('Payment Processor'), array(
- 'entity' => 'PaymentProcessor',
- 'multiple' => TRUE,
- 'api' => array(
- 'params' => array('domain_id' => CRM_Core_Config::domainID()),
- ),
- 'select' => array('minimumInputLength' => 0),
- ));
+ $this->addCheckBox('payment_processor', ts('Payment Processor'),
+ array_flip($paymentProcessor),
+ NULL, NULL, NULL, NULL,
+ [' ', ' ', ' ', ' ']
+ );
// financial type
if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() ||
@@ -272,11 +268,11 @@ public function buildQuickForm() {
}
else {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
- $this->addSelect('financial_type_id', array('context' => 'search', 'options' => $financialTypes));
+ $this->addSelect('financial_type_id', ['context' => 'search', 'options' => $financialTypes]);
}
// add pay later options
$this->addElement('checkbox', 'is_pay_later', ts('Enable Pay Later option?'), NULL,
- array('onclick' => "return showHideByValue('is_pay_later','','payLaterOptions','block','radio',false);")
+ ['onclick' => "return showHideByValue('is_pay_later','','payLaterOptions','block','radio',false);"]
);
$this->addElement('textarea', 'pay_later_text', ts('Pay Later Label'),
CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'pay_later_text'),
@@ -295,21 +291,21 @@ public function buildQuickForm() {
$this->assign('price', TRUE);
}
$this->add('select', 'price_set_id', ts('Price Set'),
- array(
+ [
'' => ts('- none -'),
- ) + $price,
- NULL, array('onchange' => "return showHideByValue('price_set_id', '', 'map-field', 'block', 'select', false);")
+ ] + $price,
+ NULL, ['onchange' => "return showHideByValue('price_set_id', '', 'map-field', 'block', 'select', false);"]
);
- $default = array($this->createElement('radio', NULL, NULL, NULL, 0));
- $this->add('hidden', 'price_field_id', '', array('id' => 'price_field_id'));
+ $default = [$this->createElement('radio', NULL, NULL, NULL, 0)];
+ $this->add('hidden', 'price_field_id', '', ['id' => 'price_field_id']);
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
// label
$this->add('text', "label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
- $this->add('hidden', "price_field_value[$i]", '', array('id' => "price_field_value[$i]"));
+ $this->add('hidden', "price_field_value[$i]", '', ['id' => "price_field_value[$i]"]);
// value
$this->add('text', "value[$i]", ts('Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'));
- $this->addRule("value[$i]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $this->addRule("value[$i]", ts('Please enter a valid money value for this field (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
// default
$default[] = $this->createElement('radio', NULL, NULL, NULL, $i);
@@ -318,14 +314,14 @@ public function buildQuickForm() {
$this->addGroup($default, 'default');
$this->addElement('checkbox', 'is_discount', ts('Discounts by Signup Date?'), NULL,
- array('onclick' => "warnDiscountDel(); return showHideByValue('is_discount','','discount','block','radio',false);")
+ ['onclick' => "warnDiscountDel(); return showHideByValue('is_discount','','discount','block','radio',false);"]
);
$discountSection = $this->get('discountSection');
$this->assign('discountSection', $discountSection);
// form fields of Discount sets
- $defaultOption = array();
+ $defaultOption = [];
$_showHide = new CRM_Core_ShowHideBlocks('', '');
for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) {
@@ -346,11 +342,10 @@ public function buildQuickForm() {
isset($this->_submitValues['discount_end_date'][$i]) &&
$i < self::NUM_DISCOUNT - 1
) {
- $end_date = CRM_Utils_Date::processDate($this->_submitValues['discount_end_date'][$i]);
if (!empty($this->_submitValues['discount_end_date'][$i + 1])
&& empty($this->_submitValues['discount_start_date'][$i + 1])
) {
- list($this->_submitValues['discount_start_date'][$i + 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("+1 days $end_date")));
+ $this->_submitValues['discount_start_date'][$i + 1] = date('Y-m-d', strtotime("+1 days " . $this->_submitValues['discount_end_date'][$i]));
}
}
//Decrement by 1 of end date from next start date.
@@ -361,30 +356,23 @@ public function buildQuickForm() {
isset($this->_submitValues['discount_start_date']) &&
isset($this->_submitValues['discount_start_date'][$i])
) {
- $start_date = CRM_Utils_Date::processDate($this->_submitValues['discount_start_date'][$i]);
if (!empty($this->_submitValues['discount_start_date'][$i])
&& empty($this->_submitValues['discount_end_date'][$i - 1])
) {
- list($this->_submitValues['discount_end_date'][$i - 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("-1 days $start_date")));
+ list($this->_submitValues['discount_end_date'][$i - 1]) = date('Y-m-d', strtotime("-1 days " . $this->_submitValues['discount_start_date'][$i]));
}
}
- //discount name
$this->add('text', 'discount_name[' . $i . ']', ts('Discount Name'),
CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'title')
);
-
- $this->add('hidden', "discount_price_set[$i]", '', array('id' => "discount_price_set[$i]"));
-
- //discount start date
- $this->addDate('discount_start_date[' . $i . ']', ts('Discount Start Date'), FALSE, array('formatType' => 'activityDate'));
-
- //discount end date
- $this->addDate('discount_end_date[' . $i . ']', ts('Discount End Date'), FALSE, array('formatType' => 'activityDate'));
+ $this->add('hidden', "discount_price_set[$i]", '', ['id' => "discount_price_set[$i]"]);
+ $this->add('datepicker', 'discount_start_date[' . $i . ']', ts('Discount Start Date'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'discount_end_date[' . $i . ']', ts('Discount End Date'), [], FALSE, ['time' => FALSE]);
}
$_showHide->addToTemplate();
$this->addElement('submit', $this->getButtonName('submit'), ts('Add Discount Set to Fee Table'),
- array('class' => 'crm-form-submit cancel')
+ ['class' => 'crm-form-submit cancel']
);
if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
$deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
@@ -398,7 +386,7 @@ public function buildQuickForm() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_Fee', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_Fee', 'formRule']);
}
/**
@@ -411,7 +399,7 @@ public function addRules() {
* list of errors to be posted back to the form
*/
public static function formRule($values) {
- $errors = array();
+ $errors = [];
if (!empty($values['is_discount'])) {
$occurDiscount = array_count_values($values['discount_name']);
$countemptyrows = 0;
@@ -448,7 +436,7 @@ public static function formRule($values) {
foreach ($occurDiscount as $key => $value) {
if ($value > 1 && $key <> '') {
if ($key == $values['discount_name'][$i]) {
- $errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', array(1 => $key));
+ $errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', [1 => $key]);
}
}
}
@@ -496,7 +484,7 @@ public static function formRule($values) {
if (empty($values['price_set_id'])) {
//check fee label and amount
$check = 0;
- $optionKeys = array();
+ $optionKeys = [];
foreach ($values['label'] as $key => $val) {
if (trim($val) && trim($values['value'][$key])) {
$optionKeys[$key] = $key;
@@ -526,19 +514,24 @@ public static function formRule($values) {
$errors['pay_later_receipt'] = ts('Please enter the Pay Later instructions to be displayed to your users.');
}
}
+ else {
+ if (empty($values['payment_processor'])) {
+ $errors['payment_processor'] = ts('You have indicated that this is a paid event, but no payment option has been selected. If this is not a paid event, please select the "No" option at the top of the page. If this is a paid event, please select at least one payment processor and/or enable the pay later option.');
+ }
+ }
}
return empty($errors) ? TRUE : $errors;
}
public function buildAmountLabel() {
- $default = array();
+ $default = [];
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
// label
$this->add('text', "discounted_label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
// value
for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
- $this->add('text', "discounted_value[$i][$j]", ts('Value'), array('size' => 10));
- $this->addRule("discounted_value[$i][$j]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $this->add('text', "discounted_value[$i][$j]", ts('Value'), ['size' => 10]);
+ $this->addRule("discounted_value[$i][$j]", ts('Please enter a valid money value for this field (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
}
// default
@@ -553,7 +546,7 @@ public function buildAmountLabel() {
*/
public function postProcess() {
$eventTitle = '';
- $params = $this->exportValues();
+ $params = $this->cleanMoneyFields($this->exportValues());
$this->set('discountSection', 0);
@@ -564,7 +557,7 @@ public function postProcess() {
}
if (!empty($params['payment_processor'])) {
- $params['payment_processor'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
+ $params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['payment_processor']));
}
else {
$params['payment_processor'] = 'null';
@@ -603,17 +596,17 @@ public function postProcess() {
$labels = CRM_Utils_Array::value('label', $params);
$values = CRM_Utils_Array::value('value', $params);
$default = CRM_Utils_Array::value('default', $params);
- $options = array();
+ $options = [];
if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
- $options[] = array(
+ $options[] = [
'label' => trim($labels[$i]),
- 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])),
+ 'value' => $values[$i],
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
- );
+ ];
}
}
if (!empty($options)) {
@@ -672,8 +665,8 @@ public function postProcess() {
}
}
- $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
- $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
+ $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : [];
+ $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : [];
if (CRM_Utils_Array::value('is_discount', $params) == 1) {
// if there are discounted set of label / values,
// create custom options for them
@@ -683,26 +676,26 @@ public function postProcess() {
if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
- $discountOptions = array();
+ $discountOptions = [];
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (!empty($labels[$i]) &&
!CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))
) {
- $discountOptions[] = array(
+ $discountOptions[] = [
'label' => trim($labels[$i]),
- 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])),
+ 'value' => $values[$i][$j],
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
- );
+ ];
}
}
if (!empty($discountOptions)) {
- $fieldParams = array();
+ $fieldParams = [];
$params['default_discount_fee_id'] = NULL;
$keyCheck = $j - 1;
- $setParams = array();
+ $setParams = [];
if (empty($discountPriceSets[$keyCheck])) {
if (!$eventTitle) {
$eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
@@ -726,10 +719,10 @@ public function postProcess() {
}
else {
$priceSetID = $discountPriceSets[$j - 1];
- $setParams = array(
+ $setParams = [
'title' => $params['discount_name'][$j],
'id' => $priceSetID,
- );
+ ];
if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
$setParams['financial_type_id'] = $params['financial_type_id'];
}
@@ -763,13 +756,13 @@ public function postProcess() {
}
}
- $discountParams = array(
+ $discountParams = [
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
'price_set_id' => $priceSetID,
- 'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]),
- 'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]),
- );
+ 'start_date' => $params['discount_start_date'][$j],
+ 'end_date' => $params['discount_end_date'][$j],
+ ];
CRM_Core_BAO_Discount::add($discountParams);
}
}
@@ -817,4 +810,36 @@ public function getTitle() {
return ts('Event Fees');
}
+ /**
+ * Clean money fields in submitted params to remove formatting.
+ *
+ * @param array $params
+ *
+ * @return array
+ */
+ protected function cleanMoneyFields($params) {
+ foreach ($params['value'] as $index => $value) {
+ if (CRM_Utils_System::isNull($value)) {
+ unset($params['value'][$index]);
+ }
+ else {
+ $params['value'][$index] = CRM_Utils_Rule::cleanMoney(trim($value));
+ }
+ }
+ foreach ($params['discounted_value'] as $index => $discountedValueSet) {
+ foreach ($discountedValueSet as $innerIndex => $value) {
+ if (CRM_Utils_System::isNull($value)) {
+ unset($params['discounted_value'][$index][$innerIndex]);
+ }
+ else {
+ $params['discounted_value'][$index][$innerIndex] = CRM_Utils_Rule::cleanMoney(trim($value));
+ }
+ }
+ if (empty($params['discounted_value'][$index])) {
+ unset($params['discounted_value'][$index]);
+ }
+ }
+ return $params;
+ }
+
}
diff --git a/CRM/Event/Form/ManageEvent/Location.php b/CRM/Event/Form/ManageEvent/Location.php
index 87ba5c250036..b33eafe0a420 100644
--- a/CRM/Event/Form/ManageEvent/Location.php
+++ b/CRM/Event/Form/ManageEvent/Location.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'location');
$this->_values = $this->get('values');
if ($this->_id && empty($this->_values)) {
//get location values.
- $params = array(
+ $params = [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- );
+ ];
$this->_values = CRM_Core_BAO_Location::getValues($params);
//get event values.
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $this->_values);
$this->set('values', $this->_values);
}
@@ -124,7 +126,7 @@ public function setDefaultValues() {
* Add local and global form rules.
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_Location', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_Location', 'formRule']);
}
/**
@@ -147,17 +149,14 @@ public static function formRule($fields) {
* Function to build location block.
*/
public function buildQuickForm() {
- //load form for child blocks
- if ($this->_addBlockName) {
- $className = "CRM_Contact_Form_Edit_{$this->_addBlockName}";
- return $className::buildQuickForm($this);
- }
+ CRM_Contact_Form_Edit_Address::buildQuickForm($this, 1);
+ CRM_Contact_Form_Edit_Email::buildQuickForm($this, 1);
+ CRM_Contact_Form_Edit_Email::buildQuickForm($this, 2);
+ CRM_Contact_Form_Edit_Phone::buildQuickForm($this, 1);
+ CRM_Contact_Form_Edit_Phone::buildQuickForm($this, 2);
$this->applyFilter('__ALL__', 'trim');
- //build location blocks.
- CRM_Contact_Form_Location::buildQuickForm($this);
-
//fix for CRM-1971
$this->assign('action', $this->_action);
@@ -184,20 +183,19 @@ public function buildQuickForm() {
$locationEvents = array_unique($locationEvents);
}
- $events = array();
if (!empty($locationEvents)) {
$this->assign('locEvents', TRUE);
- $optionTypes = array(
+ $optionTypes = [
'1' => ts('Create new location'),
'2' => ts('Use existing location'),
- );
+ ];
$this->addRadio('location_option', ts("Choose Location"), $optionTypes);
if (!isset($locationEvents[$this->_oldLocBlockId]) || (!$this->_oldLocBlockId)) {
- $locationEvents = array('' => ts('- select -')) + $locationEvents;
+ $locationEvents = ['' => ts('- select -')] + $locationEvents;
}
- $this->add('select', 'loc_event_id', ts('Use Location'), $locationEvents, FALSE, array('class' => 'crm-select2'));
+ $this->add('select', 'loc_event_id', ts('Use Location'), $locationEvents, FALSE, ['class' => 'crm-select2']);
}
$this->addElement('advcheckbox', 'is_show_location', ts('Show Location?'));
parent::buildQuickForm();
@@ -231,7 +229,8 @@ public function postProcess() {
);
}
- // if 'create new loc' optioin is selected OR selected new loc is different
+ $this->_values['address'] = $this->_values['phone'] = $this->_values['email'] = [];
+ // if 'create new loc' option is selected OR selected new loc is different
// from old one, go ahead and delete the old loc provided thats not being
// used by any other event
if ($this->_oldLocBlockId && $deleteOldBlock) {
@@ -243,11 +242,11 @@ public function postProcess() {
$params['entity_id'] = $this->_id;
$defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
- foreach (array(
- 'address',
- 'phone',
- 'email',
- ) as $block) {
+ foreach ([
+ 'address',
+ 'phone',
+ 'email',
+ ] as $block) {
if (empty($params[$block]) || !is_array($params[$block])) {
continue;
}
@@ -256,6 +255,9 @@ public function postProcess() {
$values['is_primary'] = 1;
}
$values['location_type_id'] = ($defaultLocationType->id) ? $defaultLocationType->id : 1;
+ if (isset($this->_values[$block][$count])) {
+ $values['id'] = $this->_values[$block][$count]['id'];
+ }
}
}
diff --git a/CRM/Event/Form/ManageEvent/Registration.php b/CRM/Event/Form/ManageEvent/Registration.php
index 9634feef78f8..0c62605713f5 100644
--- a/CRM/Event/Form/ManageEvent/Registration.php
+++ b/CRM/Event/Form/ManageEvent/Registration.php
@@ -1,9 +1,9 @@
_profileBottomNumAdd = CRM_Utils_Array::value('addProfileNumAdd', $_GET, 0);
parent::preProcess();
+ $this->assign('selectedChild', 'registration');
$this->assign('addProfileBottom', $this->_addProfileBottom);
$this->assign('profileBottomNum', $this->_profileBottomNum);
@@ -96,23 +97,23 @@ public function setDefaultValues() {
$this->setShowHide($defaults);
if (isset($eventId)) {
- $params = array('id' => $eventId);
+ $params = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
- $ufJoinParams = array(
+ $ufJoinParams = [
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent',
'entity_id' => $eventId,
- );
+ ];
list($defaults['custom_pre_id'],
$defaults['custom_post']
) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
// Get the id for the event registration profile
- $eventRegistrationIdParams = $eventRegistrationIdDefaults = array(
+ $eventRegistrationIdParams = $eventRegistrationIdDefaults = [
'name' => 'event_registration',
- );
+ ];
CRM_Core_BAO_UFGroup::retrieve($eventRegistrationIdParams, $eventRegistrationIdDefaults);
// Set event registration as the default profile if none selected
@@ -142,11 +143,11 @@ public function setDefaultValues() {
if (!empty($defaults['is_multiple_registrations'])) {
// CRM-4377: set additional participants’ profiles – set to ‘none’ if explicitly unset (non-active)
- $ufJoinAddParams = array(
+ $ufJoinAddParams = [
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent_Additional',
'entity_id' => $eventId,
- );
+ ];
list($defaults['additional_custom_pre_id'],
$defaults['additional_custom_post']
@@ -178,16 +179,6 @@ public function setDefaultValues() {
$defaults['thankyou_title'] = CRM_Utils_Array::value('thankyou_title', $defaults, ts('Thank You for Registering'));
$defaults['approval_req_text'] = CRM_Utils_Array::value('approval_req_text', $defaults, ts('Participation in this event requires approval. Submit your registration request here. Once approved, you will receive an email with a link to a web page where you can complete the registration process.'));
- if (!empty($defaults['registration_start_date'])) {
- list($defaults['registration_start_date'], $defaults['registration_start_date_time'])
- = CRM_Utils_Date::setDateDefaults($defaults['registration_start_date'], 'activityDateTime');
- }
-
- if (!empty($defaults['registration_end_date'])) {
- list($defaults['registration_end_date'], $defaults['registration_end_date_time'])
- = CRM_Utils_Date::setDateDefaults($defaults['registration_end_date'], 'activityDateTime');
- }
-
return $defaults;
}
@@ -200,7 +191,7 @@ public function setDefaultValues() {
* @return void
*/
public function setShowHide($defaults) {
- $this->_showHide = new CRM_Core_ShowHideBlocks(array('registration' => 1),
+ $this->_showHide = new CRM_Core_ShowHideBlocks(['registration' => 1],
''
);
if (empty($defaults)) {
@@ -237,27 +228,27 @@ public function buildQuickForm() {
'is_online_registration',
ts('Allow Online Registration'),
NULL,
- array(
+ [
'onclick' => "return showHideByValue('is_online_registration'," .
"''," .
"'registration_blocks'," .
"'block'," .
"'radio'," .
"false );",
- )
+ ]
);
$this->add('text', 'registration_link_text', ts('Registration Link Text'));
if (!$this->_isTemplate) {
- $this->addDateTime('registration_start_date', ts('Registration Start Date'), FALSE, array('formatType' => 'activityDateTime'));
- $this->addDateTime('registration_end_date', ts('Registration End Date'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'registration_start_date', ts('Registration Start Date'), [], FALSE, ['time' => TRUE]);
+ $this->add('datepicker', 'registration_end_date', ts('Registration End Date'), [], FALSE, ['time' => TRUE]);
}
- $params = array(
+ $params = [
'used' => 'Supervised',
'contact_type' => 'Individual',
- );
+ ];
$dedupeRuleFields = CRM_Dedupe_BAO_Rule::dedupeRuleFields($params);
foreach ($dedupeRuleFields as $key => $fields) {
@@ -271,7 +262,7 @@ public function buildQuickForm() {
// CRM-17745: Make maximum additional participants configurable
$numericOptions = CRM_Core_SelectValues::getNumericOptions(1, 9);
- $this->add('select', 'max_additional_participants', ts('Maximum additional participants'), $numericOptions, FALSE, array('class' => 'required'));
+ $this->add('select', 'max_additional_participants', ts('Maximum additional participants'), $numericOptions, FALSE, ['class' => 'required']);
$this->addElement('checkbox',
'allow_same_participant_emails',
@@ -279,9 +270,9 @@ public function buildQuickForm() {
);
$this->assign('ruleFields', json_encode($ruleFields));
- $dedupeRules = array(
+ $dedupeRules = [
'' => '- Unsupervised rule -',
- );
+ ];
$dedupeRules += CRM_Dedupe_BAO_RuleGroup::getByType('Individual');
$this->add('select', 'dedupe_rule_group_id', ts('Duplicate matching rule'), $dedupeRules);
@@ -291,14 +282,14 @@ public function buildQuickForm() {
'requires_approval',
ts('Require participant approval?'),
NULL,
- array('onclick' => "return showHideByValue('requires_approval', '', 'id-approval-text', 'table-row', 'radio', false);")
+ ['onclick' => "return showHideByValue('requires_approval', '', 'id-approval-text', 'table-row', 'radio', false);"]
);
$this->add('textarea', 'approval_req_text', ts('Approval message'), $attributes['approval_req_text']);
}
$this->add('text', 'expiration_time', ts('Pending participant expiration (hours)'));
$this->addRule('expiration_time', ts('Please enter the number of hours (as an integer).'), 'integer');
- $this->addField('allow_selfcancelxfer', array('label' => ts('Allow self-service cancellation or transfer?'), 'type' => 'advcheckbox'));
+ $this->addField('allow_selfcancelxfer', ['label' => ts('Allow self-service cancellation or transfer?'), 'type' => 'advcheckbox']);
$this->add('text', 'selfcancelxfer_time', ts('Cancellation or transfer time limit (hours)'));
$this->addRule('selfcancelxfer_time', ts('Please enter the number of hours (as an integer).'), 'integer');
self::buildRegistrationBlock($this);
@@ -316,7 +307,7 @@ public function buildQuickForm() {
*
*/
public function buildRegistrationBlock(&$form) {
- $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'intro_text') + array('class' => 'collapsed', 'preset' => 'civievent');
+ $attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'intro_text') + ['class' => 'collapsed', 'preset' => 'civievent'];
$form->add('wysiwyg', 'intro_text', ts('Introductory Text'), $attributes);
$form->add('wysiwyg', 'footer_text', ts('Footer Text'), $attributes);
@@ -357,17 +348,17 @@ public function buildMultipleProfileBottom(&$form, $count, $prefix = '', $label
* ['allowCoreTypes' => array, 'allowSubTypes' => array, 'profileEntities' => array]
*/
public static function getProfileSelectorTypes() {
- $configs = array(
- 'allowCoreTypes' => array(),
- 'allowSubTypes' => array(),
- 'profileEntities' => array(),
- 'usedFor' => array(),
- );
-
- $configs['allowCoreTypes'] = array_merge(array(
- 'Contact',
- 'Individual',
- ), CRM_Contact_BAO_ContactType::subTypes('Individual'));
+ $configs = [
+ 'allowCoreTypes' => [],
+ 'allowSubTypes' => [],
+ 'profileEntities' => [],
+ 'usedFor' => [],
+ ];
+
+ $configs['allowCoreTypes'] = array_merge([
+ 'Contact',
+ 'Individual',
+ ], CRM_Contact_BAO_ContactType::subTypes('Individual'));
$configs['allowCoreTypes'][] = 'Participant';
if (CRM_Core_Permission::check('manage event profiles') && !CRM_Core_Permission::check('administer CiviCRM')) {
$configs['usedFor'][] = 'CiviEvent';
@@ -377,16 +368,16 @@ public static function getProfileSelectorTypes() {
if ($id) {
$participantEventType = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $id, 'event_type_id', 'id');
$participantRole = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $id, 'default_role_id');
- $configs['allowSubTypes']['ParticipantEventName'] = array($id);
- $configs['allowSubTypes']['ParticipantEventType'] = array($participantEventType);
- $configs['allowSubTypes']['ParticipantRole'] = array($participantRole);
+ $configs['allowSubTypes']['ParticipantEventName'] = [$id];
+ $configs['allowSubTypes']['ParticipantEventType'] = [$participantEventType];
+ $configs['allowSubTypes']['ParticipantRole'] = [$participantRole];
}
- $configs['profileEntities'][] = array('entity_name' => 'contact_1', 'entity_type' => 'IndividualModel');
- $configs['profileEntities'][] = array(
+ $configs['profileEntities'][] = ['entity_name' => 'contact_1', 'entity_type' => 'IndividualModel'];
+ $configs['profileEntities'][] = [
'entity_name' => 'participant_1',
'entity_type' => 'ParticipantModel',
'entity_sub_type' => '*',
- );
+ ];
return $configs;
}
@@ -403,11 +394,11 @@ public function buildConfirmationBlock(&$form) {
$is_monetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_id, 'is_monetary');
$form->assign('is_monetary', $is_monetary);
if ($is_monetary == "0") {
- $form->addYesNo('is_confirm_enabled', ts('Use a confirmation screen?'), NULL, NULL, array('onclick' => "return showHideByValue('is_confirm_enabled','','confirm_screen_settings','block','radio',false);"));
+ $form->addYesNo('is_confirm_enabled', ts('Use a confirmation screen?'), NULL, NULL, ['onclick' => "return showHideByValue('is_confirm_enabled','','confirm_screen_settings','block','radio',false);"]);
}
$form->add('text', 'confirm_title', ts('Title'), $attributes['confirm_title']);
- $form->add('wysiwyg', 'confirm_text', ts('Introductory Text'), $attributes['confirm_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
- $form->add('wysiwyg', 'confirm_footer_text', ts('Footer Text'), $attributes['confirm_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
+ $form->add('wysiwyg', 'confirm_text', ts('Introductory Text'), $attributes['confirm_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
+ $form->add('wysiwyg', 'confirm_footer_text', ts('Footer Text'), $attributes['confirm_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
}
/**
@@ -419,7 +410,7 @@ public function buildConfirmationBlock(&$form) {
public function buildMailBlock(&$form) {
$form->registerRule('emailList', 'callback', 'emailList', 'CRM_Utils_Rule');
$attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
- $form->addYesNo('is_email_confirm', ts('Send Confirmation Email?'), NULL, NULL, array('onclick' => "return showHideByValue('is_email_confirm','','confirmEmail','block','radio',false);"));
+ $form->addYesNo('is_email_confirm', ts('Send Confirmation Email?'), NULL, NULL, ['onclick' => "return showHideByValue('is_email_confirm','','confirmEmail','block','radio',false);"]);
$form->add('textarea', 'confirm_email_text', ts('Text'), $attributes['confirm_email_text']);
$form->add('text', 'cc_confirm', ts('CC Confirmation To'), CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'cc_confirm'));
$form->addRule('cc_confirm', ts('Please enter a valid list of comma delimited email addresses'), 'emailList');
@@ -436,8 +427,8 @@ public function buildMailBlock(&$form) {
public function buildThankYouBlock(&$form) {
$attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
$form->add('text', 'thankyou_title', ts('Title'), $attributes['thankyou_title']);
- $form->add('wysiwyg', 'thankyou_text', ts('Introductory Text'), $attributes['thankyou_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
- $form->add('wysiwyg', 'thankyou_footer_text', ts('Footer Text'), $attributes['thankyou_text'] + array('class' => 'collapsed', 'preset' => 'civievent'));
+ $form->add('wysiwyg', 'thankyou_text', ts('Introductory Text'), $attributes['thankyou_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
+ $form->add('wysiwyg', 'thankyou_footer_text', ts('Footer Text'), $attributes['thankyou_text'] + ['class' => 'collapsed', 'preset' => 'civievent']);
}
/**
@@ -450,7 +441,7 @@ public function addRules() {
if ($this->_addProfileBottom || $this->_addProfileBottomAdd) {
return;
}
- $this->addFormRule(array('CRM_Event_Form_ManageEvent_Registration', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_ManageEvent_Registration', 'formRule'], $this);
}
/**
@@ -482,26 +473,21 @@ public static function formRule($values, $files, $form) {
}
}
- if (
- isset($values['registration_start_date']) &&
- isset($values['registration_end_date'])
- ) {
- $start = CRM_Utils_Date::processDate($values['registration_start_date']);
- $end = CRM_Utils_Date::processDate($values['registration_end_date']);
- if ($end < $start) {
+ if (isset($values['registration_start_date']) && isset($values['registration_end_date'])) {
+ if ($values['registration_end_date'] < $values['registration_start_date']) {
$errorMsg['registration_end_date'] = ts('Registration end date should be after Registration start date');
}
}
//check that the selected profiles have either firstname+lastname or email required
- $profileIds = array(
+ $profileIds = [
CRM_Utils_Array::value('custom_pre_id', $values),
CRM_Utils_Array::value('custom_post_id', $values),
- );
- $additionalProfileIds = array(
+ ];
+ $additionalProfileIds = [
CRM_Utils_Array::value('additional_custom_pre_id', $values),
CRM_Utils_Array::value('additional_custom_post_id', $values),
- );
+ ];
//additional profile fields default to main if not set
if (!is_numeric($additionalProfileIds[0])) {
$additionalProfileIds[0] = $profileIds[0];
@@ -525,7 +511,7 @@ public static function formRule($values, $files, $form) {
$additionalCustomPreId = $additionalCustomPostId = NULL;
$isPreError = $isPostError = TRUE;
if (!empty($values['allow_same_participant_emails']) && !empty($values['is_multiple_registrations'])) {
- $types = array_merge(array('Individual'), CRM_Contact_BAO_ContactType::subTypes('Individual'));
+ $types = array_merge(['Individual'], CRM_Contact_BAO_ContactType::subTypes('Individual'));
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types);
//check for additional custom pre profile
@@ -651,7 +637,7 @@ public static function formRule($values, $files, $form) {
* @return bool
*/
public static function getEmailFields($profileIds) {
- $emailFields = array();
+ $emailFields = [];
foreach ($profileIds as $profileId) {
if ($profileId && is_numeric($profileId)) {
$fields = CRM_Core_BAO_UFGroup::getFields($profileId);
@@ -672,7 +658,7 @@ public static function getEmailFields($profileIds) {
* @return bool
*/
public static function isProfileComplete($profileIds) {
- $profileReqFields = array();
+ $profileReqFields = [];
foreach ($profileIds as $profileId) {
if ($profileId && is_numeric($profileId)) {
$fields = CRM_Core_BAO_UFGroup::getFields($profileId);
@@ -708,21 +694,21 @@ public static function isProfileComplete($profileIds) {
*/
public static function canProfilesDedupe($profileIds, $rgId = 0) {
// find the unsupervised rule
- $rgParams = array(
+ $rgParams = [
'used' => 'Unsupervised',
'contact_type' => 'Individual',
- );
+ ];
if ($rgId > 0) {
$rgParams['id'] = $rgId;
}
$activeRg = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($rgParams);
// get the combinations that could be a match for the rule
- $okCombos = $combos = array();
+ $okCombos = $combos = [];
CRM_Dedupe_BAO_RuleGroup::combos($activeRg[0], $activeRg[1], $combos);
// create an index of what combinations involve each field
- $index = array();
+ $index = [];
foreach ($combos as $comboid => $combo) {
foreach ($combo as $cfield) {
$index[$cfield][$comboid] = TRUE;
@@ -732,7 +718,7 @@ public static function canProfilesDedupe($profileIds, $rgId = 0) {
}
// get profiles and see if they have the necessary combos
- $profileReqFields = array();
+ $profileReqFields = [];
foreach ($profileIds as $profileId) {
if ($profileId && is_numeric($profileId)) {
$fields = CRM_Core_BAO_UFGroup::getFields($profileId);
@@ -808,7 +794,8 @@ public function postProcess() {
// format params
$params['is_online_registration'] = CRM_Utils_Array::value('is_online_registration', $params, FALSE);
- $params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE); // CRM-11182
+ // CRM-11182
+ $params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE);
$params['is_multiple_registrations'] = CRM_Utils_Array::value('is_multiple_registrations', $params, FALSE);
$params['allow_same_participant_emails'] = CRM_Utils_Array::value('allow_same_participant_emails', $params, FALSE);
$params['requires_approval'] = CRM_Utils_Array::value('requires_approval', $params, FALSE);
@@ -821,31 +808,20 @@ public function postProcess() {
$params['selfcancelxfer_time'] = !empty($params['selfcancelxfer_time']) ? $params['selfcancelxfer_time'] : 0;
}
- if (!$this->_isTemplate) {
- $params['registration_start_date'] = CRM_Utils_Date::processDate($params['registration_start_date'],
- $params['registration_start_date_time'],
- TRUE
- );
- $params['registration_end_date'] = CRM_Utils_Date::processDate($params['registration_end_date'],
- $params['registration_end_date_time'],
- TRUE
- );
- }
-
CRM_Event_BAO_Event::add($params);
// also update the ProfileModule tables
- $ufJoinParams = array(
+ $ufJoinParams = [
'is_active' => 1,
'module' => 'CiviEvent',
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
- );
+ ];
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
- $uf = array();
+ $uf = [];
$wt = 2;
if (!empty($params['custom_pre_id'])) {
$uf[1] = $params['custom_pre_id'];
@@ -869,17 +845,17 @@ public function postProcess() {
}
}
// also update the ProfileModule tables
- $ufJoinParamsAdd = array(
+ $ufJoinParamsAdd = [
'is_active' => 1,
'module' => 'CiviEvent_Additional',
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
- );
+ ];
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParamsAdd);
if (!empty($params['is_multiple_registrations'])) {
- $ufAdd = array();
+ $ufAdd = [];
$wtAdd = 2;
if (array_key_exists('additional_custom_pre_id', $params)) {
@@ -907,7 +883,7 @@ public function postProcess() {
}
if (!empty($params['additional_custom_post_id_multiple'])) {
- $additionalPostMultiple = array();
+ $additionalPostMultiple = [];
foreach ($params['additional_custom_post_id_multiple'] as $key => $value) {
if (is_null($value) && !empty($params['custom_post_id'])) {
$additionalPostMultiple[$key] = $params['custom_post_id'];
@@ -936,14 +912,14 @@ public function postProcess() {
}
// get the profiles to evaluate what they collect
- $profileIds = array(
+ $profileIds = [
CRM_Utils_Array::value('custom_pre_id', $params),
CRM_Utils_Array::value('custom_post_id', $params),
- );
- $additionalProfileIds = array(
+ ];
+ $additionalProfileIds = [
CRM_Utils_Array::value('additional_custom_pre_id', $params),
CRM_Utils_Array::value('additional_custom_post_id', $params),
- );
+ ];
// additional profile fields default to main if not set
if (!is_numeric($additionalProfileIds[0])) {
$additionalProfileIds[0] = $profileIds[0];
@@ -988,7 +964,7 @@ public function postProcess() {
}
}
if ($cantDedupe) {
- CRM_Core_Session::setStatus($cantDedupe, $dedupeTitle, 'alert dedupenotify', array('expires' => 0));
+ CRM_Core_Session::setStatus($cantDedupe, $dedupeTitle, 'alert dedupenotify', ['expires' => 0]);
}
// Update tab "disabled" css class
diff --git a/CRM/Event/Form/ManageEvent/Repeat.php b/CRM/Event/Form/ManageEvent/Repeat.php
index f031f006e0be..f02716591d66 100644
--- a/CRM/Event/Form/ManageEvent/Repeat.php
+++ b/CRM/Event/Form/ManageEvent/Repeat.php
@@ -14,17 +14,19 @@ class CRM_Event_Form_ManageEvent_Repeat extends CRM_Event_Form_ManageEvent {
/**
* Parent Event Start Date.
+ * @var string
*/
protected $_parentEventStartDate = NULL;
/**
* Parent Event End Date.
+ * @var string
*/
protected $_parentEventEndDate = NULL;
-
public function preProcess() {
parent::preProcess();
+ $this->assign('selectedChild', 'repeat');
$this->assign('currentEventId', $this->_id);
$checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($this->_id, 'civicrm_event');
@@ -35,13 +37,13 @@ public function preProcess() {
*/
//Get all connected event ids
$allEventIdsArray = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($checkParentExistsForThisId, 'civicrm_event');
- $allEventIds = array();
+ $allEventIds = [];
if (!empty($allEventIdsArray)) {
foreach ($allEventIdsArray as $key => $val) {
$allEventIds[] = $val['id'];
}
if (!empty($allEventIds)) {
- $params = array();
+ $params = [];
$query = "
SELECT *
FROM civicrm_event
@@ -53,7 +55,7 @@ public function preProcess() {
$permissions = CRM_Event_BAO_Event::checkPermission();
while ($dao->fetch()) {
if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
- $manageEvent[$dao->id] = array();
+ $manageEvent[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
}
}
@@ -62,9 +64,9 @@ public function preProcess() {
}
}
- $parentEventParams = array('id' => $this->_id);
- $parentEventValues = array();
- $parentEventReturnProperties = array('start_date', 'end_date');
+ $parentEventParams = ['id' => $this->_id];
+ $parentEventValues = [];
+ $parentEventReturnProperties = ['start_date', 'end_date'];
$parentEventAttributes = CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $parentEventParams, $parentEventValues, $parentEventReturnProperties);
$this->_parentEventStartDate = $parentEventAttributes->start_date;
$this->_parentEventEndDate = $parentEventAttributes->end_date;
@@ -78,11 +80,10 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
//Always pass current event's start date by default
- $currentEventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'start_date', 'id');
- list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($currentEventStartDate, 'activityDateTime');
+ $defaults['repetition_start_date'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'start_date', 'id');
$recurringEntityDefaults = CRM_Core_Form_RecurringEntity::setDefaultValues();
return array_merge($defaults, $recurringEntityDefaults);
}
@@ -96,10 +97,10 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
if ($this->_parentEventStartDate && $this->_parentEventEndDate) {
$interval = CRM_Core_BAO_RecurringEntity::getInterval($this->_parentEventStartDate, $this->_parentEventEndDate);
- $params['intervalDateColumns'] = array('end_date' => $interval);
+ $params['intervalDateColumns'] = ['end_date' => $interval];
}
- $params['dateColumns'] = array('start_date');
- $params['excludeDateRangeColumns'] = array('start_date', 'end_date');
+ $params['dateColumns'] = ['start_date'];
+ $params['excludeDateRangeColumns'] = ['start_date', 'end_date'];
$params['entity_table'] = 'civicrm_event';
$params['entity_id'] = $this->_id;
@@ -110,46 +111,46 @@ public function postProcess() {
unset($params['id']);
$url = 'civicrm/event/manage/repeat';
- $urlParams = "action=update&reset=1&id={$this->_id}";
+ $urlParams = "action=update&reset=1&id={$this->_id}&selectedChild=repeat";
- $linkedEntities = array(
- array(
+ $linkedEntities = [
+ [
'table' => 'civicrm_price_set_entity',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => FALSE,
- ),
- array(
+ ],
+ [
'table' => 'civicrm_uf_join',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => FALSE,
- ),
- array(
+ ],
+ [
'table' => 'civicrm_tell_friend',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => TRUE,
- ),
- array(
+ ],
+ [
'table' => 'civicrm_pcp_block',
- 'findCriteria' => array(
+ 'findCriteria' => [
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
- ),
- 'linkedColumns' => array('entity_id'),
+ ],
+ 'linkedColumns' => ['entity_id'],
'isRecurringEntityRecord' => TRUE,
- ),
- );
+ ],
+ ];
CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_event', $linkedEntities);
CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
}
@@ -168,8 +169,8 @@ public function postProcess() {
*
* @return array
*/
- static public function getParticipantCountforEvent($listOfRelatedEntities = array()) {
- $participantDetails = array();
+ public static function getParticipantCountforEvent($listOfRelatedEntities = []) {
+ $participantDetails = [];
if (!empty($listOfRelatedEntities)) {
$implodeRelatedEntities = implode(',', array_map(function ($entity) {
return $entity['id'];
@@ -192,15 +193,15 @@ static public function getParticipantCountforEvent($listOfRelatedEntities = arra
}
/**
- * This function checks if there was any registraion for related event ids,
- * and returns array of ids with no regsitrations
+ * This function checks if there was any registration for related event ids,
+ * and returns array of ids with no registrations
*
- * @param string or int or object... $eventID
+ * @param mixed $eventID string, int or object
*
* @return array
*/
public static function checkRegistrationForEvents($eventID) {
- $eventIdsWithNoRegistration = array();
+ $eventIdsWithNoRegistration = [];
if ($eventID) {
$getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($eventID, 'civicrm_event', TRUE);
$participantDetails = CRM_Event_Form_ManageEvent_Repeat::getParticipantCountforEvent($getRelatedEntities);
diff --git a/CRM/Event/Form/ManageEvent/ScheduleReminders.php b/CRM/Event/Form/ManageEvent/ScheduleReminders.php
index aa8e69182bd0..483f275de624 100644
--- a/CRM/Event/Form/ManageEvent/ScheduleReminders.php
+++ b/CRM/Event/Form/ManageEvent/ScheduleReminders.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'reminder');
$setTab = CRM_Utils_Request::retrieve('setTab', 'Int', $this, FALSE, 0);
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => ($this->_isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
- )));
+ ]));
$reminderList = CRM_Core_BAO_ActionSchedule::getList(FALSE, $mapping, $this->_id);
if ($reminderList && is_array($reminderList)) {
// Add action links to each of the reminders
@@ -70,7 +71,7 @@ public function preProcess() {
$format['action'] = CRM_Core_Action::formLink(
$links,
$action,
- array('id' => $format['id']),
+ ['id' => $format['id']],
ts('more'),
FALSE,
'actionSchedule.manage.action',
diff --git a/CRM/Event/Form/ManageEvent/TabHeader.php b/CRM/Event/Form/ManageEvent/TabHeader.php
index a818a54e481f..c966147e4fc7 100644
--- a/CRM/Event/Form/ManageEvent/TabHeader.php
+++ b/CRM/Event/Form/ManageEvent/TabHeader.php
@@ -1,9 +1,9 @@
assign('selectedChild', CRM_Utils_Request::retrieve('selectedChild', 'Alphanumeric', $form));
+
$tabs = $form->get('tabHeader');
if (!$tabs || empty($_GET['reset'])) {
$tabs = self::process($form);
@@ -52,11 +55,11 @@ public static function build(&$form) {
$form->assign_by_ref('tabHeader', $tabs);
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header')
- ->addSetting(array(
- 'tabSettings' => array(
+ ->addSetting([
+ 'tabSettings' => [
'active' => self::getCurrentTab($tabs),
- ),
- ));
+ ],
+ ]);
CRM_Event_Form_ManageEvent::addProfileEditScripts();
return $tabs;
}
@@ -72,26 +75,26 @@ public static function process(&$form) {
return NULL;
}
- $default = array(
+ $default = [
'link' => NULL,
'valid' => TRUE,
'active' => TRUE,
'current' => FALSE,
'class' => 'ajaxForm',
- );
+ ];
- $tabs = array();
- $tabs['settings'] = array('title' => ts('Info and Settings'), 'class' => 'ajaxForm livePage') + $default;
- $tabs['location'] = array('title' => ts('Event Location')) + $default;
- $tabs['fee'] = array('title' => ts('Fees')) + $default;
- $tabs['registration'] = array('title' => ts('Online Registration')) + $default;
+ $tabs = [];
+ $tabs['settings'] = ['title' => ts('Info and Settings'), 'class' => 'ajaxForm livePage'] + $default;
+ $tabs['location'] = ['title' => ts('Event Location')] + $default;
+ $tabs['fee'] = ['title' => ts('Fees')] + $default;
+ $tabs['registration'] = ['title' => ts('Online Registration')] + $default;
if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
- $tabs['reminder'] = array('title' => ts('Schedule Reminders'), 'class' => 'livePage') + $default;
+ $tabs['reminder'] = ['title' => ts('Schedule Reminders'), 'class' => 'livePage'] + $default;
}
- $tabs['conference'] = array('title' => ts('Conference Slots')) + $default;
- $tabs['friend'] = array('title' => ts('Tell a Friend')) + $default;
- $tabs['pcp'] = array('title' => ts('Personal Campaigns')) + $default;
- $tabs['repeat'] = array('title' => ts('Repeat')) + $default;
+ $tabs['conference'] = ['title' => ts('Conference Slots')] + $default;
+ $tabs['friend'] = ['title' => ts('Tell a Friend')] + $default;
+ $tabs['pcp'] = ['title' => ts('Personal Campaigns')] + $default;
+ $tabs['repeat'] = ['title' => ts('Repeat')] + $default;
// Repeat tab must refresh page when switching repeat mode so js & vars will get set-up
if (!$form->_isRepeatingEvent) {
@@ -107,9 +110,9 @@ public static function process(&$form) {
$eventID = $form->getVar('_id');
if ($eventID) {
// disable tabs based on their configuration status
- $eventNameMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $eventNameMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
- )));
+ ]));
$sql = "
SELECT e.loc_block_id as is_location, e.is_online_registration, e.is_monetary, taf.is_active, pcp.is_active as is_pcp, sch.id as is_reminder, re.id as is_repeating_event
FROM civicrm_event e
@@ -121,10 +124,10 @@ public static function process(&$form) {
";
//Check if repeat is configured
$eventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($eventID, 'civicrm_event');
- $params = array(
- 1 => array($eventID, 'Integer'),
- 2 => array($eventNameMapping->getId(), 'Integer'),
- );
+ $params = [
+ 1 => [$eventID, 'Integer'],
+ 2 => [$eventNameMapping->getId(), 'Integer'],
+ ];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if (!$dao->fetch()) {
CRM_Core_Error::fatal();
@@ -155,7 +158,7 @@ public static function process(&$form) {
// see if any other modules want to add any tabs
// note: status of 'valid' flag of any injected tab, needs to be taken care in the hook implementation.
CRM_Utils_Hook::tabset('civicrm/event/manage', $tabs,
- array('event_id' => $eventID));
+ ['event_id' => $eventID]);
$fullName = $form->getVar('_name');
$className = CRM_Utils_String::getClassName($fullName);
@@ -165,7 +168,7 @@ public static function process(&$form) {
switch ($className) {
case 'Event':
$attributes = $form->getVar('_attributes');
- $class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
+ $class = CRM_Utils_Request::retrieveComponent($attributes);
break;
case 'EventInfo':
@@ -235,7 +238,7 @@ public static function getCurrentTab($tabs) {
if (is_array($tabs)) {
foreach ($tabs as $subPage => $pageVal) {
- if ($pageVal['current'] === TRUE) {
+ if (CRM_Utils_Array::value('current', $pageVal) === TRUE) {
$current = $subPage;
break;
}
diff --git a/CRM/Event/Form/Participant.php b/CRM/Event/Form/Participant.php
index dd0244e4db21..0b0b31e0dcf2 100644
--- a/CRM/Event/Form/Participant.php
+++ b/CRM/Event/Form/Participant.php
@@ -1,9 +1,9 @@
contactID
*
* The id of the contact associated with this participation.
*
* @var int
+ * @deprecated
*/
public $_contactId;
@@ -112,52 +112,61 @@ class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment
/**
* If event is paid or unpaid.
+ * @var bool
*/
public $_isPaidEvent;
/**
* Page action.
+ * @var int
*/
public $_action;
/**
* Role Id.
+ * @var int
*/
protected $_roleId = NULL;
/**
* Event Type Id.
+ * @var int
*/
protected $_eventTypeId = NULL;
/**
* Participant status Id.
+ * @var int
*/
protected $_statusId = NULL;
/**
* Cache all the participant statuses.
+ * @var array
*/
protected $_participantStatuses;
/**
* Participant mode.
+ * @var string
*/
public $_mode = NULL;
/**
* Event ID preselect.
+ * @var int
*/
public $_eID = NULL;
/**
* Line Item for Price Set.
+ * @var array
*/
public $_lineItem = NULL;
/**
* Contribution mode for event registration for offline mode.
- *
+ * @var string
* @deprecated
*/
public $_contributeMode = 'direct';
@@ -166,32 +175,37 @@ class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment
/**
* Store id of role custom data type ( option value )
+ * @var int
*/
protected $_roleCustomDataTypeID;
/**
* Store id of event Name custom data type ( option value)
+ * @var int
*/
protected $_eventNameCustomDataTypeID;
/**
* Selected discount id.
+ * @var int
*/
public $_originalDiscountId = NULL;
/**
* Event id.
+ * @var int
*/
public $_eventId = NULL;
/**
* Id of payment, if any
+ * @var int
*/
public $_paymentId = NULL;
/**
- * @todo add explanatory note about this
* @var null
+ * @todo add explanatory note about this
*/
public $_onlinePendingContributionId = NULL;
@@ -202,10 +216,18 @@ public function getDefaultEntity() {
return 'Participant';
}
+ /**
+ * Default form context used as part of addField()
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
/**
* Set variables up before form is built.
*
* @return void
+ * @throws \CRM_Core_Exception
*/
public function preProcess() {
parent::preProcess();
@@ -216,11 +238,11 @@ public function preProcess() {
// @todo eliminate this duplication.
$this->_contactId = $this->_contactID;
$this->_eID = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $this->_context);
if ($this->_contactID) {
- $this->setPageTitle(ts('Event Registration for %1', array(1 => $this->userDisplayName)));
+ $this->setPageTitle(ts('Event Registration for %1', [1 => $this->userDisplayName]));
}
else {
$this->setPageTitle(ts('Event Registration'));
@@ -284,12 +306,12 @@ public function preProcess() {
$this->_single = TRUE;
$this->assign('urlPath', 'civicrm/contact/view/participant');
if (!$this->_id && !$this->_contactId) {
- $breadCrumbs = array(
- array(
+ $breadCrumbs = [
+ [
'title' => ts('CiviEvent Dashboard'),
'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumbs);
}
@@ -365,6 +387,7 @@ public function preProcess() {
// when custom data is included in this page
if (!empty($_POST['hidden_custom'])) {
+ $eventId = (int) CRM_Utils_Array::value('event_id', $_POST);
// Custom data of type participant role
// Note: Some earlier commits imply $_POST['role_id'] could be a comma separated string,
// not sure if that ever really happens
@@ -377,13 +400,13 @@ public function preProcess() {
}
//custom data of type participant event
- CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $_POST['event_id'], 1, 'Participant', $this->_id);
+ CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $eventId, 1, 'Participant', $this->_id);
CRM_Custom_Form_CustomData::buildQuickForm($this);
CRM_Custom_Form_CustomData::setDefaultValues($this);
// custom data of type participant event type
$eventTypeId = NULL;
- if ($eventId = CRM_Utils_Array::value('event_id', $_POST)) {
+ if ($eventId) {
$eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'event_type_id', 'id');
}
CRM_Custom_Form_CustomData::preProcess($this, $this->_eventTypeCustomDataTypeID, $eventTypeId,
@@ -412,23 +435,23 @@ public function preProcess() {
* This function sets the default values for the form in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
+ * @return array
+ * @throws \CRM_Core_Exception
*/
public function setDefaultValues() {
if ($this->_showFeeBlock) {
return CRM_Event_Form_EventFees::setDefaultValues($this);
}
- $defaults = array();
+ $defaults = [];
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
if ($this->_id) {
- $ids = array();
- $params = array('id' => $this->_id);
+ $ids = [];
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
@@ -459,15 +482,6 @@ public function setDefaultValues() {
}
}
- if ($this->_action & (CRM_Core_Action::VIEW | CRM_Core_Action::BROWSE)) {
- $inactiveNeeded = TRUE;
- $viewMode = TRUE;
- }
- else {
- $viewMode = FALSE;
- $inactiveNeeded = FALSE;
- }
-
//setting default register date
if ($this->_action == CRM_Core_Action::ADD) {
$statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
@@ -505,6 +519,7 @@ public function setDefaultValues() {
if (!empty($submittedEvent[0])) {
$eventID = $submittedEvent[0];
}
+ $defaults[$this->_id]['register_date'] = date('Y-m-d H:i:s');
}
else {
$defaults[$this->_id]['record_contribution'] = 0;
@@ -524,9 +539,6 @@ public function setDefaultValues() {
}
}
- list($defaults[$this->_id]['register_date'], $defaults[$this->_id]['register_date_time'])
- = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value('register_date', $defaults[$this->_id]), 'activityDateTime');
-
//assign event and role id, this is needed for Custom data building
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
if (!empty($defaults[$this->_id]['participant_role_id'])) {
@@ -578,6 +590,8 @@ public function setDefaultValues() {
* Build the form object.
*
* @return void
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function buildQuickForm() {
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
@@ -602,51 +616,50 @@ public function buildQuickForm() {
TRUE
)) - 1;
if ($additionalParticipant) {
- $deleteParticipants = array(
+ $deleteParticipants = [
1 => ts('Delete this participant record along with associated participant record(s).'),
2 => ts('Delete only this participant record.'),
- );
+ ];
$this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, ' ');
- $this->setDefaults(array('delete_participant' => 1));
+ $this->setDefaults(['delete_participant' => 1]);
$this->assign('additionalParticipant', $additionalParticipant);
}
}
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
return;
}
if ($this->_single && $this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Contact'), array(
- 'create' => TRUE,
- 'api' => array('extra' => array('email')),
- ), TRUE);
+ $this->addEntityRef('contact_id', ts('Contact'), [
+ 'create' => TRUE,
+ 'api' => ['extra' => ['email']],
+ ], TRUE);
}
- $eventFieldParams = array(
- 'entity' => 'event',
- 'select' => array('minimumInputLength' => 0),
- 'api' => array(
- 'extra' => array('campaign_id', 'default_role_id', 'event_type_id'),
- ),
- );
+ $eventFieldParams = [
+ 'entity' => 'Event',
+ 'select' => ['minimumInputLength' => 0],
+ 'api' => [
+ 'extra' => ['campaign_id', 'default_role_id', 'event_type_id'],
+ ],
+ ];
if ($this->_mode) {
// exclude events which are not monetary when credit card registration is used
$eventFieldParams['api']['params']['is_monetary'] = 1;
- $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, TRUE);
}
+ $this->addPaymentProcessorSelect(TRUE, FALSE, FALSE);
$element = $this->addEntityRef('event_id', ts('Event'), $eventFieldParams, TRUE);
@@ -672,26 +685,25 @@ public function buildQuickForm() {
}
}
CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
-
- $this->addDateTime('register_date', ts('Registration Date'), TRUE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'register_date', ts('Registration Date'), [], TRUE, ['time' => TRUE]);
if ($this->_id) {
$this->assign('entityID', $this->_id);
}
- $this->addSelect('role_id', array('multiple' => TRUE, 'class' => 'huge'), TRUE);
+ $this->addSelect('role_id', ['multiple' => TRUE, 'class' => 'huge'], TRUE);
// CRM-4395
- $checkCancelledJs = array('onchange' => "return sendNotification( );");
+ $checkCancelledJs = ['onchange' => "return sendNotification( );"];
$confirmJS = NULL;
if ($this->_onlinePendingContributionId) {
$cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
$cancelledContributionStatusId = array_search('Cancelled',
CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
);
- $checkCancelledJs = array(
+ $checkCancelledJs = [
'onchange' => "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
- );
+ ];
$participantStatusId = array_search('Pending from pay later',
CRM_Event_PseudoConstant::participantStatus()
@@ -699,18 +711,18 @@ public function buildQuickForm() {
$contributionStatusId = array_search('Completed',
CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
);
- $confirmJS = array('onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );");
+ $confirmJS = ['onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );"];
}
// get the participant status names to build special status array which is used to show notification
// checkbox below participant status select
$participantStatusName = CRM_Event_PseudoConstant::participantStatus();
- $notificationStatuses = array(
+ $notificationStatuses = [
'Cancelled',
'Pending from waitlist',
'Pending from approval',
'Expired',
- );
+ ];
// get the required status and then implode only ids
$notificationStatusIds = implode(',', array_keys(array_intersect($participantStatusName, $notificationStatuses)));
@@ -726,42 +738,42 @@ public function buildQuickForm() {
}
}
- $this->addSelect('status_id', $checkCancelledJs + array(
- 'options' => $statusOptions,
- 'option_url' => 'civicrm/admin/participant_status',
- ), TRUE);
+ $this->addSelect('status_id', $checkCancelledJs + [
+ 'options' => $statusOptions,
+ 'option_url' => 'civicrm/admin/participant_status',
+ ], TRUE);
$this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
- $this->add('text', 'source', ts('Event Source'));
+ $this->addField('source', ['entity' => 'Participant', 'name' => 'source']);
$noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
$this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
'js' => $confirmJS,
- );
+ ];
$path = CRM_Utils_System::currentPath();
- $excludeForPaths = array(
+ $excludeForPaths = [
'civicrm/contact/search',
'civicrm/group/search',
- );
+ ];
if (!in_array($path, $excludeForPaths)) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save and New'),
'subName' => 'new',
'js' => $confirmJS,
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
if ($this->_action == CRM_Core_Action::VIEW) {
@@ -772,11 +784,10 @@ public function buildQuickForm() {
/**
* Add local and global form rules.
*
- *
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_Participant', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Participant', 'formRule'], $this);
}
/**
@@ -801,7 +812,7 @@ public static function formRule($values, $files, $self) {
return TRUE;
}
- $errorMsg = array();
+ $errorMsg = [];
if (!empty($values['payment_processor_id'])) {
// make sure that payment instrument values (e.g. credit card number and cvv) are valid
@@ -902,7 +913,7 @@ public function postProcess() {
}
if (!$this->_single && !empty($event_id)) {
$duplicateContacts = 0;
- while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
+ foreach ($this->_contactIds as $k => $dupeCheckContactId) {
// Eliminate contacts that have already been assigned to this event.
$dupeCheck = new CRM_Event_BAO_Participant();
$dupeCheck->contact_id = $dupeCheckContactId;
@@ -916,7 +927,7 @@ public function postProcess() {
if ($duplicateContacts > 0) {
$msg = ts(
"%1 contacts have already been assigned to this event. They were not added a second time.",
- array(1 => $duplicateContacts)
+ [1 => $duplicateContacts]
);
CRM_Core_Session::setStatus($msg);
}
@@ -964,7 +975,9 @@ public function postProcess() {
*
* @param array $params
*
- * @return array
+ * @return string
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function submit($params) {
$participantStatus = CRM_Event_PseudoConstant::participantStatus();
@@ -986,9 +999,9 @@ public function submit($params) {
}
if ($this->_isPaidEvent) {
- $contributionParams = array();
- $lineItem = array();
- $additionalParticipantDetails = array();
+ $contributionParams = ['skipCleanMoney' => TRUE];
+ $lineItem = [];
+ $additionalParticipantDetails = [];
if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
$eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
@@ -1019,16 +1032,16 @@ public function submit($params) {
}
else {
- //check if discount is selected
- if (!empty($params['discount_id'])) {
- $discountId = $params['discount_id'];
- }
- else {
- $discountId = $params['discount_id'] = 'null';
+ // check that discount_id is set
+ if (empty($params['discount_id'])) {
+ $params['discount_id'] = 'null';
}
//lets carry currency, CRM-4453
$params['fee_currency'] = $config->defaultCurrency;
+ if (!isset($lineItem[0])) {
+ $lineItem[0] = [];
+ }
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
$params, $lineItem[0]
);
@@ -1063,7 +1076,7 @@ public function submit($params) {
$this->_lineItem = $lineItem;
$lineItem = array_merge($lineItem, $additionalParticipantDetails);
- $participantCount = array();
+ $participantCount = [];
foreach ($lineItem as $k) {
foreach ($k as $v) {
if (CRM_Utils_Array::value('participant_count', $v) > 0) {
@@ -1089,8 +1102,6 @@ public function submit($params) {
$amountOwed = $params['amount'];
unset($params['amount']);
}
- $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
- $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
$params['contact_id'] = $this->_contactId;
// overwrite actual payment amount if entered
@@ -1112,6 +1123,8 @@ public function submit($params) {
$this->_params['participant_register_date'] = $params['register_date'];
$roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
+ $now = date('YmdHis');
+
if ($this->_mode) {
if (!$this->_isPaidEvent) {
CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
@@ -1126,10 +1139,10 @@ public function submit($params) {
// set source if not set
if (empty($params['source'])) {
- $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(
- 1 => $userName,
- 2 => $eventTitle,
- ));
+ $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', [
+ 1 => $userName,
+ 2 => $eventTitle,
+ ]);
}
else {
$this->_params['participant_source'] = $params['source'];
@@ -1139,8 +1152,7 @@ public function submit($params) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
$this->_mode
);
- $now = date('YmdHis');
- $fields = array();
+ $fields = [];
// set email for primary location.
$fields['email-Primary'] = 1;
@@ -1164,7 +1176,7 @@ public function submit($params) {
$fields["email-{$this->_bltID}"] = 1;
$ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
- $nameFields = array('first_name', 'middle_name', 'last_name');
+ $nameFields = ['first_name', 'middle_name', 'last_name'];
foreach ($nameFields as $name) {
$fields[$name] = 1;
@@ -1177,7 +1189,7 @@ public function submit($params) {
}
if (!empty($this->_params['participant_role_id'])) {
- $customFieldsRole = array();
+ $customFieldsRole = [];
foreach ($this->_params['participant_role_id'] as $roleKey) {
$customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
@@ -1199,10 +1211,8 @@ public function submit($params) {
);
$customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
$customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
- $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
- $this->_id,
- 'Participant'
- );
+
+ $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, $this->getDefaultEntity());
}
//do cleanup line items if participant edit the Event Fee.
@@ -1233,7 +1243,7 @@ public function submit($params) {
// so more conservative approach is called for.
// In fact the use of $params and $this->_params & $this->_contactId vs $contactID
// needs rationalising.
- $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
+ $mapParams = array_merge(['contact_id' => $contactID], $this->_params);
CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
$payment = $this->_paymentProcessor['object'];
@@ -1264,9 +1274,7 @@ public function submit($params) {
$this->set('params', $this->_params);
$this->assign('trxn_id', $result['trxn_id']);
- $this->assign('receive_date',
- CRM_Utils_Date::processDate($this->_params['receive_date'])
- );
+ $this->assign('receive_date', $this->_params['receive_date']);
//add contribution record
$this->_params['financial_type_id']
@@ -1282,7 +1290,7 @@ public function submit($params) {
);
// add participant record
- $participants = array();
+ $participants = [];
if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
$this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
$this->_params['role_id']
@@ -1301,17 +1309,16 @@ public function submit($params) {
'Participant'
);
//add participant payment
- $paymentParticipant = array(
+ $paymentParticipant = [
'participant_id' => $participants[0]->id,
'contribution_id' => $contribution->id,
- );
- $ids = array();
+ ];
- CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
+ CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
$this->_contactIds[] = $this->_contactId;
}
else {
- $participants = array();
+ $participants = [];
if ($this->_single) {
if ($params['role_id']) {
$params['role_id'] = $roleIdWithSeparator;
@@ -1346,7 +1353,7 @@ public function submit($params) {
$this->_contactIds[] = $this->_contactId;
}
- $contributions = array();
+ $contributions = [];
if (!empty($params['record_contribution'])) {
if (!empty($params['id'])) {
if ($this->_onlinePendingContributionId) {
@@ -1365,10 +1372,10 @@ public function submit($params) {
//build contribution params
if (!$this->_onlinePendingContributionId) {
if (empty($params['source'])) {
- $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(
- 1 => $eventTitle,
- 2 => $userName,
- ));
+ $contributionParams['source'] = ts('%1 : Offline registration (by %2)', [
+ 1 => $eventTitle,
+ 2 => $userName,
+ ]);
}
else {
$contributionParams['source'] = $params['source'];
@@ -1379,10 +1386,9 @@ public function submit($params) {
$contributionParams['non_deductible_amount'] = 'null';
$contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
$contributionParams['contact_id'] = $this->_contactID;
- // @todo change receive_date to datepicker field. Strip out all wrangling.
- $contributionParams['receive_date'] = $params['receive_date'];
+ $contributionParams['receive_date'] = CRM_Utils_Array::value('receive_date', $params, 'null');
- $recordContribution = array(
+ $recordContribution = [
'financial_type_id',
'payment_instrument_id',
'trxn_id',
@@ -1391,7 +1397,7 @@ public function submit($params) {
'campaign_id',
'pan_truncation',
'card_type_id',
- );
+ ];
foreach ($recordContribution as $f) {
$contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
@@ -1446,12 +1452,12 @@ public function submit($params) {
if ($this->_single) {
if (empty($ids)) {
- $ids = array();
+ $ids = [];
}
$contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
}
else {
- $ids = array();
+ $ids = [];
foreach ($this->_contactIds as $contactID) {
$contributionParams['contact_id'] = $contactID;
$contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
@@ -1522,8 +1528,8 @@ public function submit($params) {
);
}
- $sent = array();
- $notSent = array();
+ $sent = [];
+ $notSent = [];
if (!empty($params['send_receipt'])) {
if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
$receiptFrom = $params['from_email_address'];
@@ -1531,8 +1537,8 @@ public function submit($params) {
$this->assign('module', 'Event Registration');
//use of the message template below requires variables in different format
- $event = $events = array();
- $returnProperties = array('event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
+ $event = $events = [];
+ $returnProperties = ['event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
//get all event details.
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
@@ -1543,7 +1549,7 @@ public function submit($params) {
$role = CRM_Event_PseudoConstant::participantRole();
$participantRoles = CRM_Utils_Array::value('role_id', $params);
if (is_array($participantRoles)) {
- $selectedRoles = array();
+ $selectedRoles = [];
foreach ($participantRoles as $roleId) {
$selectedRoles[] = $role[$roleId];
}
@@ -1563,10 +1569,10 @@ public function submit($params) {
$this->assign('isShowLocation', $event['is_show_location']);
if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
- $locationParams = array(
+ $locationParams = [
'entity_id' => $params['event_id'],
'entity_table' => 'civicrm_event',
- );
+ ];
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
$this->assign('location', $location);
}
@@ -1615,18 +1621,17 @@ public function submit($params) {
}
$this->assign('register_date', $params['register_date']);
- if ($params['receive_date']) {
+ if (isset($params['receive_date'])) {
$this->assign('receive_date', $params['receive_date']);
}
- $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
+ $participant = [['participant_id', '=', $participants[0]->id, 0, 0]];
// check whether its a test drive ref CRM-3075
if (!empty($this->_defaultValues['is_test'])) {
- $participant[] = array('participant_test', '=', 1, 0, 0);
+ $participant[] = ['participant_test', '=', 1, 0, 0];
}
- $template = CRM_Core_Smarty::singleton();
- $customGroup = array();
+ $customGroup = [];
//format submitted data
foreach ($params['custom'] as $fieldID => $values) {
foreach ($values as $fieldValue) {
@@ -1658,15 +1663,15 @@ public function submit($params) {
if ($this->_isPaidEvent) {
// fix amount for each of participants ( for bulk mode )
- $eventAmount = array();
+ $eventAmount = [];
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
//add dataArray in the receipts in ADD and UPDATE condition
- $dataArray = array();
+ $dataArray = [];
if ($this->_action & CRM_Core_Action::ADD) {
- $line = $lineItem[0];
+ $line = isset($lineItem[0]) ? $lineItem[0] : [];
}
elseif ($this->_action & CRM_Core_Action::UPDATE) {
$line = $this->_values['line_items'];
@@ -1684,30 +1689,30 @@ public function submit($params) {
}
}
$this->assign('totalTaxAmount', $totalTaxAmount);
- $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
+ $this->assign('taxTerm', $this->getSalesTaxTerm());
$this->assign('dataArray', $dataArray);
}
if (!empty($additionalParticipantDetails)) {
$params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
}
- $eventAmount[$num] = array(
+ $eventAmount[$num] = [
'label' => preg_replace('//', '', $params['amount_level']),
'amount' => $params['fee_amount'],
- );
+ ];
//as we are using same template for online & offline registration.
//So we have to build amount as array.
$eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
$this->assign('amount', $eventAmount);
}
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_offline_receipt',
'contactId' => $contactID,
'isTest' => !empty($this->_defaultValues['is_test']),
'PDFFilename' => ts('confirmation') . '.pdf',
- );
+ ];
// try to send emails only if email id is present
// and the do-not-email option is not checked for that contact
@@ -1727,7 +1732,7 @@ public function submit($params) {
);
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
- if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
+ if (!empty($taxAmt) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
$sendTemplateParams['isEmailPdf'] = TRUE;
$sendTemplateParams['contributionId'] = $contributionId;
}
@@ -1782,9 +1787,9 @@ public function setCustomDataTypes() {
protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
$statusMsg = '';
if (($this->_action & CRM_Core_Action::UPDATE)) {
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contributorDisplayName]);
if (!empty($params['send_receipt']) && count($sent)) {
- $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
+ $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', [1 => $this->_contributorEmail]);
}
if ($updateStatusMsg) {
@@ -1793,15 +1798,15 @@ protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
}
elseif ($this->_action & CRM_Core_Action::ADD) {
if ($this->_single) {
- $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
+ $statusMsg = ts('Event registration for %1 has been added.', [1 => $this->_contributorDisplayName]);
if (!empty($params['send_receipt']) && count($sent)) {
- $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
+ $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $this->_contributorEmail]);
}
}
else {
- $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
+ $statusMsg = ts('Total Participant(s) added to event: %1.', [1 => count($this->_contactIds)]);
if (count($notSent) > 0) {
- $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
+ $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', [1 => count($notSent)]);
}
elseif (isset($params['send_receipt'])) {
$statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
diff --git a/CRM/Event/Form/ParticipantFeeSelection.php b/CRM/Event/Form/ParticipantFeeSelection.php
index aab0a8375da3..50511fba177e 100644
--- a/CRM/Event/Form/ParticipantFeeSelection.php
+++ b/CRM/Event/Form/ParticipantFeeSelection.php
@@ -1,9 +1,9 @@
assign('lineItemTotal', $total);
}
- $title = ts("Change selections for %1", array(1 => $this->_contributorDisplayName));
+ $title = ts("Change selections for %1", [1 => $this->_contributorDisplayName]);
if ($title) {
CRM_Utils_System::setTitle($title);
}
@@ -123,7 +123,7 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- $params = array('id' => $this->_participantId);
+ $params = ['id' => $this->_participantId];
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $this->_eventId);
@@ -163,12 +163,12 @@ public function buildQuickForm() {
$this->assign('currencySymbol', $config->defaultCurrencySymbol);
// line items block
- $lineItem = $event = array();
- $params = array('id' => $this->_eventId);
+ $lineItem = $event = [];
+ $params = ['id' => $this->_eventId];
CRM_Event_BAO_Event::retrieve($params, $event);
//retrieve custom information
- $this->_values = array();
+ $this->_values = [];
CRM_Event_Form_Registration::initEventFee($this, $event['id']);
CRM_Event_Form_Registration_Register::buildAmount($this, TRUE);
@@ -181,16 +181,16 @@ public function buildQuickForm() {
$statusOptions = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
$this->add('select', 'status_id', ts('Participant Status'),
- array(
+ [
'' => ts('- select -'),
- ) + $statusOptions,
+ ] + $statusOptions,
TRUE
);
$this->addElement('checkbox',
'send_receipt',
ts('Send Confirmation?'), NULL,
- array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
+ ['onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails['from_email_id']);
@@ -200,26 +200,26 @@ public function buildQuickForm() {
$noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
$this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- );
+ ];
if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_participantId)) {
- $buttons[] = array(
+ $buttons[] = [
'type' => 'upload',
'name' => ts('Save and Record Payment'),
'subName' => 'new',
- );
+ ];
}
- $buttons[] = array(
+ $buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
- );
+ ];
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Event_Form_ParticipantFeeSelection', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_ParticipantFeeSelection', 'formRule'], $this);
}
/**
@@ -230,7 +230,7 @@ public function buildQuickForm() {
* @return array
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
return $errors;
}
@@ -239,11 +239,11 @@ public function postProcess() {
$feeBlock = $this->_values['fee'];
$lineItems = $this->_values['line_items'];
- CRM_Price_BAO_LineItem::changeFeeSelections($params, $this->_participantId, 'participant', $this->_contributionId, $feeBlock, $lineItems, $this->_paidAmount);
+ CRM_Price_BAO_LineItem::changeFeeSelections($params, $this->_participantId, 'participant', $this->_contributionId, $feeBlock, $lineItems);
$this->contributionAmt = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionId, 'total_amount');
// email sending
if (!empty($params['send_receipt'])) {
- $fetchParticipantVals = array('id' => $this->_participantId);
+ $fetchParticipantVals = ['id' => $this->_participantId];
CRM_Event_BAO_Participant::getValues($fetchParticipantVals, $participantDetails, CRM_Core_DAO::$_nullArray);
$participantParams = array_merge($params, $participantDetails[$this->_participantId]);
$mailSent = $this->emailReceipt($participantParams);
@@ -252,13 +252,13 @@ public function postProcess() {
// update participant
CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $this->_participantId, 'status_id', $params['status_id']);
if (!empty($params['note'])) {
- $noteParams = array(
+ $noteParams = [
'entity_table' => 'civicrm_participant',
'note' => $params['note'],
'entity_id' => $this->_participantId,
'contact_id' => $this->_contactId,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Note::add($noteParams);
}
CRM_Core_Session::setStatus(ts("The fee selection has been changed for this participant"), ts('Saved'), 'success');
@@ -279,7 +279,7 @@ public function postProcess() {
*/
public function emailReceipt(&$params) {
$updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', FALSE, FALSE);
- $lineItem = array();
+ $lineItem = [];
if ($updatedLineItem) {
$lineItem[] = $updatedLineItem;
}
@@ -292,8 +292,8 @@ public function emailReceipt(&$params) {
$this->assign('module', 'Event Registration');
//use of the message template below requires variables in different format
- $event = $events = array();
- $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
+ $event = $events = [];
+ $returnProperties = ['fee_label', 'start_date', 'end_date', 'is_show_location', 'title'];
//get all event details.
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
@@ -304,7 +304,7 @@ public function emailReceipt(&$params) {
$role = CRM_Event_PseudoConstant::participantRole();
$participantRoles = CRM_Utils_Array::value('role_id', $params);
if (is_array($participantRoles)) {
- $selectedRoles = array();
+ $selectedRoles = [];
foreach (array_keys($participantRoles) as $roleId) {
$selectedRoles[] = $role[$roleId];
}
@@ -324,10 +324,10 @@ public function emailReceipt(&$params) {
$this->assign('isShowLocation', $event['is_show_location']);
if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
- $locationParams = array(
+ $locationParams = [
'entity_id' => $params['event_id'],
'entity_table' => 'civicrm_event',
- );
+ ];
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
$this->assign('location', $location);
}
@@ -366,13 +366,13 @@ public function emailReceipt(&$params) {
$this->assign('contactID', $this->_contactId);
$this->assign('participantID', $this->_participantId);
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_offline_receipt',
'contactId' => $this->_contactId,
'isTest' => FALSE,
'PDFFilename' => ts('confirmation') . '.pdf',
- );
+ ];
// try to send emails only if email id is present
// and the do-not-email option is not checked for that contact
diff --git a/CRM/Event/Form/ParticipantView.php b/CRM/Event/Form/ParticipantView.php
index c7d22619a65c..8b51c854655b 100644
--- a/CRM/Event/Form/ParticipantView.php
+++ b/CRM/Event/Form/ParticipantView.php
@@ -1,9 +1,9 @@
$participantID);
+ $params = ['id' => $participantID];
CRM_Event_BAO_Participant::getValues($params,
$values,
@@ -100,8 +100,25 @@ public function preProcess() {
}
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
+ // CRM-20879: Show 'Transfer or Cancel' option beside 'Change fee selection'
+ // only if logged in user have 'edit event participants' permission and
+ // participant status is not Cancelled or Transferred
+ if (CRM_Core_Permission::check('edit event participants') && !in_array($status, ['Cancelled', 'Transferred'])) {
+ $this->assign('transferOrCancelLink',
+ CRM_Utils_System::url(
+ 'civicrm/event/selfsvcupdate',
+ [
+ 'reset' => 1,
+ 'is_backoffice' => 1,
+ 'pid' => $participantID,
+ 'cs' => CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, 'inf'),
+ ]
+ )
+ );
+ }
+
if ($values[$participantID]['is_test']) {
- $values[$participantID]['status'] .= ' (test) ';
+ $values[$participantID]['status'] = CRM_Core_TestEntity::appendTestText($values[$participantID]['status']);
}
// Get Note
@@ -138,8 +155,8 @@ public function preProcess() {
$eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
$eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
$allRoleIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $values[$participantID]['role_id']);
- $groupTree = array();
- $finalTree = array();
+ $groupTree = [];
+ $finalTree = [];
foreach ($allRoleIDs as $k => $v) {
$roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL, $v, $roleCustomDataTypeID);
@@ -175,7 +192,7 @@ public function preProcess() {
"action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::check('edit event participants')) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=update&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
@@ -190,7 +207,7 @@ public function preProcess() {
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$displayName = CRM_Contact_BAO_Contact::displayName($values[$participantID]['contact_id']);
- $participantCount = array();
+ $participantCount = [];
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
@@ -214,7 +231,7 @@ public function preProcess() {
$title = $displayName . ' (' . CRM_Utils_Array::value($roleId, $participantRoles) . ' - ' . $eventTitle . ')';
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
- $viewRoles = array();
+ $viewRoles = [];
foreach (explode($sep, $values[$participantID]['role_id']) as $k => $v) {
$viewRoles[] = $participantRoles[$v];
}
@@ -237,15 +254,14 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Event/Form/Registration.php b/CRM/Event/Form/Registration.php
index 34d840bd2187..2e60b956e41a 100644
--- a/CRM/Event/Form/Registration.php
+++ b/CRM/Event/Form/Registration.php
@@ -1,9 +1,9 @@
_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
- $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
+ $this->_action = CRM_Utils_Request::retrieve('action', 'Alphanumeric', $this, FALSE, CRM_Core_Action::ADD);
//CRM-4320
$this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
@@ -391,9 +393,7 @@ public function preProcess() {
$this->_contributeMode = $this->get('contributeMode');
$this->assign('contributeMode', $this->_contributeMode);
- // setting CMS page title
- CRM_Utils_System::setTitle($this->_values['event']['title']);
- $this->assign('title', $this->_values['event']['title']);
+ $this->setTitle($this->_values['event']['title']);
$this->assign('paidEvent', $this->_values['event']['is_monetary']);
@@ -761,8 +761,7 @@ public function confirmPostProcess($contactID = NULL, $contribution = NULL, $pay
'participant_id' => $participant->id,
'contribution_id' => $contribution->id,
);
- $ids = array();
- $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
+ $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams);
}
//set only primary participant's params for transfer checkout.
@@ -1258,10 +1257,10 @@ public static function resetSubmittedValue($elementName, $optionIds = array(), &
return;
}
foreach (array(
- 'constantValues',
- 'submitValues',
- 'defaultValues',
- ) as $val) {
+ 'constantValues',
+ 'submitValues',
+ 'defaultValues',
+ ) as $val) {
$values = $form->{"_$val"};
if (!is_array($values) || empty($values)) {
continue;
diff --git a/CRM/Event/Form/Registration/AdditionalParticipant.php b/CRM/Event/Form/Registration/AdditionalParticipant.php
index f23867627d11..afaaf1a4d4ff 100644
--- a/CRM/Event/Form/Registration/AdditionalParticipant.php
+++ b/CRM/Event/Form/Registration/AdditionalParticipant.php
@@ -1,9 +1,9 @@
assign('formId', $participantNo);
- $this->_params = array();
+ $this->_params = [];
$this->_params = $this->get('params');
$participantTot = $this->_params[0]['additional_participants'] + 1;
@@ -67,7 +68,7 @@ public function preProcess() {
if ($skipCount) {
$this->assign('skipCount', $skipCount);
}
- CRM_Utils_System::setTitle(ts('Register Participant %1 of %2', array(1 => $participantCnt, 2 => $participantTot)));
+ CRM_Utils_System::setTitle(ts('Register Participant %1 of %2', [1 => $participantCnt, 2 => $participantTot]));
//CRM-4320, hack to check last participant.
$this->_lastParticipant = FALSE;
@@ -85,7 +86,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = $unsetSubmittedOptions = array();
+ $defaults = $unsetSubmittedOptions = [];
$discountId = NULL;
//fix for CRM-3088, default value for discount set.
if (!empty($this->_values['discount'])) {
@@ -102,7 +103,7 @@ public function setDefaultValues() {
continue;
}
- $optionsFull = CRM_Utils_Array::value('option_full_ids', $val, array());
+ $optionsFull = CRM_Utils_Array::value('option_full_ids', $val, []);
foreach ($val['options'] as $keys => $values) {
if ($values['is_default'] && !in_array($keys, $optionsFull)) {
if ($val['html_type'] == 'CheckBox') {
@@ -180,19 +181,19 @@ public function buildQuickForm() {
CRM_Event_Form_Registration_Register::buildAmount($this);
}
$first_name = $last_name = NULL;
- $pre = $post = array();
- foreach (array(
- 'pre',
- 'post',
- ) as $keys) {
+ $pre = $post = [];
+ foreach ([
+ 'pre',
+ 'post',
+ ] as $keys) {
if (isset($this->_values['additional_custom_' . $keys . '_id'])) {
$this->buildCustom($this->_values['additional_custom_' . $keys . '_id'], 'additionalCustom' . ucfirst($keys));
$$keys = CRM_Core_BAO_UFGroup::getFields($this->_values['additional_custom_' . $keys . '_id']);
}
- foreach (array(
- 'first_name',
- 'last_name',
- ) as $name) {
+ foreach ([
+ 'first_name',
+ 'last_name',
+ ] as $name) {
if (array_key_exists($name, $$keys) &&
CRM_Utils_Array::value('is_required', CRM_Utils_Array::value($name, $$keys))
) {
@@ -209,7 +210,7 @@ public function buildQuickForm() {
//add buttons
$js = NULL;
if ($this->isLastParticipant(TRUE) && empty($this->_values['event']['is_monetary'])) {
- $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
+ $js = ['onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"];
}
//handle case where user might sart with waiting by group
@@ -262,23 +263,23 @@ public function buildQuickForm() {
$this->_allowWaitlist = FALSE;
$this->set('allowWaitlist', $this->_allowWaitlist);
if ($this->_requireApproval) {
- $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.", array(
- 1 => ++$processedCnt,
- 2 => $spaces,
- ));
+ $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.", [
+ 1 => ++$processedCnt,
+ 2 => $spaces,
+ ]);
}
else {
- $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed).", array(
- 1 => ++$processedCnt,
- 2 => $spaces,
- ));
+ $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed).", [
+ 1 => ++$processedCnt,
+ 2 => $spaces,
+ ]);
}
}
else {
- $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Please go back to the main registration page and reduce the number of additional people. You will also need to complete payment information.", array(
- 1 => ++$processedCnt,
- 2 => $spaces,
- ));
+ $statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Please go back to the main registration page and reduce the number of additional people. You will also need to complete payment information.", [
+ 1 => ++$processedCnt,
+ 2 => $spaces,
+ ]);
$allowToProceed = FALSE;
}
CRM_Core_Session::setStatus($statusMessage, ts('Registration Error'), 'error');
@@ -344,40 +345,38 @@ public function buildQuickForm() {
$this->assign('statusMessage', $statusMessage);
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'back',
'name' => ts('Go Back'),
'spacing' => '  ',
- ),
- );
+ ],
+ ];
//CRM-4320
if ($allowToProceed) {
- $buttons = array_merge($buttons, array(
- array(
- 'type' => 'upload',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- 'js' => $js,
- ),
- )
- );
+ $buttons = array_merge($buttons, [
+ [
+ 'type' => 'upload',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ 'js' => $js,
+ ],
+ ]);
if ($includeSkipButton) {
- $buttons = array_merge($buttons, array(
- array(
- 'type' => 'next',
- 'name' => ts('Skip Participant'),
- 'subName' => 'skip',
- 'icon' => 'fa-fast-forward',
- ),
- )
- );
+ $buttons = array_merge($buttons, [
+ [
+ 'type' => 'next',
+ 'name' => ts('Skip Participant'),
+ 'subName' => 'skip',
+ 'icon' => 'fa-fast-forward',
+ ],
+ ]);
}
}
$this->addButtons($buttons);
- $this->addFormRule(array('CRM_Event_Form_Registration_AdditionalParticipant', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Registration_AdditionalParticipant', 'formRule'], $this);
$this->unsavedChangesWarn = TRUE;
}
@@ -395,7 +394,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
//get the button name.
$button = substr($self->controller->getButtonName(), -4);
@@ -430,8 +429,8 @@ public static function formRule($fields, $files, $self) {
if ($key != $addParticipantNum) {
if (!$self->_values['event']['allow_same_participant_emails']) {
//collect all email fields
- $existingEmails = array();
- $additionalParticipantEmails = array();
+ $existingEmails = [];
+ $additionalParticipantEmails = [];
if (is_array($value)) {
foreach ($value as $key => $val) {
if (substr($key, 0, 6) == 'email-' && $val) {
@@ -474,7 +473,7 @@ public static function formRule($fields, $files, $self) {
//validate price field params.
$priceSetErrors = self::validatePriceSet($self, $allParticipantParams);
- $errors = array_merge($errors, CRM_Utils_Array::value($addParticipantNum, $priceSetErrors, array()));
+ $errors = array_merge($errors, CRM_Utils_Array::value($addParticipantNum, $priceSetErrors, []));
if (!$self->_allowConfirmation &&
is_numeric($self->_availableRegistrations)
@@ -492,10 +491,10 @@ public static function formRule($fields, $files, $self) {
if (!$self->_allowConfirmation && empty($self->_values['event']['has_waitlist']) &&
$totalParticipants > $self->_availableRegistrations
) {
- $errors['_qf_default'] = ts('Sorry, it looks like this event only has %2 spaces available, and you are trying to register %1 participants. Please change your selections accordingly.', array(
- 1 => $totalParticipants,
- 2 => $self->_availableRegistrations,
- ));
+ $errors['_qf_default'] = ts('Sorry, it looks like this event only has %2 spaces available, and you are trying to register %1 participants. Please change your selections accordingly.', [
+ 1 => $totalParticipants,
+ 2 => $self->_availableRegistrations,
+ ]);
}
}
}
@@ -550,7 +549,7 @@ public function validatePaymentValues($self, $fields) {
$validatePayement = FALSE;
if (!empty($fields['priceSetId'])) {
- $lineItem = array();
+ $lineItem = [];
CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
if ($fields['amount'] > 0) {
$validatePayement = TRUE;
@@ -568,7 +567,7 @@ public function validatePaymentValues($self, $fields) {
return TRUE;
}
- $errors = array();
+ $errors = [];
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
@@ -583,7 +582,7 @@ public function validatePaymentValues($self, $fields) {
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
if ($greetingType = CRM_Utils_Array::value($greeting, $self->_params[0])) {
- $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
+ $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
if ($customizedValue == $greetingType && empty($self->_params[0][$greeting . '_custom'])) {
return FALSE;
}
@@ -688,7 +687,7 @@ public function postProcess() {
$params['amount'] = $this->_values['fee'][$params['amount']]['value'];
}
else {
- $lineItem = array();
+ $lineItem = [];
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
//build line item array..
@@ -733,13 +732,14 @@ public function postProcess() {
$participantNo = count($this->_params);
if ($button != 'skip') {
- $statusMsg = ts('Registration information for participant %1 has been saved.', array(1 => $participantNo));
+ $statusMsg = ts('Registration information for participant %1 has been saved.', [1 => $participantNo]);
CRM_Core_Session::setStatus($statusMsg, ts('Registration Saved'), 'success');
}
// Check whether to process the registration now, calling processRegistration()
if (
- !$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
+ // CRM-11182 - Optional confirmation screen
+ !$this->_values['event']['is_confirm_enabled']
&& !$this->_values['event']['is_monetary']
&& CRM_Utils_Array::value('additional_participants', $this->_params[0])
&& $this->isLastParticipant()
@@ -754,12 +754,12 @@ public function postProcess() {
* @return array
*/
public static function &getPages($additionalParticipant) {
- $details = array();
+ $details = [];
for ($i = 1; $i <= $additionalParticipant; $i++) {
- $details["Participant_{$i}"] = array(
+ $details["Participant_{$i}"] = [
'className' => 'CRM_Event_Form_Registration_AdditionalParticipant',
'title' => "Register Additional Participant {$i}",
- );
+ ];
}
return $details;
}
diff --git a/CRM/Event/Form/Registration/Confirm.php b/CRM/Event/Form/Registration/Confirm.php
index 99b021c9b1c6..bc800a62a5d4 100644
--- a/CRM/Event/Form/Registration/Confirm.php
+++ b/CRM/Event/Form/Registration/Confirm.php
@@ -1,9 +1,9 @@
_contributeMode == 'express') {
- $params = array();
+ $params = [];
// rfp == redirect from paypal
// rfp is probably not required - the getPreApprovalDetails should deal with any payment-processor specific 'stuff'
$rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean',
@@ -105,14 +115,14 @@ public function preProcess() {
// also merge all the other values from the profile fields
$values = $this->controller->exportValues('Register');
- $skipFields = array(
+ $skipFields = [
'amount',
"street_address-{$this->_bltID}",
"city-{$this->_bltID}",
"state_province_id-{$this->_bltID}",
"postal_code-{$this->_bltID}",
"country_id-{$this->_bltID}",
- );
+ ];
foreach ($values as $name => $value) {
// skip amount field
@@ -199,9 +209,10 @@ public function buildQuickForm() {
$this->assignToTemplate();
if ($this->_values['event']['is_monetary'] &&
- ($this->_params[0]['amount'] || $this->_params[0]['amount'] == 0)
+ ($this->_params[0]['amount'] || $this->_params[0]['amount'] == 0) &&
+ !$this->_requireApproval
) {
- $this->_amount = array();
+ $this->_amount = [];
$taxAmount = 0;
foreach ($this->_params as $k => $v) {
@@ -212,10 +223,11 @@ public function buildQuickForm() {
//display tax amount on confirmation page
$taxAmount += $v['tax_amount'];
if (is_array($v)) {
- foreach (array(
- 'first_name',
- 'last_name',
- ) as $name) {
+ $this->cleanMoneyFields($v);
+ foreach ([
+ 'first_name',
+ 'last_name',
+ ] as $name) {
if (isset($v['billing_' . $name]) &&
!isset($v[$name])
) {
@@ -274,7 +286,7 @@ public function buildQuickForm() {
}
if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
- $lineItemForTemplate = array();
+ $lineItemForTemplate = [];
$getTaxDetails = FALSE;
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
@@ -303,22 +315,21 @@ public function buildQuickForm() {
$this->assign('isAmountzero', ($this->_totalAmount <= 0) ? TRUE : FALSE);
$contribButton = ts('Continue');
- $this->addButtons(array(
- array(
- 'type' => 'back',
- 'name' => ts('Go Back'),
- ),
- array(
- 'type' => 'next',
- 'name' => $contribButton,
- 'isDefault' => TRUE,
- 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"),
- ),
- )
- );
-
- $defaults = array();
- $fields = array();
+ $this->addButtons([
+ [
+ 'type' => 'back',
+ 'name' => ts('Go Back'),
+ ],
+ [
+ 'type' => 'next',
+ 'name' => $contribButton,
+ 'isDefault' => TRUE,
+ 'js' => ['onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"],
+ ],
+ ]);
+
+ $defaults = [];
+ $fields = [];
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $dontCare) {
$fields[$name] = 1;
@@ -354,7 +365,7 @@ public function buildQuickForm() {
// Assign Participant Count to Lineitem Table
$this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
- $this->addFormRule(array('CRM_Event_Form_Registration_Confirm', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Registration_Confirm', 'formRule'], $this);
}
/**
@@ -367,7 +378,7 @@ public function buildQuickForm() {
* @return array|bool
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
$eventFull = CRM_Event_BAO_Participant::eventFull($self->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $self->_values['event']));
if ($eventFull && empty($self->_allowConfirmation)) {
if (empty($self->_allowWaitlist)) {
@@ -398,6 +409,8 @@ public function postProcess() {
$now = date('YmdHis');
$this->_params = $this->get('params');
+ $this->cleanMoneyFields($this->_params);
+
if (!empty($this->_params[0]['contact_id'])) {
// unclear when this would be set & whether it could be checked in getContactID.
// perhaps it relates to when cid is in the url
@@ -429,7 +442,7 @@ public function postProcess() {
if ($this->_values['event']['is_monetary']) {
$this->set('finalAmount', $this->_amount);
}
- $participantCount = array();
+ $participantCount = [];
$taxAmount = $totalTaxAmount = 0;
//unset the skip participant from params.
@@ -459,8 +472,8 @@ public function postProcess() {
$payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
$paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
- $this->participantIDS = array();
- $fields = array();
+ $this->participantIDS = [];
+ $fields = [];
foreach ($params as $key => $value) {
CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
//unset the billing parameters if it is pay later mode
@@ -473,7 +486,7 @@ public function postProcess() {
|| (!empty($value['is_pay_later']) && !$this->_isBillingAddressRequiredForPayLater)
|| empty($value['is_primary'])
) {
- $billingFields = array(
+ $billingFields = [
"email-{$this->_bltID}",
'billing_first_name',
'billing_middle_name',
@@ -486,7 +499,7 @@ public function postProcess() {
"billing_country-{$this->_bltID}",
"billing_country_id-{$this->_bltID}",
"address_name-{$this->_bltID}",
- );
+ ];
foreach ($billingFields as $field) {
unset($value[$field]);
}
@@ -514,8 +527,7 @@ public function postProcess() {
// transactions etc
// for things like tell a friend
if (!$this->getContactID() && !empty($value['is_primary'])) {
- $session = CRM_Core_Session::singleton();
- $session->set('transaction.userID', $contactID);
+ CRM_Core_Session::singleton()->set('transaction.userID', $contactID);
}
$value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
@@ -534,13 +546,12 @@ public function postProcess() {
$value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
}
- //there might be case user seleted pay later and
+ //there might be case user selected pay later and
//now becomes part of run time waiting list.
$value['is_pay_later'] = FALSE;
}
-
- // required only if paid event
- if ($this->_values['event']['is_monetary'] && !($this->_allowWaitlist || $this->_requireApproval)) {
+ elseif ($this->_values['event']['is_monetary']) {
+ // required only if paid event
if (is_array($this->_paymentProcessor)) {
$payment = $this->_paymentProcessor['object'];
}
@@ -548,7 +559,6 @@ public function postProcess() {
$preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
$value = array_merge($value, $preApprovalParams);
}
- $result = NULL;
if (!empty($value['is_pay_later']) ||
$value['amount'] == 0 ||
@@ -571,16 +581,6 @@ public function postProcess() {
if (empty($value['email'])) {
$value['email'] = CRM_Utils_Array::valueByRegexKey('/^email-/', $value);
}
-
- if (is_object($payment)) {
- // Not quite sure why we don't just user $value since it contains the data
- // from result
- // @todo ditch $result & retest.
- list($result, $value) = $this->processPayment($payment, $value);
- }
- else {
- CRM_Core_Error::fatal($paymentObjError);
- }
}
$value['receive_date'] = $now;
@@ -607,8 +607,44 @@ public function postProcess() {
$isAdditionalAmount = TRUE;
}
+ CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params[0]);
//passing contribution id is already registered.
- $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount, $this->_paymentProcessor);
+ $contribution = self::processContribution($this, $value, NULL, $contactID, TRUE, $isAdditionalAmount, $this->_paymentProcessor);
+
+ try {
+ // @todo this should really be if $amount > 0, for pay later we should just load the
+ // manual pseudo processor (0) so there *should* always be a defined processor
+ if (!empty($payment)) {
+ $result = $payment->doPayment($value, 'event');
+ if ($result['payment_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
+ try {
+ civicrm_api3('contribution', 'completetransaction', [
+ 'id' => $contribution->id,
+ 'trxn_id' => $result['trxn_id'],
+ 'payment_processor_id' => $this->_paymentProcessor['id'],
+ 'is_transactional' => FALSE,
+ 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
+ 'is_email_receipt' => FALSE,
+ 'card_type_id' => CRM_Utils_Array::value('card_type_id', $params[0]),
+ 'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $params[0]),
+ ]);
+ // This has now been set to 1 in the DB - declare it here also
+ $contribution->contribution_status_id = 1;
+ }
+ catch (CiviCRM_API3_Exception $e) {
+ if ($e->getErrorCode() != 'contribution_completed') {
+ throw new CRM_Core_Exception('Failed to update contribution in database');
+ }
+ }
+ }
+ }
+ }
+ catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
+ Civi::log()->error('Payment processor exception: ' . $e->getMessage());
+ CRM_Core_Session::singleton()->setStatus($e->getMessage());
+ CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
+ }
+
$value['contributionID'] = $contribution->id;
$value['contributionTypeID'] = $contribution->financial_type_id;
$value['receive_date'] = $contribution->receive_date;
@@ -685,14 +721,14 @@ public function postProcess() {
if ($this->_allowConfirmation &&
!empty($this->_additionalParticipantIds)
) {
- $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
+ $allParticipantIds = array_merge([$registerByID], $this->_additionalParticipantIds);
}
$entityTable = 'civicrm_participant';
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
- $dataArray = array();
+ $dataArray = [];
foreach ($this->_lineItem as $key => $value) {
if ($value == 'skip') {
continue;
@@ -786,13 +822,13 @@ public function postProcess() {
if ($participantNum === NULL) {
break;
}
- //unset current particpant so we don't check them again
+ //unset current participant so we don't check them again
unset($copyParticipantCountLines[$participantNum]);
}
}
// get values of line items
if ($this->_amount) {
- $amount = array();
+ $amount = [];
$amount[$participantNum]['label'] = preg_replace('//', '', $params[$participantNum]['amount_level']);
$amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
$params[$participantNum]['amounts'] = $amount;
@@ -800,7 +836,7 @@ public function postProcess() {
if (!empty($this->_lineItem)) {
$lineItems = $this->_lineItem;
- $lineItem = array();
+ $lineItem = [];
if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
$lineItem[] = $lineItemValue;
}
@@ -819,7 +855,6 @@ public function postProcess() {
// call postprocess hook before leaving
$this->postProcessHook();
- // this does not return
$this->processPayment($payment, $primaryParticipant);
}
@@ -837,14 +872,14 @@ public function postProcess() {
NULL, $primaryContactId, $isTest,
TRUE
);
- //lets send mails to all with meaningful text, CRM-4320.
+ //let's send mails to all with meaningful text, CRM-4320.
$this->assign('isOnWaitlist', $this->_allowWaitlist);
$this->assign('isRequireApproval', $this->_requireApproval);
//need to copy, since we are unsetting on the way.
$copyParticipantCount = $participantCount;
- //lets carry all paticipant params w/ values.
+ //let's carry all participant params w/ values.
foreach ($additionalIDs as $participantID => $contactId) {
$participantNum = NULL;
if ($participantID == $registerByID) {
@@ -883,8 +918,8 @@ public function postProcess() {
unset($participantCount[$participantNum]);
}
// Change $this->_values['participant'] to include additional participant values
- $ids = $participantValues = array();
- $participantParams = array('id' => $participantID);
+ $ids = $participantValues = [];
+ $participantParams = ['id' => $participantID];
CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
$this->_values['participant'] = $participantValues[$participantID];
@@ -892,7 +927,7 @@ public function postProcess() {
$this->assign('customProfile', NULL);
//Additional Participant should get only it's payment information
if (!empty($this->_amount)) {
- $amount = array();
+ $amount = [];
$params = $this->get('params');
$amount[$participantNum]['label'] = preg_replace('//', '', $params[$participantNum]['amount_level']);
$amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
@@ -900,7 +935,7 @@ public function postProcess() {
}
if ($this->_lineItem) {
$lineItems = $this->_lineItem;
- $lineItem = array();
+ $lineItem = [];
if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
$lineItem[] = $lineItemValue;
}
@@ -910,7 +945,7 @@ public function postProcess() {
$this->assign('dataArray', $dataArray);
$this->assign('totalAmount', $individual[$participantNum]['totalAmtWithTax']);
$this->assign('totalTaxAmount', $individual[$participantNum]['totalTaxAmt']);
- $this->assign('individual', array($individual[$participantNum]));
+ $this->assign('individual', [$individual[$participantNum]]);
}
$this->assign('lineItem', $lineItem);
}
@@ -939,8 +974,10 @@ public function postProcess() {
* @param int $contactID
* @param bool $pending
* @param bool $isAdditionalAmount
+ * @param array $paymentProcessor
*
* @return \CRM_Contribute_BAO_Contribution
+ * @throws \CRM_Core_Exception
*/
public static function processContribution(
&$form, $params, $result, $contactID,
@@ -961,9 +998,12 @@ public static function processContribution(
}
// CRM-20264: fetch CC type ID and number (last 4 digit) and assign it back to $params
+ // @todo remove this once backoffice form is doing it - front end is doing it twice.
+ // (in general they are sharing much more code than they should - anything that truly should be shared
+ // should not be on this class).
CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($params);
- $contribParams = array(
+ $contribParams = [
'contact_id' => $contactID,
'financial_type_id' => !empty($form->_values['event']['financial_type_id']) ? $form->_values['event']['financial_type_id'] : $params['financial_type_id'],
'receive_date' => $now,
@@ -977,7 +1017,7 @@ public static function processContribution(
'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
'card_type_id' => CRM_Utils_Array::value('card_type_id', $params),
'pan_truncation' => CRM_Utils_Array::value('pan_truncation', $params),
- );
+ ];
if ($paymentProcessor) {
$contribParams['payment_instrument_id'] = $paymentProcessor['payment_instrument_id'];
@@ -985,12 +1025,12 @@ public static function processContribution(
}
if (!$pending && $result) {
- $contribParams += array(
+ $contribParams += [
'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']),
'trxn_id' => $result['trxn_id'],
'receipt_date' => $receiptDate,
- );
+ ];
}
$allStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
@@ -1004,21 +1044,14 @@ public static function processContribution(
$contribParams['is_test'] = 1;
}
- $contribID = NULL;
if (!empty($contribParams['invoice_id'])) {
- $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
+ $contribParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
$contribParams['invoice_id'],
'id',
'invoice_id'
);
}
- $ids = array();
- if ($contribID) {
- $ids['contribution'] = $contribID;
- $contribParams['id'] = $contribID;
- }
-
if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
$eventStartDate = CRM_Utils_Array::value(
'start_date',
@@ -1039,8 +1072,9 @@ public static function processContribution(
}
$contribParams['skipLineItem'] = 1;
+ $contribParams['skipCleanMoney'] = 1;
// create contribution record
- $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
+ $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
// CRM-11124
CRM_Event_BAO_Participant::createDiscountTrxn($form->_eventId, $contribParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($params));
@@ -1078,7 +1112,7 @@ public static function fixLocationFields(&$params, &$fields, &$form) {
// the billing fields (if they are set)
if (is_array($fields)) {
if (!array_key_exists('first_name', $fields)) {
- $nameFields = array('first_name', 'middle_name', 'last_name');
+ $nameFields = ['first_name', 'middle_name', 'last_name'];
foreach ($nameFields as $name) {
$fields[$name] = 1;
if (array_key_exists("billing_$name", $params)) {
@@ -1124,7 +1158,7 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
//particular uf group
// get the add to groups
- $addToGroups = array();
+ $addToGroups = [];
if (!empty($form->_fields)) {
foreach ($form->_fields as $key => $value) {
@@ -1196,7 +1230,7 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
}
//get email primary first if exist
- $subscribtionEmail = array('email' => CRM_Utils_Array::value('email-Primary', $params));
+ $subscribtionEmail = ['email' => CRM_Utils_Array::value('email-Primary', $params)];
if (!$subscribtionEmail['email']) {
$subscribtionEmail['email'] = CRM_Utils_Array::value("email-{$form->_bltID}", $params);
}
@@ -1215,7 +1249,7 @@ public static function updateContactFields($contactID, $params, $fields, &$form)
*/
public static function assignProfiles(&$form) {
$participantParams = $form->_params;
- $formattedValues = $profileFields = array();
+ $formattedValues = $profileFields = [];
$count = 1;
foreach ($participantParams as $participantNum => $participantValue) {
if ($participantNum) {
@@ -1229,7 +1263,7 @@ public static function assignProfiles(&$form) {
if ($participantValue != 'skip') {
//get the customPre profile info
if (!empty($form->_values[$prefix2 . 'custom_pre_id'])) {
- $values = $groupName = array();
+ $values = $groupName = [];
CRM_Event_BAO_Event::displayProfile($participantValue,
$form->_values[$prefix2 . 'custom_pre_id'],
$groupName,
@@ -1244,9 +1278,9 @@ public static function assignProfiles(&$form) {
}
//get the customPost profile info
if (!empty($form->_values[$prefix2 . 'custom_post_id'])) {
- $values = $groupName = array();
+ $values = $groupName = [];
foreach ($form->_values[$prefix2 . 'custom_post_id'] as $gids) {
- $val = array();
+ $val = [];
CRM_Event_BAO_Event::displayProfile($participantValue,
$gids,
$group,
@@ -1296,13 +1330,14 @@ public static function testSubmit($params) {
$_REQUEST['id'] = $form->_eventId = $params['id'];
$form->controller = new CRM_Event_Controller_Registration();
$form->_params = $params['params'];
- $form->_amount = $form->_totalAmount = CRM_Utils_Array::value('totalAmount', $params);
+ // This happens in buildQuickForm so emulate here.
+ $form->_amount = $form->_totalAmount = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('totalAmount', $params));
$form->set('params', $params['params']);
- $form->_values['custom_pre_id'] = array();
- $form->_values['custom_post_id'] = array();
+ $form->_values['custom_pre_id'] = [];
+ $form->_values['custom_post_id'] = [];
$form->_values['event'] = CRM_Utils_Array::value('event', $params);
$form->_contributeMode = $params['contributeMode'];
- $eventParams = array('id' => $params['id']);
+ $eventParams = ['id' => $params['id']];
CRM_Event_BAO_Event::retrieve($eventParams, $form->_values['event']);
$form->set('registerByID', $params['registerByID']);
if (!empty($params['paymentProcessorObj'])) {
@@ -1322,14 +1357,29 @@ public static function testSubmit($params) {
private function processPayment($payment, $value) {
try {
$result = $payment->doPayment($value, 'event');
- return array($result, $value);
+ return [$result, $value];
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
Civi::log()->error('Payment processor exception: ' . $e->getMessage());
CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
}
- return array();
+ return [];
+ }
+
+ /**
+ * Clean money fields from the form.
+ *
+ * @param array $params
+ */
+ protected function cleanMoneyFields(&$params) {
+ foreach ($this->submittableMoneyFields as $moneyField) {
+ foreach ($params as $index => $paramField) {
+ if (isset($paramField[$moneyField])) {
+ $params[$index][$moneyField] = CRM_Utils_Rule::cleanMoney($paramField[$moneyField]);
+ }
+ }
+ }
}
}
diff --git a/CRM/Event/Form/Registration/ParticipantConfirm.php b/CRM/Event/Form/Registration/ParticipantConfirm.php
index 2d134f3950dc..e64d4e9e3443 100644
--- a/CRM/Event/Form/Registration/ParticipantConfirm.php
+++ b/CRM/Event/Form/Registration/ParticipantConfirm.php
@@ -1,9 +1,9 @@
_cc = CRM_Utils_Request::retrieve('cc', 'String', $this);
//get the contact and event id and assing to session.
- $values = array();
+ $values = [];
$csContactID = NULL;
if ($this->_participantId) {
- $params = array('id' => $this->_participantId);
+ $params = ['id' => $this->_participantId];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Participant', $params, $values,
- array('contact_id', 'event_id', 'status_id')
+ ['contact_id', 'event_id', 'status_id']
);
}
@@ -95,13 +98,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $params = array('id' => $this->_eventId);
- $values = array();
+ $params = ['id' => $this->_eventId];
+ $values = [];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $values,
- array('title')
+ ['title']
);
- $buttons = array();
+ $buttons = [];
// only pending status class family able to confirm.
$statusMsg = NULL;
@@ -115,27 +118,27 @@ public function buildQuickForm() {
$additonalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
$requireSpace = 1 + count($additonalIds);
if ($emptySeats !== NULL && ($requireSpace > $emptySeats)) {
- $statusMsg = ts("Oops, it looks like there are currently no available spaces for the %1 event.", array(1 => $values['title']));
+ $statusMsg = ts("Oops, it looks like there are currently no available spaces for the %1 event.", [1 => $values['title']]);
}
else {
if ($this->_cc == 'fail') {
- $statusMsg = '
' . ts('Your Credit Card transaction was not successful. No money has yet been charged to your card.') . '
' . ts('Click the "Confirm Registration" button to complete your registration in %1, or click "Cancel Registration" if you are no longer interested in attending this event.', array(
- 1 => $values['title'],
- )) . '
';
+ $statusMsg = '
' . ts('Your Credit Card transaction was not successful. No money has yet been charged to your card.') . '
' . ts('Click the "Confirm Registration" button to complete your registration in %1, or click "Cancel Registration" if you are no longer interested in attending this event.', [
+ 1 => $values['title'],
+ ]) . '
';
}
else {
- $statusMsg = '
' . ts('Confirm your registration for %1.', array(
- 1 => $values['title'],
- )) . '
' . ts('Click the "Confirm Registration" button to begin, or click "Cancel Registration" if you are no longer interested in attending this event.') . '
';
+ $statusMsg = '
' . ts('Confirm your registration for %1.', [
+ 1 => $values['title'],
+ ]) . '
' . ts('Click the "Confirm Registration" button to begin, or click "Cancel Registration" if you are no longer interested in attending this event.') . '
';
}
- $buttons = array_merge($buttons, array(
- array(
+ $buttons = array_merge($buttons, [
+ [
'type' => 'next',
'name' => ts('Confirm Registration'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
@@ -144,21 +147,21 @@ public function buildQuickForm() {
CRM_Event_PseudoConstant::participantStatus(NULL, "class != 'Negative'")
)) {
$cancelConfirm = ts('Are you sure you want to cancel your registration for this event?');
- $buttons = array_merge($buttons, array(
- array(
+ $buttons = array_merge($buttons, [
+ [
'type' => 'submit',
'name' => ts('Cancel Registration'),
'spacing' => ' ',
- 'js' => array('onclick' => 'return confirm(\'' . $cancelConfirm . '\');'),
- ),
- ));
+ 'js' => ['onclick' => 'return confirm(\'' . $cancelConfirm . '\');'],
+ ],
+ ]);
if (!$statusMsg) {
- $statusMsg = ts('You can cancel your registration for %1 by clicking "Cancel Registration".', array(1 => $values['title']));
+ $statusMsg = ts('You can cancel your registration for %1 by clicking "Cancel Registration".', [1 => $values['title']]);
}
}
if (!$statusMsg) {
$statusMsg = ts("Oops, it looks like your registration for %1 has already been cancelled.",
- array(1 => $values['title'])
+ [1 => $values['title']]
);
}
$this->assign('statusMsg', $statusMsg);
@@ -196,11 +199,11 @@ public function postProcess() {
$cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
- $participantIds = array_merge(array($participantId), $additionalParticipantIds);
+ $participantIds = array_merge([$participantId], $additionalParticipantIds);
$results = CRM_Event_BAO_Participant::transitionParticipants($participantIds, $cancelledId, NULL, TRUE);
if (count($participantIds) > 1) {
- $statusMessage = ts("%1 Event registration(s) have been cancelled.", array(1 => count($participantIds)));
+ $statusMessage = ts("%1 Event registration(s) have been cancelled.", [1 => count($participantIds)]);
}
else {
$statusMessage = ts("Your Event Registration has been cancelled.");
@@ -208,7 +211,7 @@ public function postProcess() {
if (!empty($results['mailedParticipants'])) {
foreach ($results['mailedParticipants'] as $key => $displayName) {
- $statusMessage .= " " . ts("Email has been sent to : %1", array(1 => $displayName));
+ $statusMessage .= " " . ts("Email has been sent to : %1", [1 => $displayName]);
}
}
diff --git a/CRM/Event/Form/Registration/Register.php b/CRM/Event/Form/Registration/Register.php
index f2418bfc0214..fd5a218f3e8e 100644
--- a/CRM/Event/Form/Registration/Register.php
+++ b/CRM/Event/Form/Registration/Register.php
@@ -1,9 +1,9 @@
getContactID();
+ $contactID = $form->getContactID();
}
if (!$contactID && is_array($fields) && $fields) {
- $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $self->_values['event']));
+ $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $form->_values['event']), ['event_id' => CRM_Utils_Array::value('id', $form->_values['event'])]);
}
return $contactID;
}
@@ -116,7 +123,7 @@ public function preProcess() {
// We hide the payment fields if the event is full or requires approval,
// and the current user has not yet been approved CRM-12279
$this->_noFees = (($eventFull || $this->_requireApproval) && !$this->_allowConfirmation);
- $this->_paymentProcessors = $this->_noFees ? array() : $this->get('paymentProcessors');
+ $this->_paymentProcessors = $this->_noFees ? [] : $this->get('paymentProcessors');
$this->preProcessPaymentOptions();
$this->_allowWaitlist = FALSE;
@@ -146,7 +153,7 @@ public function preProcess() {
* Set default values for the form.
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
if (!$this->_allowConfirmation && $this->_requireApproval) {
$this->_defaults['bypass_payment'] = 1;
}
@@ -223,7 +230,7 @@ public function setDefaultValues() {
if (empty($val['options'])) {
continue;
}
- $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, array());
+ $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, []);
foreach ($val['options'] as $keys => $values) {
if ($values['is_default'] && empty($values['is_full'])) {
@@ -301,7 +308,7 @@ public function buildQuickForm() {
if (!$this->_allowConfirmation || $this->_additionalParticipantIds) {
// CRM-17745: Make maximum additional participants configurable
// Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
- $additionalOptions = array();
+ $additionalOptions = [];
$additionalOptions[''] = 1;
for ($i = 1; $i <= $this->_values['event']['max_additional_participants']; $i++) {
$additionalOptions[$i] = $i + 1;
@@ -310,7 +317,7 @@ public function buildQuickForm() {
ts('How many people are you registering?'),
$additionalOptions,
NULL,
- array('onChange' => "allowParticipant()")
+ ['onChange' => "allowParticipant()"]
);
$isAdditionalParticipants = TRUE;
}
@@ -331,7 +338,7 @@ public function buildQuickForm() {
//case might be group become as a part of waitlist.
//If not waitlist then they require admin approve.
$allowGroupOnWaitlist = TRUE;
- $this->_waitlistMsg = ts("This event has only %1 space(s) left. If you continue and register more than %1 people (including yourself ), the whole group will be wait listed. Or, you can reduce the number of people you are registering to %1 to avoid being put on the waiting list.", array(1 => $this->_availableRegistrations));
+ $this->_waitlistMsg = ts("This event has only %1 space(s) left. If you continue and register more than %1 people (including yourself ), the whole group will be wait listed. Or, you can reduce the number of people you are registering to %1 to avoid being put on the waiting list.", [1 => $this->_availableRegistrations]);
if ($this->_requireApproval) {
$this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
@@ -359,7 +366,7 @@ public function buildQuickForm() {
self::buildAmount($this);
}
- $pps = array();
+ $pps = [];
//@todo this processor adding fn is another one duplicated on contribute - a shared
// common class would make this sort of thing extractable
$onlinePaymentProcessorEnabled = FALSE;
@@ -394,7 +401,7 @@ public function buildQuickForm() {
}
}
- $this->addElement('hidden', 'bypass_payment', NULL, array('id' => 'bypass_payment'));
+ $this->addElement('hidden', 'bypass_payment', NULL, ['id' => 'bypass_payment']);
$this->assign('bypassPayment', $bypassPayment);
@@ -412,7 +419,7 @@ public function buildQuickForm() {
$this->_values['custom_post_id']
) {
if (!is_array($this->_values['custom_post_id'])) {
- $profileIDs = array($this->_values['custom_post_id']);
+ $profileIDs = [$this->_values['custom_post_id']];
}
else {
$profileIDs = $this->_values['custom_post_id'];
@@ -457,7 +464,7 @@ public function buildQuickForm() {
$js = NULL;
if (empty($this->_values['event']['is_monetary'])) {
- $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
+ $js = ['onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');"];
}
// CRM-11182 - Optional confirmation screen
@@ -473,19 +480,18 @@ public function buildQuickForm() {
$buttonLabel = ts('Continue');
}
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => $buttonLabel,
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- 'js' => $js,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => $buttonLabel,
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ 'js' => $js,
+ ],
+ ]);
}
- $this->addFormRule(array('CRM_Event_Form_Registration_Register', 'formRule'), $this);
+ $this->addFormRule(['CRM_Event_Form_Registration_Register', 'formRule'], $this);
$this->unsavedChangesWarn = TRUE;
// add pcp fields
@@ -497,14 +503,14 @@ public function buildQuickForm() {
/**
* Build the radio/text form elements for the amount field
*
- * @param CRM_Core_Form $form
+ * @param CRM_Event_Form_Registration_Register $form
* Form object.
* @param bool $required
* True if you want to add formRule.
* @param int $discountId
* Discount id for the event.
*/
- static public function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
+ public static function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
// build amount only when needed, skip incase of event full and waitlisting is enabled
// and few other conditions check preProcess()
if (property_exists($form, '_noFees') && $form->_noFees) {
@@ -535,7 +541,7 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
}
}
if (!is_array($form->_feeBlock)) {
- $form->_feeBlock = array();
+ $form->_feeBlock = [];
}
//its time to call the hook.
@@ -588,20 +594,24 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
//user might modified w/ hook.
$options = CRM_Utils_Array::value('options', $field);
- $formClasses = array('CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection');
+ $formClasses = ['CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection'];
if (!is_array($options)) {
continue;
}
elseif ($hideAdminValues && !in_array($className, $formClasses)) {
+ $publicVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('public');
+ $adminVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('admin');
+
foreach ($options as $key => $currentOption) {
- if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField::getVisibilityOptionID('admin')) {
+ $optionVisibility = CRM_Utils_Array::value('visibility_id', $currentOption, $publicVisibilityID);
+ if ($optionVisibility == $adminVisibilityID) {
unset($options[$key]);
}
}
}
- $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, array());
+ $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, []);
//soft suppress required rule when option is full.
if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
@@ -624,14 +634,14 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
$form->assign('priceSet', $form->_priceSet);
}
else {
- $eventFeeBlockValues = array();
+ $eventFeeBlockValues = [];
foreach ($form->_feeBlock as $fee) {
if (is_array($fee)) {
//CRM-7632, CRM-6201
$totalAmountJs = NULL;
if ($className == 'CRM_Event_Form_Participant') {
- $totalAmountJs = array('onClick' => "fillTotalAmount(" . $fee['value'] . ")");
+ $totalAmountJs = ['onClick' => "fillTotalAmount(" . $fee['value'] . ")"];
}
$eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
@@ -657,12 +667,12 @@ static public function buildAmount(&$form, $required = TRUE, $discountId = NULL)
}
/**
- * @param CRM_Core_Form $form
+ * @param CRM_Event_Form_Registration $form
*/
public static function formatFieldsForOptionFull(&$form) {
$priceSet = $form->get('priceSet');
$priceSetId = $form->get('priceSetId');
- $defaultPricefieldIds = array();
+ $defaultPricefieldIds = [];
if (!empty($form->_values['line_items'])) {
foreach ($form->_values['line_items'] as $lineItem) {
$defaultPricefieldIds[] = $lineItem['price_field_value_id'];
@@ -675,7 +685,7 @@ public static function formatFieldsForOptionFull(&$form) {
return;
}
- $skipParticipants = $formattedPriceSetDefaults = array();
+ $skipParticipants = $formattedPriceSetDefaults = [];
if (!empty($form->_allowConfirmation) && (isset($form->_pId) || isset($form->_additionalParticipantId))) {
$participantId = isset($form->_pId) ? $form->_pId : $form->_additionalParticipantId;
$pricesetDefaults = CRM_Event_Form_EventFees::setDefaultPriceSet($participantId,
@@ -700,7 +710,7 @@ public static function formatFieldsForOptionFull(&$form) {
$optionFullTotalAmount = 0;
$currentParticipantNo = (int) substr($form->_name, 12);
foreach ($form->_feeBlock as & $field) {
- $optionFullIds = array();
+ $optionFullIds = [];
$fieldId = $field['id'];
if (!is_array($field['options'])) {
continue;
@@ -750,7 +760,7 @@ public static function formatFieldsForOptionFull(&$form) {
//ignore option full for offline registration.
if ($className == 'CRM_Event_Form_Participant') {
- $optionFullIds = array();
+ $optionFullIds = [];
}
//finally get option ids in.
@@ -766,40 +776,40 @@ public static function formatFieldsForOptionFull(&$form) {
* The input form values.
* @param array $files
* The uploaded files if any.
- * @param $self
+ * @param CRM_Event_Form_Registration $form
*
*
* @return bool|array
* true if no errors, else array of errors
*/
- public static function formRule($fields, $files, $self) {
- $errors = array();
+ public static function formRule($fields, $files, $form) {
+ $errors = [];
//check that either an email or firstname+lastname is included in the form(CRM-9587)
- self::checkProfileComplete($fields, $errors, $self->_eventId);
+ self::checkProfileComplete($fields, $errors, $form->_eventId);
//To check if the user is already registered for the event(CRM-2426)
- if (!$self->_skipDupeRegistrationCheck) {
- self::checkRegistration($fields, $self);
+ if (!$form->_skipDupeRegistrationCheck) {
+ self::checkRegistration($fields, $form);
}
//check for availability of registrations.
- if (!$self->_allowConfirmation && empty($fields['bypass_payment']) &&
- is_numeric($self->_availableRegistrations) &&
- CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations
+ if (!$form->_allowConfirmation && empty($fields['bypass_payment']) &&
+ is_numeric($form->_availableRegistrations) &&
+ CRM_Utils_Array::value('additional_participants', $fields) >= $form->_availableRegistrations
) {
- $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations));
+ $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", [1 => $form->_availableRegistrations]);
}
// during confirmation don't allow to increase additional participants, CRM-4320
- if ($self->_allowConfirmation && !empty($fields['additional_participants']) &&
- is_array($self->_additionalParticipantIds) &&
- $fields['additional_participants'] > count($self->_additionalParticipantIds)
+ if ($form->_allowConfirmation && !empty($fields['additional_participants']) &&
+ is_array($form->_additionalParticipantIds) &&
+ $fields['additional_participants'] > count($form->_additionalParticipantIds)
) {
- $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", array(1 => count($self->_additionalParticipantIds)));
+ $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", [1 => count($form->_additionalParticipantIds)]);
}
//don't allow to register w/ waiting if enough spaces available.
- if (!empty($fields['bypass_payment']) && $self->_allowConfirmation) {
- if (!is_numeric($self->_availableRegistrations) ||
- (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations)
+ if (!empty($fields['bypass_payment']) && $form->_allowConfirmation) {
+ if (!is_numeric($form->_availableRegistrations) ||
+ (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $form->_availableRegistrations)
) {
$errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
}
@@ -813,16 +823,16 @@ public static function formRule($fields, $files, $self) {
// priceset validations
if (!empty($fields['priceSetId']) &&
- !$self->_requireApproval && !$self->_allowWaitlist
+ !$form->_requireApproval && !$form->_allowWaitlist
) {
//format params.
- $formatted = self::formatPriceSetParams($self, $fields);
- $ppParams = array($formatted);
- $priceSetErrors = self::validatePriceSet($self, $ppParams);
- $primaryParticipantCount = self::getParticipantCount($self, $ppParams);
+ $formatted = self::formatPriceSetParams($form, $fields);
+ $ppParams = [$formatted];
+ $priceSetErrors = self::validatePriceSet($form, $ppParams);
+ $primaryParticipantCount = self::getParticipantCount($form, $ppParams);
//get price set fields errors in.
- $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
+ $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, []));
$totalParticipants = $primaryParticipantCount;
if (!empty($fields['additional_participants'])) {
@@ -830,30 +840,30 @@ public static function formRule($fields, $files, $self) {
}
if (empty($fields['bypass_payment']) &&
- !$self->_allowConfirmation &&
- is_numeric($self->_availableRegistrations) &&
- $self->_availableRegistrations < $totalParticipants
+ !$form->_allowConfirmation &&
+ is_numeric($form->_availableRegistrations) &&
+ $form->_availableRegistrations < $totalParticipants
) {
- $errors['_qf_default'] = ts("Only %1 Registrations available.", array(1 => $self->_availableRegistrations));
+ $errors['_qf_default'] = ts("Only %1 Registrations available.", [1 => $form->_availableRegistrations]);
}
- $lineItem = array();
- CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
+ $lineItem = [];
+ CRM_Price_BAO_PriceSet::processAmount($form->_values['fee'], $fields, $lineItem);
$minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
if ($fields['amount'] < 0) {
$errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
}
elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
- $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', array(
+ $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', [
1 => CRM_Utils_Money::format($minAmt),
- ));
+ ]);
}
}
// @todo - can we remove the 'is_monetary' concept?
- if ($self->_values['event']['is_monetary']) {
- if (empty($self->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
+ if ($form->_values['event']['is_monetary']) {
+ if (empty($form->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
!isset($fields['payment_processor_id'])) {
$errors['payment_processor_id'] = ts('Please select a Payment Method');
}
@@ -865,28 +875,28 @@ public static function formRule($fields, $files, $self) {
}
}
elseif (!empty($fields['amount']) &&
- (isset($self->_values['discount'][$fields['amount']])
- && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0
+ (isset($form->_values['discount'][$fields['amount']])
+ && CRM_Utils_Array::value('value', $form->_values['discount'][$fields['amount']]) == 0
)
) {
$isZeroAmount = TRUE;
}
elseif (!empty($fields['amount']) &&
- (isset($self->_values['fee'][$fields['amount']])
- && CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) == 0
+ (isset($form->_values['fee'][$fields['amount']])
+ && CRM_Utils_Array::value('value', $form->_values['fee'][$fields['amount']]) == 0
)
) {
$isZeroAmount = TRUE;
}
- if ($isZeroAmount && !($self->_forcePayement && !empty($fields['additional_participants']))) {
+ if ($isZeroAmount && !($form->_forcePayement && !empty($fields['additional_participants']))) {
$skipPaymentValidation = TRUE;
}
// also return if zero fees for valid members
if (!empty($fields['bypass_payment']) ||
$skipPaymentValidation ||
- (!$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist))
+ (!$form->_allowConfirmation && ($form->_requireApproval || $form->_allowWaitlist))
) {
return empty($errors) ? TRUE : $errors;
}
@@ -894,16 +904,16 @@ public static function formRule($fields, $files, $self) {
$fields['payment_processor_id'],
$fields,
$errors,
- (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
+ (!$form->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
);
}
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
- $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
+ $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
$errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
- array(1 => ucwords(str_replace('_', ' ', $greeting)))
+ [1 => ucwords(str_replace('_', ' ', $greeting))]
);
}
}
@@ -927,7 +937,7 @@ public static function checkProfileComplete($fields, &$errors, $eventId) {
}
if (!$email && !(!empty($fields['first_name']) && !empty($fields['last_name']))) {
- $defaults = $params = array('id' => $eventId);
+ $defaults = $params = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
$errors['_qf_default'] = $message;
@@ -1039,7 +1049,7 @@ public function postProcess() {
}
}
else {
- $lineItem = array();
+ $lineItem = [];
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
if ($params['tax_amount']) {
$this->set('tax_amount', $params['tax_amount']);
@@ -1049,11 +1059,11 @@ public function postProcess() {
$submittedLineItems[0] = $lineItem;
}
else {
- $submittedLineItems = array($lineItem);
+ $submittedLineItems = [$lineItem];
}
$submittedLineItems = array_filter($submittedLineItems);
$this->set('lineItem', $submittedLineItems);
- $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
+ $this->set('lineItemParticipantsCount', [$primaryParticipantCount]);
}
$this->set('amount', $params['amount']);
@@ -1100,7 +1110,7 @@ public function postProcess() {
$this->_params[0] = $params;
}
else {
- $this->_params = array();
+ $this->_params = [];
$this->_params[] = $params;
}
$this->set('params', $this->_params);
@@ -1139,7 +1149,7 @@ public function postProcess() {
$this->handlePreApproval($params);
}
elseif ($this->_paymentProcessor &&
- $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
+ (int) $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
) {
// The concept of contributeMode is deprecated - but still needs removal from the message templates.
$this->set('contributeMode', 'notify');
@@ -1148,13 +1158,14 @@ public function postProcess() {
else {
$params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
- $this->_params = array();
+ $this->_params = [];
$this->_params[] = $params;
$this->set('params', $this->_params);
if (
empty($params['additional_participants'])
- && !$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
+ // CRM-11182 - Optional confirmation screen
+ && !$this->_values['event']['is_confirm_enabled']
) {
$this->processRegistration($this->_params);
}
@@ -1173,58 +1184,58 @@ public function postProcess() {
*
* @param array $fields
* The input form values(anonymous user).
- * @param CRM_Event_Form_Registration_Register $self
+ * @param CRM_Event_Form_Registration_Register $form
* Event data.
* @param bool $isAdditional
* Treat isAdditional participants a bit differently.
*
* @return int
*/
- public static function checkRegistration($fields, &$self, $isAdditional = FALSE) {
+ public static function checkRegistration($fields, $form, $isAdditional = FALSE) {
// CRM-3907, skip check for preview registrations
// CRM-4320 participant need to walk wizard
if (
- ($self->_mode == 'test' || $self->_allowConfirmation)
+ ($form->_mode == 'test' || $form->_allowConfirmation)
) {
return FALSE;
}
- $contactID = self::getRegistrationContactID($fields, $self, $isAdditional);
+ $contactID = self::getRegistrationContactID($fields, $form, $isAdditional);
if ($contactID) {
$participant = new CRM_Event_BAO_Participant();
$participant->contact_id = $contactID;
- $participant->event_id = $self->_values['event']['id'];
+ $participant->event_id = $form->_values['event']['id'];
if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
$participant->role_id = $fields['participant_role'];
}
else {
- $participant->role_id = $self->_values['event']['default_role_id'];
+ $participant->role_id = $form->_values['event']['default_role_id'];
}
$participant->is_test = 0;
$participant->find();
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
while ($participant->fetch()) {
if (array_key_exists($participant->status_id, $statusTypes)) {
- if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
+ if (!$isAdditional && !$form->_values['event']['allow_same_participant_emails']) {
$registerUrl = CRM_Utils_System::url('civicrm/event/register',
- "reset=1&id={$self->_values['event']['id']}&cid=0"
+ "reset=1&id={$form->_values['event']['id']}&cid=0"
);
- if ($self->_pcpId) {
- $registerUrl .= '&pcpId=' . $self->_pcpId;
+ if ($form->_pcpId) {
+ $registerUrl .= '&pcpId=' . $form->_pcpId;
}
- $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', array(1 => $registerUrl));
+ $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', [1 => $registerUrl]);
CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
$url = CRM_Utils_System::url('civicrm/event/info',
- "reset=1&id={$self->_values['event']['id']}&noFullMsg=true"
+ "reset=1&id={$form->_values['event']['id']}&noFullMsg=true"
);
- if ($self->_action & CRM_Core_Action::PREVIEW) {
+ if ($form->_action & CRM_Core_Action::PREVIEW) {
$url .= '&action=preview';
}
- if ($self->_pcpId) {
- $url .= '&pcpId=' . $self->_pcpId;
+ if ($form->_pcpId) {
+ $url .= '&pcpId=' . $form->_pcpId;
}
CRM_Utils_System::redirect($url);
diff --git a/CRM/Event/Form/Registration/ThankYou.php b/CRM/Event/Form/Registration/ThankYou.php
index 3a29a96eeaef..7c13ada6f6a8 100644
--- a/CRM/Event/Form/Registration/ThankYou.php
+++ b/CRM/Event/Form/Registration/ThankYou.php
@@ -1,9 +1,9 @@
assignToTemplate();
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
+ $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
$getTaxDetails = FALSE;
$taxAmount = 0;
- $lineItemForTemplate = array();
+ $lineItemForTemplate = [];
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
if (!empty($value) && $value != 'skip') {
@@ -129,7 +127,7 @@ public function buildQuickForm() {
if ($invoicing) {
$this->assign('getTaxDetails', $getTaxDetails);
$this->assign('totalTaxAmount', $taxAmount);
- $this->assign('taxTerm', $taxTerm);
+ $this->assign('taxTerm', CRM_Invoicing_Utils::getTaxTerm());
}
$this->assign('totalAmount', $this->_totalAmount);
@@ -148,8 +146,8 @@ public function buildQuickForm() {
if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
$this->assign('defaultRole', TRUE);
}
- $defaults = array();
- $fields = array();
+ $defaults = [];
+ $fields = [];
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $dontCare) {
$fields[$name] = 1;
@@ -179,7 +177,7 @@ public function buildQuickForm() {
$params['entity_id'] = $this->_eventId;
$params['entity_table'] = 'civicrm_event';
- $data = array();
+ $data = [];
CRM_Friend_BAO_Friend::retrieve($params, $data);
if (!empty($data['is_active'])) {
$friendText = $data['title'];
diff --git a/CRM/Event/Form/Search.php b/CRM/Event/Form/Search.php
index 455210313596..4a61657ee308 100644
--- a/CRM/Event/Form/Search.php
+++ b/CRM/Event/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
- $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
- $this->assign("context", $this->_context);
-
- // get user submitted values
- // get it from controller only if form has been submitted, else preProcess has set this
- if (!empty($_POST) && !$this->controller->isModal()) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- }
- else {
- $this->_formValues = $this->get('formValues');
- }
-
- if (empty($this->_formValues)) {
- if (isset($this->_ssID)) {
- $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
- }
- }
+ $this->loadStandardSearchOptionsFromUrl();
+ $this->loadFormValues();
if ($this->_force) {
$this->postProcess();
@@ -130,7 +105,7 @@ public function preProcess() {
);
}
- $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
+ $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, ['event_id']);
$selector = new CRM_Event_Selector_Search($this->_queryParams,
$this->_action,
NULL,
@@ -168,17 +143,13 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
-
- if (CRM_Core_Permission::check('access deleted contacts') and Civi::settings()->get('contact_undelete')) {
- $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . ' ' . ts('(deleted contacts)'));
- }
+ $this->addContactSearchFields();
CRM_Event_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
- $lineItems = $eventIds = array();
+ $lineItems = $eventIds = [];
if (!$this->_single) {
$this->addRowSelectors($rows);
}
@@ -194,18 +165,18 @@ public function buildQuickForm() {
$participantCount = 0;
if (count($eventIds) == 1) {
//convert form values to clause.
- $seatClause = array();
+ $seatClause = [];
if (CRM_Utils_Array::value('participant_test', $this->_formValues) == '1' || CRM_Utils_Array::value('participant_test', $this->_formValues) == '0') {
$seatClause[] = "( participant.is_test = {$this->_formValues['participant_test']} )";
}
if (!empty($this->_formValues['participant_status_id'])) {
- $seatClause[] = CRM_Contact_BAO_Query::buildClause("participant.status_id", '=', $this->_formValues['participant_status_id'], 'Int');
+ $seatClause[] = CRM_Contact_BAO_Query::buildClause("participant.status_id", 'IN', $this->_formValues['participant_status_id'], 'Int');
if ($status = CRM_Utils_Array::value('IN', $this->_formValues['participant_status_id'])) {
$this->_formValues['participant_status_id'] = $status;
}
}
if (!empty($this->_formValues['participant_role_id'])) {
- $escapedRoles = array();
+ $escapedRoles = [];
foreach ((array) $this->_formValues['participant_role_id'] as $participantRole) {
$escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
}
@@ -215,11 +186,13 @@ public function buildQuickForm() {
// CRM-15379
if (!empty($this->_formValues['participant_fee_id'])) {
$participant_fee_id = $this->_formValues['participant_fee_id'];
+ $val_regexp = [];
foreach ($participant_fee_id as $k => &$val) {
$val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
+ $val_regexp[$k] = CRM_Core_DAO::escapeString(preg_quote(trim($val)));
$val = CRM_Core_DAO::escapeString(trim($val));
}
- $feeLabel = implode('|', $participant_fee_id);
+ $feeLabel = implode('|', $val_regexp);
$seatClause[] = "( participant.fee_level REGEXP '{$feeLabel}' )";
}
@@ -229,18 +202,14 @@ public function buildQuickForm() {
$this->assign('participantCount', $participantCount);
$this->assign('lineItems', $lineItems);
- $permission = CRM_Core_Permission::getPermission();
+ $taskParams['ssID'] = isset($this->_ssID) ? $this->_ssID : NULL;
+ $tasks = CRM_Event_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission(), $taskParams);
- $tasks = CRM_Event_Task::permissionedTaskTitles($permission);
if (isset($this->_ssID)) {
- if ($permission == CRM_Core_Permission::EDIT) {
- $tasks = $tasks + CRM_Event_Task::optionalTaskTitle();
- }
-
- $savedSearchValues = array(
+ $savedSearchValues = [
'id' => $this->_ssID,
'name' => CRM_Contact_BAO_SavedSearch::getName($this->_ssID, 'title'),
- );
+ ];
$this->assign_by_ref('savedSearch', $savedSearchValues);
$this->assign('ssID', $this->_ssID);
}
@@ -273,36 +242,49 @@ protected function getSortNameLabelWithOutEmail() {
}
/**
- * The post processing of the form gets done here.
+ * Get the label for the tag field.
*
- * Key things done during post processing are
- * - check for reset or next request. if present, skip post procesing.
- * - now check if user requested running a saved search, if so, then
- * the form values associated with the saved search are used for searching.
- * - if user has done a submit with new values the regular post submissing is
- * done.
- * The processing consists of using a Selector / Controller framework for getting the
- * search results.
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
*
- * @param
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Participant Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
*
- * @return void
+ * @return string
*/
- public function postProcess() {
- if ($this->_done) {
- return;
- }
+ protected function getGroupLabel() {
+ return ts('Participant Group(s)');
+ }
- $this->_done = TRUE;
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Participant Contact Type');
+ }
- if (!empty($_POST)) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, array('participant_status_id'));
- }
+ /**
+ * Test submit the form.
+ * @param $formValues
+ */
+ public function testSubmit($formValues) {
+ $this->submit($formValues);
+ }
- if (empty($this->_formValues)) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- }
+ /**
+ * Submit the search form with given values.
+ * @param $formValues
+ */
+ private function submit($formValues) {
+ $this->_formValues = $formValues;
$this->fixFormValues();
@@ -318,7 +300,7 @@ public function postProcess() {
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
- $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
+ $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, ['event_id']);
$this->set('formValues', $this->_formValues);
$this->set('queryParams', $this->_queryParams);
@@ -341,7 +323,7 @@ public function postProcess() {
);
}
- $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
+ $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, ['event_id']);
$selector = new CRM_Event_Selector_Search($this->_queryParams,
$this->_action,
@@ -378,6 +360,42 @@ public function postProcess() {
$controller->run();
}
+ /**
+ * The post processing of the form gets done here.
+ *
+ * Key things done during post processing are
+ * - check for reset or next request. if present, skip post procesing.
+ * - now check if user requested running a saved search, if so, then
+ * the form values associated with the saved search are used for searching.
+ * - if user has done a submit with new values the regular post submissing is
+ * done.
+ * The processing consists of using a Selector / Controller framework for getting the
+ * search results.
+ *
+ * @param
+ *
+ * @return void
+ */
+ public function postProcess() {
+ if ($this->_done) {
+ return;
+ }
+
+ $this->_done = TRUE;
+ $formValues = [];
+
+ if (!empty($_POST)) {
+ $formValues = $this->controller->exportValues($this->_name);
+ CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, ['participant_status_id']);
+ }
+
+ if (empty($this->_formValues)) {
+ $formValues = $this->controller->exportValues($this->_name);
+ }
+
+ $this->submit($formValues);
+ }
+
/**
* add the rules (mainly global rules) for form.
* All local rules are added near the element
@@ -396,7 +414,7 @@ public function addRules() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults = $this->_formValues;
return $defaults;
}
@@ -426,7 +444,7 @@ public function fixFormValues() {
elseif (is_array($status) && !array_key_exists('IN', $status)) {
$statusTypes = array_keys($status);
}
- $this->_formValues['participant_status_id'] = is_array($statusTypes) ? array('IN' => array_keys($statusTypes)) : $statusTypes;
+ $this->_formValues['participant_status_id'] = is_array($statusTypes) ? ['IN' => array_keys($statusTypes)] : $statusTypes;
}
$role = CRM_Utils_Request::retrieve('role', 'String');
diff --git a/CRM/Event/Form/SearchEvent.php b/CRM/Event/Form/SearchEvent.php
index d76fb9e4adec..402535ceb893 100644
--- a/CRM/Event/Form/SearchEvent.php
+++ b/CRM/Event/Form/SearchEvent.php
@@ -1,9 +1,9 @@
_showHide = new CRM_Core_ShowHideBlocks();
@@ -60,32 +60,31 @@ public function setDefaultValues() {
/**
* Build the form object.
*
- *
- * @return void
+ * @throws \CRM_Core_Exception
*/
public function buildQuickForm() {
- $this->add('text', 'title', ts('Find'),
- array(CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'title'))
+ $this->add('text', 'title', ts('Event Name'),
+ [CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'title')]
);
- $this->addSelect('event_type_id', array('multiple' => TRUE, 'context' => 'search'));
+ $this->addSelect('event_type_id', ['multiple' => TRUE, 'context' => 'search']);
- $eventsByDates = array();
- $searchOption = array(ts('Show Current and Upcoming Events'), ts('Search All or by Date Range'));
- $this->addRadio('eventsByDates', ts('Events by Dates'), $searchOption, array('onclick' => "return showHideByValue('eventsByDates','1','id_fromToDates','block','radio',true);"), " ");
+ $eventsByDates = [];
+ $searchOption = [ts('Show Current and Upcoming Events'), ts('Search All or by Date Range')];
+ $this->addRadio('eventsByDates', ts('Events by Dates'), $searchOption, ['onclick' => "return showHideByValue('eventsByDates','1','id_fromToDates','block','radio',true);"], ' ');
- $this->addDate('start_date', ts('From'), FALSE, array('formatType' => 'searchDate'));
- $this->addDate('end_date', ts('To'), FALSE, array('formatType' => 'searchDate'));
+ $this->add('datepicker', 'start_date', ts('From'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'end_date', ts('To'), [], FALSE, ['time' => FALSE]);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($this);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
public function postProcess() {
@@ -93,14 +92,13 @@ public function postProcess() {
$parent = $this->controller->getParent();
$parent->set('searchResult', 1);
if (!empty($params)) {
- $fields = array('title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id');
+ $fields = ['title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
) {
- if (substr($field, -4) == 'date') {
- $time = ($field == 'end_date') ? '235959' : NULL;
- $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
+ if ($field === 'end_date') {
+ $parent->set($field, $params[$field] . ' 23:59:59');
}
else {
$parent->set($field, $params[$field]);
diff --git a/CRM/Event/Form/SelfSvcTransfer.php b/CRM/Event/Form/SelfSvcTransfer.php
index 4469b0ef4ed6..c3af950956bf 100644
--- a/CRM/Event/Form/SelfSvcTransfer.php
+++ b/CRM/Event/Form/SelfSvcTransfer.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -29,7 +29,7 @@
/**
*
* @package CRM
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
* $Id$
*
*/
@@ -109,32 +109,39 @@ class CRM_Event_Form_SelfSvcTransfer extends CRM_Core_Form {
*
* @var string
*/
- protected $_participant = array();
+ protected $_participant = [];
/**
* particpant values
*
- * @array string
+ * @var string
*/
protected $_part_values;
/**
* details
*
- * @array string
+ * @var array
*/
- protected $_details = array();
+ protected $_details = [];
/**
* line items
*
- * @array string
+ * @var array
*/
- protected $_line_items = array();
+ protected $_line_items = [];
/**
* contact_id
*
- * @array string
+ * @var int
*/
protected $contact_id;
+ /**
+ * Is backoffice form?
+ *
+ * @var bool
+ */
+ protected $isBackoffice = FALSE;
+
/**
* Get source values for transfer based on participant id in URL. Line items will
* be transferred to this participant - at this point no transaction changes processed
@@ -147,8 +154,9 @@ public function preProcess() {
$this->_userContext = $session->readUserContext();
$this->_from_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
- $params = array('id' => $this->_from_participant_id);
- $participant = $values = array();
+ $this->isBackoffice = CRM_Utils_Request::retrieve('is_backoffice', 'String', $this, FALSE, NULL, 'REQUEST');
+ $params = ['id' => $this->_from_participant_id];
+ $participant = $values = [];
$this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
$this->_part_values = $values[$this->_from_participant_id];
$this->set('values', $this->_part_values);
@@ -163,7 +171,7 @@ public function preProcess() {
if ($this->_from_participant_id) {
$this->assign('participantId', $this->_from_participant_id);
}
- $event = array();
+ $event = [];
$daoName = 'title';
$this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
$daoName = 'start_date';
@@ -171,7 +179,7 @@ public function preProcess() {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_from_contact_id);
$this->_contact_name = $displayName;
$this->_contact_email = $email;
- $details = array();
+ $details = [];
$details = CRM_Event_BAO_Participant::participantDetails($this->_from_participant_id);
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
$query = "
@@ -204,16 +212,24 @@ public function preProcess() {
* return @void
*/
public function buildQuickForm() {
- $this->add('text', 'email', ts('To Email'), ts($this->_contact_email), TRUE);
- $this->add('text', 'last_name', ts('To Last Name'), ts($this->_to_contact_last_name), TRUE);
- $this->add('text', 'first_name', ts('To First Name'), ts($this->_to_contact_first_name), TRUE);
- $this->addButtons(array(
- array(
+ // use entityRef select field for contact when this form is used by staff/admin user
+ if ($this->isBackoffice) {
+ $this->addEntityRef("contact_id", ts('Select Contact'), ['create' => TRUE], TRUE);
+ }
+ // for front-end user show and use the basic three fields used to create a contact
+ else {
+ $this->add('text', 'email', ts('To Email'), ts($this->_contact_email), TRUE);
+ $this->add('text', 'last_name', ts('To Last Name'), ts($this->_to_contact_last_name), TRUE);
+ $this->add('text', 'first_name', ts('To First Name'), ts($this->_to_contact_first_name), TRUE);
+ }
+
+ $this->addButtons([
+ [
'type' => 'submit',
- 'name' => ts('Transfer Registration'),),
- )
- );
- $this->addFormRule(array('CRM_Event_Form_SelfSvcTransfer', 'formRule'), $this);
+ 'name' => ts('Transfer Registration'),
+ ],
+ ]);
+ $this->addFormRule(['CRM_Event_Form_SelfSvcTransfer', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -223,7 +239,7 @@ public function buildQuickForm() {
* return @array _defaults
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
return $this->_defaults;
}
@@ -233,11 +249,16 @@ public function setDefaultValues() {
* return array $errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
- //check that either an email or firstname+lastname is included in the form(CRM-9587)
- $to_contact_id = self::checkProfileComplete($fields, $errors, $self);
+ $errors = [];
+ if (!empty($fields['contact_id'])) {
+ $to_contact_id = $fields['contact_id'];
+ }
+ else {
+ //check that either an email or firstname+lastname is included in the form(CRM-9587)
+ $to_contact_id = self::checkProfileComplete($fields, $errors, $self);
+ }
//To check if the user is already registered for the event(CRM-2426)
- if ($to_contact_id) {
+ if (!empty($to_contact_id)) {
self::checkRegistration($fields, $self, $to_contact_id, $errors);
}
//return parent::formrule($fields, $files, $self);
@@ -258,7 +279,7 @@ public static function checkProfileComplete($fields, &$errors, $self) {
}
if (!$email && !(CRM_Utils_Array::value('first_name', $fields) &&
CRM_Utils_Array::value('last_name', $fields))) {
- $defaults = $params = array('id' => $eventId);
+ $defaults = $params = ['id' => $eventId];
CRM_Event_BAO_Event::retrieve($params, $defaults);
$message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
$errors['_qf_default'] = $message;
@@ -269,11 +290,12 @@ public static function checkProfileComplete($fields, &$errors, $self) {
$errors['email'] = ts('Enter valid email address.');
}
if (empty($errors) && empty($contact_id)) {
- $params = array(
+ $params = [
'email-Primary' => CRM_Utils_Array::value('email', $fields, NULL),
'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL),
'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL),
- 'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, FALSE),);
+ 'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, FALSE),
+ ];
//create new contact for this name/email pair
//if new contact, no need to check for contact already registered
$contact_id = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contact_id);
@@ -293,7 +315,7 @@ public static function checkRegistration($fields, $self, $contact_id, &$errors)
$query = "select event_id from civicrm_participant where contact_id = " . $contact_id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $to_event_id[] = $dao->event_id;
+ $to_event_id[] = $dao->event_id;
}
if (!empty($to_event_id)) {
foreach ($to_event_id as $id) {
@@ -311,16 +333,28 @@ public static function checkRegistration($fields, $self, $contact_id, &$errors)
public function postProcess() {
//For transfer, process form to allow selection of transferree
$params = $this->controller->exportValues($this->_name);
- //cancel 'from' participant row
- $query = "select contact_id from civicrm_email where email = '" . $params['email'] . "'";
- $dao = CRM_Core_DAO::executeQuery($query);
- while ($dao->fetch()) {
- $contact_id = $dao->contact_id;
+ if (!empty($params['contact_id'])) {
+ $contact_id = $params['contact_id'];
}
- $from_participant = $params = array();
+ else {
+ //cancel 'from' participant row
+ $contact_id_result = civicrm_api3('Contact', 'get', [
+ 'sequential' => 1,
+ 'return' => ["id"],
+ 'email' => $params['email'],
+ 'options' => ['limit' => 1],
+ ]);
+ $contact_id_result = $contact_id_result['values'][0];
+ $contact_id = $contact_id_result['contact_id'];
+ $contact_is_deleted = $contact_id_result['contact_is_deleted'];
+ if ($contact_is_deleted || !is_numeric($contact_id)) {
+ CRM_Core_Error::statusBounce(ts('Contact does not exist.'));
+ }
+ }
+ $from_participant = $params = [];
$query = "select role_id, source, fee_level, is_test, is_pay_later, fee_amount, discount_id, fee_currency,campaign_id, discount_amount from civicrm_participant where id = " . $this->_from_participant_id;
$dao = CRM_Core_DAO::executeQuery($query);
- $value_to = array();
+ $value_to = [];
while ($dao->fetch()) {
$value_to['role_id'] = $dao->role_id;
$value_to['source'] = $dao->source;
@@ -339,7 +373,7 @@ public function postProcess() {
$this->participantTransfer($participant);
//now update registered_by_id
$query = "UPDATE civicrm_participant cp SET cp.registered_by_id = %1 WHERE cp.id = ({$participant->id})";
- $params = array(1 => array($this->_from_participant_id, 'Integer'));
+ $params = [1 => [$this->_from_participant_id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
//copy line items to new participant
$line_items = CRM_Price_BAO_LineItem::getLineItems($this->_from_participant_id);
@@ -350,7 +384,7 @@ public function postProcess() {
$new_item = CRM_Price_BAO_LineItem::create($item);
}
//now cancel the from participant record, leaving the original line-item(s)
- $value_from = array();
+ $value_from = [];
$value_from['id'] = $this->_from_participant_id;
$tansferId = array_search('Transferred', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$value_from['status_id'] = $tansferId;
@@ -361,9 +395,12 @@ public function postProcess() {
CRM_Event_BAO_Participant::create($value_from);
$this->sendCancellation();
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contact_id);
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $displayName));
- $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $email));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $displayName]);
+ $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', [1 => $email]);
CRM_Core_Session::setStatus($statusMsg, ts('Registration Transferred'), 'success');
+ if ($this->isBackoffice) {
+ return;
+ }
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
CRM_Utils_System::redirect($url);
}
@@ -374,19 +411,19 @@ public function postProcess() {
* return @ void
*/
public function participantTransfer($participant) {
- $contactDetails = array();
+ $contactDetails = [];
$contactIds[] = $participant->contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
- FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
+ FALSE, FALSE, NULL, [], 'CRM_Event_BAO_Participant');
foreach ($currentContactDetails as $contactId => $contactValues) {
$contactDetails[$contactId] = $contactValues;
}
$participantRoles = CRM_Event_PseudoConstant::participantRole();
- $participantDetails = array();
+ $participantDetails = [];
$query = "SELECT * FROM civicrm_participant WHERE id = " . $participant->id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -396,35 +433,35 @@ public function participantTransfer($participant) {
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
}
- $domainValues = array();
+ $domainValues = [];
if (empty($domainValues)) {
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
+ $tokens = [
'domain' =>
- array(
+ [
'name',
'phone',
'address',
'email',
- ),
+ ],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
}
- $eventDetails = array();
- $eventParams = array('id' => $participant->event_id);
+ $eventDetails = [];
+ $eventParams = ['id' => $participant->event_id];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails);
//get default participant role.
$eventDetails['participant_role'] = CRM_Utils_Array::value($eventDetails['default_role_id'], $participantRoles);
//get the location info
- $locParams = array(
+ $locParams = [
'entity_id' => $participant->event_id,
'entity_table' => 'civicrm_event',
- );
+ ];
$eventDetails['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
$toEmail = CRM_Utils_Array::value('email', $contactDetails[$participant->contact_id]);
if ($toEmail) {
@@ -434,14 +471,14 @@ public function participantTransfer($participant) {
$receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
}
$participantName = $contactDetails[$participant->contact_id]['display_name'];
- $tplParams = array(
+ $tplParams = [
'event' => $eventDetails,
'participant' => $participantDetails[$participant->id],
'participantID' => $participant->id,
'participant_status' => 'Registered',
- );
+ ];
- $sendTemplateParams = array(
+ $sendTemplateParams = [
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_online_receipt',
'contactId' => $participantDetails[$participant->id]['contact_id'],
@@ -451,7 +488,7 @@ public function participantTransfer($participant) {
'toEmail' => $toEmail,
'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
- );
+ ];
CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
@@ -462,28 +499,28 @@ public function participantTransfer($participant) {
* return @ void
*/
public function sendCancellation() {
- $domainValues = array();
+ $domainValues = [];
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
+ $tokens = [
'domain' =>
- array(
+ [
'name',
'phone',
'address',
'email',
- ),
+ ],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
- $participantRoles = array();
+ $participantRoles = [];
$participantRoles = CRM_Event_PseudoConstant::participantRole();
- $participantDetails = array();
+ $participantDetails = [];
$query = "SELECT * FROM civicrm_participant WHERE id = {$this->_from_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -493,20 +530,20 @@ public function sendCancellation() {
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
}
- $eventDetails = array();
- $eventParams = array('id' => $this->_event_id);
+ $eventDetails = [];
+ $eventParams = ['id' => $this->_event_id];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
//get default participant role.
$eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
//get the location info
- $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
+ $locParams = ['entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'];
$eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
//get contact details
$contactIds[$this->_from_contact_id] = $this->_from_contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
- FALSE, FALSE, NULL, array(),
+ FALSE, FALSE, NULL, [],
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
@@ -521,8 +558,8 @@ public function sendCancellation() {
"Transferred",
""
);
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
- $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contact_name]);
+ $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', [1 => $this->_contact_email]);
CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
}
diff --git a/CRM/Event/Form/SelfSvcUpdate.php b/CRM/Event/Form/SelfSvcUpdate.php
index 693c53f19908..de7e8090fc23 100644
--- a/CRM/Event/Form/SelfSvcUpdate.php
+++ b/CRM/Event/Form/SelfSvcUpdate.php
@@ -1,9 +1,9 @@
_userContext = $session->readUserContext();
- $participant = $values = array();
+ $participant = $values = [];
$this->_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
- $params = array('id' => $this->_participant_id);
+ $this->isBackoffice = CRM_Utils_Request::retrieve('is_backoffice', 'String', $this, FALSE, NULL, 'REQUEST');
+ $params = ['id' => $this->_participant_id];
$this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
$this->_part_values = $values[$this->_participant_id];
$this->set('values', $this->_part_values);
@@ -135,7 +143,7 @@ public function preProcess() {
if ($this->_participant_id) {
$this->assign('participantId', $this->_participant_id);
}
- $event = array();
+ $event = [];
$daoName = 'title';
$this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
$daoName = 'start_date';
@@ -143,7 +151,7 @@ public function preProcess() {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contact_id);
$this->_contact_name = $displayName;
$this->_contact_email = $email;
- $details = array();
+ $details = [];
$details = CRM_Event_BAO_Participant::participantDetails($this->_participant_id);
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
$contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_participant_id, 'contribution_id', 'participant_id');
@@ -159,7 +167,7 @@ public function preProcess() {
while ($dao->fetch()) {
$details['status'] = $dao->status;
$details['role'] = $dao->role;
- $details['fee_level'] = $dao->fee_level;
+ $details['fee_level'] = trim($dao->fee_level, CRM_Core_DAO::VALUE_SEPARATOR);
$details['fee_amount'] = $dao->fee_amount;
$details['register_date'] = $dao->register_date;
$details['event_start_date'] = $dao->start_date;
@@ -178,16 +186,16 @@ public function preProcess() {
}
$start_time = new Datetime($start_date);
$timenow = new Datetime();
- if (!empty($start_time) && $start_time < $timenow) {
+ if (!$this->isBackoffice && !empty($start_time) && $start_time < $timenow) {
$status = ts("Registration for this event cannot be cancelled or transferred once the event has begun. Contact the event organizer if you have questions.");
CRM_Core_Error::statusBounce($status, $url, ts('Sorry'));
}
- if (!empty($time_limit) && $time_limit > 0) {
+ if (!$this->isBackoffice && !empty($time_limit) && $time_limit > 0) {
$interval = $timenow->diff($start_time);
$days = $interval->format('%d');
$hours = $interval->format('%h');
if ($hours <= $time_limit && $days < 1) {
- $status = ts("Registration for this event cannot be cancelled or transferred less than %1 hours prior to the event's start time. Contact the event organizer if you have questions.", array(1 => $time_limit));
+ $status = ts("Registration for this event cannot be cancelled or transferred less than %1 hours prior to the event's start time. Contact the event organizer if you have questions.", [1 => $time_limit]);
CRM_Core_Error::statusBounce($status, $url, ts('Sorry'));
}
}
@@ -199,6 +207,7 @@ public function preProcess() {
// for self update (event.start_date > today, event can be 'self_updated'
// retrieve contact name and email, and let user verify his/her identity
}
+
/**
* buildQuickForm -populate input variables for source Event
* to cancel or transfer to another person
@@ -206,14 +215,14 @@ public function preProcess() {
* return @void
*/
public function buildQuickForm() {
- $this->add('select', 'action', ts('Transfer or Cancel Registration'), array(ts('-select-'), ts('Transfer'), ts('Cancel')), TRUE);
- $this->addButtons(array(
- array(
+ $this->add('select', 'action', ts('Transfer or Cancel Registration'), [ts('-select-'), ts('Transfer'), ts('Cancel')], TRUE);
+ $this->addButtons([
+ [
'type' => 'submit',
'name' => ts('Submit'),
- ),
- ));
- $this->addFormRule(array('CRM_Event_Form_SelfSvcUpdate', 'formRule'), $this);
+ ],
+ ]);
+ $this->addFormRule(['CRM_Event_Form_SelfSvcUpdate', 'formRule'], $this);
parent::buildQuickForm();
}
@@ -223,7 +232,7 @@ public function buildQuickForm() {
* return @void
*/
public function setDefaultValues() {
- $this->_defaults = array();
+ $this->_defaults = [];
$this->_defaults['details'] = $this->_details;
return $this->_defaults;
}
@@ -239,7 +248,7 @@ public function setDefaultValues() {
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if (empty($fields['action'])) {
$errors['action'] = ts("Please select Transfer OR Cancel action.");
}
@@ -274,11 +283,16 @@ public function postProcess() {
* return @void
*/
public function transferParticipant($params) {
- $transferUrl = 'civicrm/event/form/selfsvctransfer';
- $url = CRM_Utils_System::url('civicrm/event/selfsvctransfer', 'reset=1&action=add&pid=' . $this->_participant_id . '&cs=' . $this->_userChecksum);
- $this->controller->setDestination($url);
- $session = CRM_Core_Session::singleton();
- $session->replaceUserContext($url);
+ $isBackOfficeArg = $this->isBackoffice ? '&is_backoffice=1' : '';
+ CRM_Utils_System::redirect(CRM_Utils_System::url(
+ 'civicrm/event/selfsvctransfer',
+ [
+ 'reset' => 1,
+ 'action' => 'add',
+ 'pid' => $this->_participant_id,
+ 'cs' => $this->_userChecksum,
+ ]
+ ));
}
/**
@@ -290,34 +304,34 @@ public function transferParticipant($params) {
public function cancelParticipant($params) {
//set participant record status to Cancelled, refund payment if possible
// send email to participant and admin, and log Activity
- $value = array();
+ $value = [];
$value['id'] = $this->_participant_id;
$cancelledId = array_search('Cancelled',
CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$value['status_id'] = $cancelledId;
CRM_Event_BAO_Participant::create($value);
- $domainValues = array();
+ $domainValues = [];
$domain = CRM_Core_BAO_Domain::getDomain();
- $tokens = array(
+ $tokens = [
'domain' =>
- array(
+ [
'name',
'phone',
'address',
'email',
- ),
+ ],
'contact' => CRM_Core_SelectValues::contactTokens(),
- );
+ ];
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
- $participantRoles = array();
+ $participantRoles = [];
$participantRoles = CRM_Event_PseudoConstant::participantRole();
- $participantDetails = array();
+ $participantDetails = [];
$query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $participantDetails[$dao->id] = array(
+ $participantDetails[$dao->id] = [
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
@@ -327,20 +341,20 @@ public function cancelParticipant($params) {
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
- );
+ ];
}
- $eventDetails = array();
- $eventParams = array('id' => $this->_event_id);
+ $eventDetails = [];
+ $eventParams = ['id' => $this->_event_id];
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
//get default participant role.
$eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
//get the location info
- $locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
+ $locParams = ['entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event'];
$eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
//get contact details
$contactIds[$this->_contact_id] = $this->_contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
- FALSE, FALSE, NULL, array(),
+ FALSE, FALSE, NULL, [],
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
@@ -355,9 +369,12 @@ public function cancelParticipant($params) {
"Cancelled",
""
);
- $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
- $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
+ $statusMsg = ts('Event registration information for %1 has been updated.', [1 => $this->_contact_name]);
+ $statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', [1 => $this->_contact_email]);
CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
+ if (!empty($this->isBackoffice)) {
+ return;
+ }
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
CRM_Utils_System::redirect($url);
}
diff --git a/CRM/Event/Form/Task.php b/CRM/Event/Form/Task.php
index 231089cfc531..87e0a07a0c29 100644
--- a/CRM/Event/Form/Task.php
+++ b/CRM/Event/Form/Task.php
@@ -1,9 +1,9 @@
_participantIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_participantIds = [];
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
- $eventTasks = CRM_Event_Task::tasks();
- $form->assign('taskName', $eventTasks[$form->_task]);
+ $tasks = CRM_Event_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission());
+ if (!array_key_exists($form->_task, $tasks)) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
+ }
+ $form->assign('taskName', $tasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -127,7 +108,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
//set the context for redirection for any task actions
$session = CRM_Core_Session::singleton();
- $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
+ $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
@@ -149,7 +130,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_participantIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_participantIds,
'civicrm_participant'
);
}
@@ -167,18 +148,17 @@ public function setContactIDs() {
* @return void
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Event/Form/Task/AddToGroup.php b/CRM/Event/Form/Task/AddToGroup.php
index 10b3034a722a..42c63d4aa017 100644
--- a/CRM/Event/Form/Task/AddToGroup.php
+++ b/CRM/Event/Form/Task/AddToGroup.php
@@ -1,9 +1,9 @@
_id) {
- $this->addRadio('group_option', ts('Group Options'), $options, array('onclick' => "return showElements();"));
+ $this->addRadio('group_option', ts('Group Options'), $options, ['onclick' => "return showElements();"]);
$this->add('text', 'title', ts('Group Name:') . ' ',
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title')
);
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_Group', $this->_id, 'title')
+ 'objectExists', ['CRM_Contact_DAO_Group', $this->_id, 'title']
);
$this->add('textarea', 'description', ts('Description:') . ' ',
@@ -122,7 +122,7 @@ public function buildQuickForm() {
}
// add select for groups
- $group = array('' => ts('- select group -')) + CRM_Core_PseudoConstant::group();
+ $group = ['' => ts('- select group -')] + CRM_Core_PseudoConstant::group();
$groupElement = $this->add('select', 'group_id', ts('Select Group'), $group);
@@ -132,13 +132,13 @@ public function buildQuickForm() {
$groupElement->freeze();
// also set the group title
- $groupValues = array('id' => $this->_id, 'title' => $this->_title);
+ $groupValues = ['id' => $this->_id, 'title' => $this->_title];
$this->assign_by_ref('group', $groupValues);
}
// Set dynamic page title for 'Add Members Group (confirm)'
if ($this->_id) {
- CRM_Utils_System::setTitle(ts('Add Contacts: %1', array(1 => $this->_title)));
+ CRM_Utils_System::setTitle(ts('Add Contacts: %1', [1 => $this->_title]));
}
else {
CRM_Utils_System::setTitle(ts('Add Contacts to A Group'));
@@ -155,7 +155,7 @@ public function buildQuickForm() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if ($this->_context === 'amtg') {
$defaults['group_id'] = $this->_id;
@@ -172,7 +172,7 @@ public function setDefaultValues() {
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_Task_AddToGroup', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_Task_AddToGroup', 'formRule']);
}
/**
@@ -185,7 +185,7 @@ public function addRules() {
* list of errors to be posted back to the form
*/
public static function formRule($params) {
- $errors = array();
+ $errors = [];
if (!empty($params['group_option']) && empty($params['title'])) {
$errors['title'] = "Group Name is a required field";
@@ -207,7 +207,7 @@ public function postProcess() {
$params = $this->controller->exportValues();
$groupOption = CRM_Utils_Array::value('group_option', $params, NULL);
if ($groupOption) {
- $groupParams = array();
+ $groupParams = [];
$groupParams['title'] = $params['title'];
$groupParams['description'] = $params['description'];
$groupParams['visibility'] = "User and User Admin Only";
@@ -233,24 +233,24 @@ public function postProcess() {
list($total, $added, $notAdded) = CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $groupID);
- $status = array(
- ts('%count contact added to group', array(
- 'count' => $added,
- 'plural' => '%count contacts added to group',
- )),
- );
+ $status = [
+ ts('%count contact added to group', [
+ 'count' => $added,
+ 'plural' => '%count contacts added to group',
+ ]),
+ ];
if ($notAdded) {
- $status[] = ts('%count contact was already in group', array(
- 'count' => $notAdded,
- 'plural' => '%count contacts were already in group',
- ));
+ $status[] = ts('%count contact was already in group', [
+ 'count' => $notAdded,
+ 'plural' => '%count contacts were already in group',
+ ]);
}
$status = '
' . implode('
', $status) . '
';
- CRM_Core_Session::setStatus($status, ts('Added Contact to %1', array(
- 1 => $groupName,
- 'count' => $added,
- 'plural' => 'Added Contacts to %1',
- )), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($status, ts('Added Contact to %1', [
+ 1 => $groupName,
+ 'count' => $added,
+ 'plural' => 'Added Contacts to %1',
+ ]), 'success', ['expires' => 0]);
}
}
diff --git a/CRM/Event/Form/Task/Badge.php b/CRM/Event/Form/Task/Badge.php
index 49c19de16e2f..3f7d87586d5e 100644
--- a/CRM/Event/Form/Task/Badge.php
+++ b/CRM/Event/Form/Task/Badge.php
@@ -1,9 +1,9 @@
_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
if ($this->_context == 'view') {
$this->_single = TRUE;
$participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
- $this->_participantIds = array($participantID);
+ $this->_participantIds = [$participantID];
$this->_componentClause = " civicrm_participant.id = $participantID ";
$this->assign('totalSelectedParticipants', 1);
@@ -93,9 +94,9 @@ public function buildQuickForm() {
$this->add('select',
'badge_id',
ts('Name Badge Format'),
- array(
+ [
'' => ts('- select -'),
- ) + $label, TRUE
+ ] + $label, TRUE
);
$next = 'next';
diff --git a/CRM/Event/Form/Task/Batch.php b/CRM/Event/Form/Task/Batch.php
index dfde70585969..e57358f3319c 100644
--- a/CRM/Event/Form/Task/Batch.php
+++ b/CRM/Event/Form/Task/Batch.php
@@ -1,9 +1,9 @@
ts('Name')),
+ $readOnlyFields = array_merge(['sort_name' => ts('Name')],
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
@@ -102,7 +103,7 @@ public function buildQuickForm() {
$this->_title = ts('Update multiple participants') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
- $this->_fields = array();
+ $this->_fields = [];
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
if (array_key_exists('participant_status', $this->_fields)) {
$this->assign('statusProfile', 1);
@@ -111,7 +112,7 @@ public function buildQuickForm() {
// remove file type field and then limit fields
$suppressFields = FALSE;
- $removehtmlTypes = array('File', 'Autocomplete-Select');
+ $removehtmlTypes = ['File'];
foreach ($this->_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -129,18 +130,17 @@ public function buildQuickForm() {
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Update Participant(s)'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Update Participant(s)'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_participantIds);
@@ -148,7 +148,7 @@ public function buildQuickForm() {
//load all campaigns.
if (array_key_exists('participant_campaign_id', $this->_fields)) {
- $this->_componentCampaigns = array();
+ $this->_componentCampaigns = [];
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Event_DAO_Participant',
TRUE, 'campaign_id', 'id',
@@ -182,7 +182,7 @@ public function buildQuickForm() {
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $this->_customFields);
- $entityColumnValue = array();
+ $entityColumnValue = [];
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
@@ -225,7 +225,7 @@ public function buildQuickForm() {
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_Batch_next') {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
}
$this->addDefaultButtons(ts('Update Participant(s)'));
@@ -242,9 +242,9 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_participantIds as $participantId) {
- $details[$participantId] = array();
+ $details[$participantId] = [];
$details[$participantId] = CRM_Event_BAO_Participant::participantDetails($participantId);
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $participantId, 'Event');
@@ -273,70 +273,14 @@ public function setDefaultValues() {
*/
public function postProcess() {
$params = $this->exportValues();
- $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
- if (isset($params['field'])) {
- foreach ($params['field'] as $key => $value) {
-
- //check for custom data
- $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
- $key,
- 'Participant'
- );
-
- $value['id'] = $key;
-
- if (!empty($value['participant_role'])) {
- if (is_array($value['participant_role'])) {
- $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
- }
- else {
- $value['role_id'] = $value['participant_role'];
- }
- }
-
- //need to send mail when status change
- $statusChange = FALSE;
- $relatedStatusChange = FALSE;
- if (!empty($value['participant_status'])) {
- $value['status_id'] = $value['participant_status'];
- $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
- if (!$fromStatusId) {
- $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
- }
-
- if ($fromStatusId != $value['status_id']) {
- $relatedStatusChange = TRUE;
- }
- if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
- $statusChange = TRUE;
- }
- }
-
- unset($value['participant_status']);
-
- civicrm_api3('Participant', 'create', $value);
-
- //need to trigger mails when we change status
- if ($statusChange) {
- CRM_Event_BAO_Participant::transitionParticipants(array($key), $value['status_id'], $fromStatusId);
- }
- if ($relatedStatusChange) {
- //update related contribution status, CRM-4395
- self::updatePendingOnlineContribution($key, $value['status_id']);
- }
- }
- CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
- }
- else {
- CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
- }
+ $this->submit($params);
}
/**
* @param int $participantId
* @param int $statusId
*
- * @return Ambigous|void
+ * @return mixed
*/
public static function updatePendingOnlineContribution($participantId, $statusId) {
if (!$participantId || !$statusId) {
@@ -370,13 +314,13 @@ public static function updatePendingOnlineContribution($participantId, $statusId
return;
}
- $params = array(
+ $params = [
'component_id' => $participantId,
'componentName' => 'Event',
'contribution_id' => $contributionId,
'contribution_status_id' => $contributionStatusId,
'IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved' => 1,
- );
+ ];
//change related contribution status.
$updatedStatusId = self::updateContributionStatus($params);
@@ -406,7 +350,7 @@ public static function updateContributionStatus($params) {
return NULL;
}
- $input = $ids = $objects = array();
+ $input = $ids = $objects = [];
//get the required ids.
$ids['contribution'] = $contributionId;
@@ -451,10 +395,10 @@ public static function updateContributionStatus($params) {
$contribution = &$objects['contribution'];
- $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
+ $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
'labelColumn' => 'name',
'flip' => 1,
- ));
+ ]);
$input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] = CRM_Utils_Array::value('IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved', $params);
if ($statusId == $contributionStatuses['Cancelled']) {
$baseIPN->cancelled($objects, $transaction, $input);
@@ -474,11 +418,11 @@ public static function updateContributionStatus($params) {
}
//set values for ipn code.
- foreach (array(
- 'fee_amount',
- 'check_number',
- 'payment_instrument_id',
- ) as $field) {
+ foreach ([
+ 'fee_amount',
+ 'check_number',
+ 'payment_instrument_id',
+ ] as $field) {
if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
$input[$field] = $contribution->$field;
}
@@ -510,7 +454,7 @@ public static function updateContributionStatus($params) {
* Assign the minimal set of variables to the template.
*/
public function assignToTemplate() {
- $notifyingStatuses = array('Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled');
+ $notifyingStatuses = ['Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled'];
$notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
$this->assign('status', TRUE);
if (!empty($notifyingStatuses)) {
@@ -519,4 +463,77 @@ public function assignToTemplate() {
}
}
+ /**
+ * @param $params
+ */
+ public function submit($params) {
+ $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
+ if (isset($params['field'])) {
+ foreach ($params['field'] as $key => $value) {
+
+ //check for custom data
+ $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
+ $key,
+ 'Participant'
+ );
+ foreach (array_keys($value) as $fieldName) {
+ // Unset the original custom field now that it has been formatting to the 'custom'
+ // array as it may not be in the right format for the api as is (notably for
+ // multiple checkbox values).
+ // @todo extract submit functions on other Batch update classes &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test them.
+ if (substr($fieldName, 0, 7) === 'custom_') {
+ unset($value[$fieldName]);
+ }
+ }
+
+ $value['id'] = $key;
+
+ if (!empty($value['participant_role'])) {
+ if (is_array($value['participant_role'])) {
+ $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
+ }
+ else {
+ $value['role_id'] = $value['participant_role'];
+ }
+ }
+
+ //need to send mail when status change
+ $statusChange = FALSE;
+ $relatedStatusChange = FALSE;
+ if (!empty($value['participant_status'])) {
+ $value['status_id'] = $value['participant_status'];
+ $fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
+ if (!$fromStatusId) {
+ $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
+ }
+
+ if ($fromStatusId != $value['status_id']) {
+ $relatedStatusChange = TRUE;
+ }
+ if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
+ $statusChange = TRUE;
+ }
+ }
+
+ unset($value['participant_status']);
+
+ civicrm_api3('Participant', 'create', $value);
+
+ //need to trigger mails when we change status
+ if ($statusChange) {
+ CRM_Event_BAO_Participant::transitionParticipants([$key], $value['status_id'], $fromStatusId);
+ }
+ if ($relatedStatusChange) {
+ //update related contribution status, CRM-4395
+ self::updatePendingOnlineContribution($key, $value['status_id']);
+ }
+ }
+ CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
+ }
+ else {
+ CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
+ }
+ }
+
}
diff --git a/CRM/Event/Form/Task/Cancel.php b/CRM/Event/Form/Task/Cancel.php
index bc3956a34a99..2fc163490da3 100644
--- a/CRM/Event/Form/Task/Cancel.php
+++ b/CRM/Event/Form/Task/Cancel.php
@@ -1,9 +1,9 @@
addDefaultButtons(ts('Continue'), 'done');
+ $this->addDefaultButtons(ts('Cancel Registrations'), 'done');
}
/**
@@ -76,7 +77,7 @@ public function buildQuickForm() {
*/
public function postProcess() {
$params = $this->exportValues();
- $value = array();
+ $value = [];
foreach ($this->_participantIds as $participantId) {
$value['id'] = $participantId;
diff --git a/CRM/Event/Form/Task/Delete.php b/CRM/Event/Form/Task/Delete.php
index 275f77032de3..ad9acdbddb70 100644
--- a/CRM/Event/Form/Task/Delete.php
+++ b/CRM/Event/Form/Task/Delete.php
@@ -1,9 +1,9 @@
ts('Delete this participant record along with associated participant record(s).'),
2 => ts('Delete only this participant record.'),
- );
+ ];
$this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, ' ');
- $this->setDefaults(array('delete_participant' => 1));
+ $this->setDefaults(['delete_participant' => 1]);
$this->addDefaultButtons(ts('Delete Participations'), 'done');
}
@@ -96,7 +96,7 @@ public function postProcess() {
$participantLinks = NULL;
if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
- $links = array();
+ $links = [];
foreach ($this->_participantIds as $participantId) {
$additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId));
$participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
@@ -131,7 +131,7 @@ public function postProcess() {
$deletedParticipants += $additionalCount;
}
- $status = ts('%count participant deleted.', array('plural' => '%count participants deleted.', 'count' => $deletedParticipants));
+ $status = ts('%count participant deleted.', ['plural' => '%count participants deleted.', 'count' => $deletedParticipants]);
if ($participantLinks) {
$status .= '
' . ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:')
diff --git a/CRM/Event/Form/Task/Email.php b/CRM/Event/Form/Task/Email.php
index 712a88aa7680..a9f5ccb6c62e 100644
--- a/CRM/Event/Form/Task/Email.php
+++ b/CRM/Event/Form/Task/Email.php
@@ -1,9 +1,9 @@
add('select', 'status_change', ts('Change All Statuses'),
- array(
+ [
'' => ts('- select status -'),
- ) + $statuses
+ ] + $statuses
);
$this->assign('context', 'statusChange');
diff --git a/CRM/Event/Form/Task/PickProfile.php b/CRM/Event/Form/Task/PickProfile.php
index a9bef04f9cd0..8d916b2275a8 100644
--- a/CRM/Event/Form/Task/PickProfile.php
+++ b/CRM/Event/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
add('select', 'uf_group_id', ts('Select Profile'),
- array(
+ [
'' => ts('- select profile -'),
- ) + $profiles, TRUE
+ ] + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
@@ -112,7 +114,7 @@ public function buildQuickForm() {
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Event_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Event_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Event/Form/Task/Print.php b/CRM/Event/Form/Task/Print.php
index da18e47b9741..828e572ded71 100644
--- a/CRM/Event/Form/Task/Print.php
+++ b/CRM/Event/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Participant List'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Participant List'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Event/Form/Task/Result.php b/CRM/Event/Form/Task/Result.php
index 0c9c8734b1d5..f91778e69329 100644
--- a/CRM/Event/Form/Task/Result.php
+++ b/CRM/Event/Form/Task/Result.php
@@ -1,9 +1,9 @@
_id)) {
- $params = array('saved_search_id' => $this->_id);
+ $params = ['saved_search_id' => $this->_id];
CRM_Contact_BAO_Group::retrieve($params, $values);
$groupId = $values['id'];
@@ -101,7 +101,7 @@ public function buildQuickForm() {
}
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Contact_DAO_Group', $groupId, 'title')
+ 'objectExists', ['CRM_Contact_DAO_Group', $groupId, 'title']
);
}
@@ -123,10 +123,10 @@ public function postProcess() {
$savedSearch->form_values = serialize($this->get('formValues'));
$savedSearch->save();
$this->set('ssID', $savedSearch->id);
- CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", array(1 => $formValues['title'])), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", [1 => $formValues['title']]), ts('Saved'), 'success');
// also create a group that is associated with this saved search only if new saved search
- $params = array();
+ $params = [];
$params['title'] = $formValues['title'];
$params['description'] = $formValues['description'];
$params['visibility'] = 'User and User Admin Only';
diff --git a/CRM/Event/Form/Task/SaveSearch/Update.php b/CRM/Event/Form/Task/SaveSearch/Update.php
index 1687c84798b0..a57171606987 100644
--- a/CRM/Event/Form/Task/SaveSearch/Update.php
+++ b/CRM/Event/Form/Task/SaveSearch/Update.php
@@ -1,9 +1,9 @@
$this->_id);
+ $params = ['saved_search_id' => $this->_id];
CRM_Contact_BAO_Group::retrieve($params, $defaults);
return $defaults;
diff --git a/CRM/Event/Form/Task/SearchTaskHookSample.php b/CRM/Event/Form/Task/SearchTaskHookSample.php
index e18c84f08929..3e143e115471 100644
--- a/CRM/Event/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Event/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_participantIds);
@@ -61,12 +61,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'register_date' => CRM_Utils_Date::customFormat($dao->register_date),
'source' => $dao->source,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -77,14 +77,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Event/Import/Controller.php b/CRM/Event/Import/Controller.php
index 43b355623698..e916a4b0e214 100644
--- a/CRM/Event/Import/Controller.php
+++ b/CRM/Event/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Event/Import/Field.php b/CRM/Event/Import/Field.php
index a4ef9799669a..773a066c63b9 100644
--- a/CRM/Event/Import/Field.php
+++ b/CRM/Event/Import/Field.php
@@ -1,9 +1,9 @@
createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -64,7 +64,7 @@ public function buildQuickForm() {
ts('On Duplicate Entries')
);
- $this->setDefaults(array('onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP));
+ $this->setDefaults(['onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP]);
$this->addContactTypeSelector();
}
@@ -75,12 +75,12 @@ public function buildQuickForm() {
* @return void
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
- ));
+ ]);
$this->submitFileForMapping('CRM_Event_Import_Parser_Participant');
}
diff --git a/CRM/Event/Import/Form/MapField.php b/CRM/Event/Import/Form/MapField.php
index 2f6342027063..161ee1f843af 100644
--- a/CRM/Event/Import/Form/MapField.php
+++ b/CRM/Event/Import/Form/MapField.php
@@ -1,9 +1,9 @@
setDefaults($defaults);
$this->addButtons(array(
- array(
- 'type' => 'back',
- 'name' => ts('Previous'),
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ array(
+ 'type' => 'back',
+ 'name' => ts('Previous'),
+ ),
+ array(
+ 'type' => 'next',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ),
+ array(
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ),
+ ));
}
/**
@@ -343,8 +341,8 @@ public static function formRule($fields, $files, $self) {
}
else {
$errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
- 1 => $threshold,
- )) . ' ' . ts('Or Provide Contact ID or External ID.') . ' ';
+ 1 => $threshold,
+ )) . ' ' . ts('Or Provide Contact ID or External ID.') . ' ';
}
}
elseif (!in_array('event_title', $importKeys)) {
@@ -362,8 +360,7 @@ public static function formRule($fields, $files, $self) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Participant', 'name');
- if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
+ if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Participant'))) {
$errors['saveMappingName'] = ts('Duplicate Import Participant Mapping Name');
}
}
@@ -461,10 +458,7 @@ public function postProcess() {
$mappingParams = array(
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import Participant',
- 'name'
- ),
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Participant'),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
diff --git a/CRM/Event/Import/Form/Preview.php b/CRM/Event/Import/Form/Preview.php
index b42db7026fee..c2e32386fd06 100644
--- a/CRM/Event/Import/Form/Preview.php
+++ b/CRM/Event/Import/Form/Preview.php
@@ -1,9 +1,9 @@
set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'dataValues',
'columnCount',
@@ -98,7 +98,7 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -120,7 +120,7 @@ public function postProcess() {
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
+ $mapperKeys = [];
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
@@ -131,7 +131,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -152,7 +152,7 @@ public function postProcess() {
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Event/Import/Form/Summary.php b/CRM/Event/Import/Form/Summary.php
index 1a9abaef1ac6..df860af8a0b9 100644
--- a/CRM/Event/Import/Form/Summary.php
+++ b/CRM/Event/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -105,7 +105,7 @@ public function preProcess() {
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Event/Import/Parser.php b/CRM/Event/Import/Parser.php
index 12ecfcf360c9..ba14c1bc2d7f 100644
--- a/CRM/Event/Import/Parser.php
+++ b/CRM/Event/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
@@ -192,14 +196,12 @@ public function run(
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- if ($this->_haveColumnHeader) {
- $recordNumber--;
- }
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
+ $recordNumber = $this->_lineCount;
+ if ($this->_haveColumnHeader) {
+ $recordNumber--;
}
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode & self::CONFLICT) {
@@ -255,32 +257,26 @@ public function run(
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('Reason'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('Reason'),
+ ], $customHeaders);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
- ts('Line Number'),
- ts('View Participant URL'),
- ),
- $customHeaders
- );
+ $headers = array_merge([
+ ts('Line Number'),
+ ts('View Participant URL'),
+ ], $customHeaders);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
@@ -316,7 +312,7 @@ public function setActiveFields($fieldKeys) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -421,7 +417,7 @@ public function set($store, $mode = self::MODE_SUMMARY) {
* @return void
*/
public static function exportCSV($fileName, $header, $data) {
- $output = array();
+ $output = [];
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
diff --git a/CRM/Event/Import/Parser/Participant.php b/CRM/Event/Import/Parser/Participant.php
index 581ce7d95211..7c41ed110a5a 100644
--- a/CRM/Event/Import/Parser/Participant.php
+++ b/CRM/Event/Import/Parser/Participant.php
@@ -1,9 +1,9 @@
addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newParticipants = array();
+ $this->_newParticipants = [];
$this->setActiveFields($this->_mapperKeys);
// FIXME: we should do this in one place together with Form/MapField.php
@@ -284,8 +284,8 @@ public function import($onDuplicate, &$values) {
$params = &$this->getActiveFieldParams();
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
- $formatted = array('version' => 3);
- $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
+ $formatted = ['version' => 3];
+ $customFields = CRM_Core_BAO_CustomField::getFields('Participant');
// don't add to recent items, CRM-4399
$formatted['skipRecentView'] = TRUE;
@@ -314,7 +314,7 @@ public function import($onDuplicate, &$values) {
}
else {
$eventTitle = $params['event_title'];
- $qParams = array();
+ $qParams = [];
$dao = new CRM_Core_DAO();
$params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '$eventTitle' ",
$qParams
@@ -328,7 +328,7 @@ public function import($onDuplicate, &$values) {
$indieFields = CRM_Event_BAO_Participant::import();
}
- $formatValues = array();
+ $formatValues = [];
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
@@ -365,11 +365,11 @@ public function import($onDuplicate, &$values) {
'Participant'
);
if ($dao->find(TRUE)) {
- $ids = array(
+ $ids = [
'participant' => $formatValues['participant_id'],
'userId' => $session->get('userID'),
- );
- $participantValues = array();
+ ];
+ $participantValues = [];
//@todo calling api functions directly is not supported
$newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
if ($newParticipant['error_message']) {
@@ -378,10 +378,10 @@ public function import($onDuplicate, &$values) {
}
$newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
if (!empty($formatted['fee_level'])) {
- $otherParams = array(
+ $otherParams = [
'fee_label' => $formatted['fee_level'],
'event_id' => $newParticipant->event_id,
- );
+ ];
CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
}
@@ -410,10 +410,10 @@ public function import($onDuplicate, &$values) {
}
else {
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = '';
@@ -531,7 +531,7 @@ protected function formatValues(&$values, $params) {
if ($type == 'CheckBox' || $type == 'Multi-Select') {
$mulValues = explode(',', $value);
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
- $values[$key] = array();
+ $values[$key] = [];
foreach ($mulValues as $v1) {
foreach ($customOption as $customValueID => $customLabel) {
$customValue = $customLabel['value'];
@@ -590,7 +590,7 @@ protected function formatValues(&$values, $params) {
return civicrm_api3_create_error("Event ID is not valid: $value");
}
$dao = new CRM_Core_DAO();
- $qParams = array();
+ $qParams = [];
$svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
$qParams
);
@@ -640,7 +640,7 @@ protected function formatValues(&$values, $params) {
// status_id and source. So, if $values contains
// participant_register_date, participant_status_id or participant_source,
// convert it to register_date, status_id or source
- $changes = array(
+ $changes = [
'participant_register_date' => 'register_date',
'participant_source' => 'source',
'participant_status_id' => 'status_id',
@@ -648,7 +648,7 @@ protected function formatValues(&$values, $params) {
'participant_fee_level' => 'fee_level',
'participant_fee_amount' => 'fee_amount',
'participant_id' => 'id',
- );
+ ];
foreach ($changes as $orgVal => $changeVal) {
if (isset($values[$orgVal])) {
diff --git a/CRM/Event/Info.php b/CRM/Event/Info.php
index 1c574456b95d..8e3e5338cafa 100644
--- a/CRM/Event/Info.php
+++ b/CRM/Event/Info.php
@@ -1,9 +1,9 @@
'CiviEvent',
'translatedName' => ts('CiviEvent'),
'title' => ts('CiviCRM Event Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
/**
@@ -65,39 +66,39 @@ public function getInfo() {
* @return array
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviEvent' => array(
+ $permissions = [
+ 'access CiviEvent' => [
ts('access CiviEvent'),
ts('Create events, view all events, and view participant records (for visible contacts)'),
- ),
- 'edit event participants' => array(
+ ],
+ 'edit event participants' => [
ts('edit event participants'),
ts('Record and update backend event registrations'),
- ),
- 'edit all events' => array(
+ ],
+ 'edit all events' => [
ts('edit all events'),
ts('Edit events even without specific ACL granted'),
- ),
- 'register for events' => array(
+ ],
+ 'register for events' => [
ts('register for events'),
ts('Register for events online'),
- ),
- 'view event info' => array(
+ ],
+ 'view event info' => [
ts('view event info'),
ts('View online event information pages'),
- ),
- 'view event participants' => array(
+ ],
+ 'view event participants' => [
ts('view event participants'),
- ),
- 'delete in CiviEvent' => array(
+ ],
+ 'delete in CiviEvent' => [
ts('delete in CiviEvent'),
ts('Delete participants and events that you can edit'),
- ),
- 'manage event profiles' => array(
+ ],
+ 'manage event profiles' => [
ts('manage event profiles'),
ts('Allow users to create, edit and copy event-related profile forms used for online event registration.'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -112,9 +113,9 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* @return array
*/
public function getAnonymousPermissionWarnings() {
- return array(
+ return [
'access CiviEvent',
- );
+ ];
}
/**
@@ -122,12 +123,12 @@ public function getAnonymousPermissionWarnings() {
* @return array
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Events'),
'title' => ts('Your Event(s)'),
- 'perm' => array('register for events'),
+ 'perm' => ['register for events'],
'weight' => 20,
- );
+ ];
}
/**
@@ -135,12 +136,20 @@ public function getUserDashboardElement() {
* @return array
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Events'),
'id' => 'participant',
'url' => 'participant',
'weight' => 40,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-calendar';
}
/**
@@ -148,10 +157,10 @@ public function registerTab() {
* @return array
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Events'),
'weight' => 40,
- );
+ ];
}
/**
@@ -159,11 +168,11 @@ public function registerAdvancedSearchPane() {
* @return array
*/
public function getActivityTypes() {
- $types = array();
- $types['Event'] = array(
+ $types = [];
+ $types['Event'] = [
'title' => ts('Event'),
'callback' => 'CRM_Event_Page_EventInfo::run()',
- );
+ ];
return $types;
}
@@ -176,20 +185,20 @@ public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviEvent') &&
CRM_Core_Permission::check('edit event participants')
) {
- $shortCut[] = array(
+ $shortCut[] = [
'path' => 'civicrm/participant/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-participant',
'title' => ts('Event Registration'),
- );
+ ];
if ($newCredit) {
$title = ts('Event Registration') . ' (' . ts('credit card') . ')';
- $shortCut[0]['shortCuts'][] = array(
+ $shortCut[0]['shortCuts'][] = [
'path' => 'civicrm/participant/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-participant-cc',
'title' => $title,
- );
+ ];
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
diff --git a/CRM/Event/Page/AJAX.php b/CRM/Event/Page/AJAX.php
index 9f9af28663b5..7227988671db 100644
--- a/CRM/Event/Page/AJAX.php
+++ b/CRM/Event/Page/AJAX.php
@@ -1,9 +1,9 @@
fetch()) {
- $results[] = array('id' => $dao->id, 'text' => $dao->label);
+ $results[] = ['id' => $dao->id, 'text' => $dao->label];
}
CRM_Utils_JSON::output($results);
}
diff --git a/CRM/Event/Page/DashBoard.php b/CRM/Event/Page/DashBoard.php
index 745ac1e70cdb..b94825a8f12c 100644
--- a/CRM/Event/Page/DashBoard.php
+++ b/CRM/Event/Page/DashBoard.php
@@ -1,9 +1,9 @@
assign('context', $context);
// Sometimes we want to suppress the Event Full msg
@@ -71,7 +71,7 @@ public function run() {
);
//retrieve event information
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Event_BAO_Event::retrieve($params, $values['event']);
if (!$values['event']['is_active']) {
@@ -80,6 +80,10 @@ public function run() {
return CRM_Utils_System::permissionDenied();
}
+ if (!$values['event']['is_public']) {
+ CRM_Utils_System::addHTMLHead('');
+ }
+
if (!empty($values['event']['is_template'])) {
// form is an Event Template
CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
@@ -148,6 +152,12 @@ public function run() {
$displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
foreach ($fieldValues['options'] as $optionId => $optionVal) {
+ if (CRM_Utils_Array::value('visibility_id', $optionVal) != array_search('public', $visibility) &&
+ $adminFieldVisible == FALSE
+ ) {
+ continue;
+ }
+
$values['feeBlock']['isDisplayAmount'][$fieldCnt] = CRM_Utils_Array::value('is_display_amounts', $fieldValues);
if ($invoicing && isset($optionVal['tax_amount'])) {
$values['feeBlock']['value'][$fieldCnt] = CRM_Price_BAO_PriceField::getTaxLabel($optionVal, 'amount', $displayOpt, $taxTerm);
@@ -168,7 +178,7 @@ public function run() {
}
}
- $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
+ $params = ['entity_id' => $this->_id, 'entity_table' => 'civicrm_event'];
$values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
// fix phone type labels
@@ -213,14 +223,14 @@ public function run() {
}
}
- $center = array(
+ $center = [
'lat' => (float ) $sumLat / count($locations),
'lng' => (float ) $sumLng / count($locations),
- );
- $span = array(
+ ];
+ $span = [
'lat' => (float ) ($maxLat - $minLat),
'lng' => (float ) ($maxLng - $minLng),
- );
+ ];
$this->assign_by_ref('center', $center);
$this->assign_by_ref('span', $span);
if ($action == CRM_Core_Action::PREVIEW) {
@@ -266,8 +276,9 @@ public function run() {
);
$allowRegistration = FALSE;
+ $isEventOpenForRegistration = CRM_Event_BAO_Event::validRegistrationRequest($values['event'], $this->_id);
if (!empty($values['event']['is_online_registration'])) {
- if (CRM_Event_BAO_Event::validRegistrationRequest($values['event'], $this->_id)) {
+ if ($isEventOpenForRegistration == 1) {
// we always generate urls for the front end in joomla
$action_query = $action === CRM_Core_Action::PREVIEW ? "&action=$action" : '';
$url = CRM_Utils_System::url('civicrm/event/register',
@@ -306,11 +317,11 @@ public function run() {
$this->assign('allowRegistration', $allowRegistration);
$session = CRM_Core_Session::singleton();
- $params = array(
+ $params = [
'contact_id' => $session->get('userID'),
'event_id' => CRM_Utils_Array::value('id', $values['event']),
'role_id' => CRM_Utils_Array::value('default_role_id', $values['event']),
- );
+ ];
if ($eventFullMessage && ($noFullMsg == 'false') || CRM_Event_BAO_Event::checkRegistration($params)) {
$statusMessage = $eventFullMessage;
@@ -323,7 +334,7 @@ public function run() {
$registerUrl = CRM_Utils_System::url('civicrm/event/register',
"reset=1&id={$values['event']['id']}&cid=0"
);
- $statusMessage = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', array(1 => $registerUrl));
+ $statusMessage = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also register another participant.', [1 => $registerUrl]);
}
}
}
@@ -333,8 +344,9 @@ public function run() {
$statusMessage = ts('Event is currently full, but you can register and be a part of waiting list.');
}
}
-
- CRM_Core_Session::setStatus($statusMessage);
+ if ($isEventOpenForRegistration == 1) {
+ CRM_Core_Session::setStatus($statusMessage);
+ }
}
// we do not want to display recently viewed items, so turn off
$this->assign('displayRecent', FALSE);
diff --git a/CRM/Event/Page/ICalendar.php b/CRM/Event/Page/ICalendar.php
index 8cdc8d16dc72..4790280e7d8e 100644
--- a/CRM/Event/Page/ICalendar.php
+++ b/CRM/Event/Page/ICalendar.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Event'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Event'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=delete&id=%%id%%',
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
'title' => ts('Delete Event'),
- ),
- CRM_Core_Action::COPY => array(
+ ],
+ CRM_Core_Action::COPY => [
'name' => ts('Copy'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'reset=1&action=copy&id=%%id%%',
'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"',
'title' => ts('Copy Event'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
+ public function eventLinks() {
+ if (!(self::$_eventLinks)) {
+ self::$_eventLinks = [
+ 'register_participant' => [
+ 'name' => ts('Register Participant'),
+ 'title' => ts('Register Participant'),
+ 'url' => 'civicrm/participant/add',
+ 'qs' => 'reset=1&action=add&context=standalone&eid=%%id%%',
+ ],
+ 'event_info' => [
+ 'name' => ts('Event Info'),
+ 'title' => ts('Event Info'),
+ 'url' => 'civicrm/event/info',
+ 'qs' => 'reset=1&id=%%id%%',
+ 'fe' => TRUE,
+ ],
+ 'online_registration_test' => [
+ 'name' => ts('Registration (Test-drive)'),
+ 'title' => ts('Online Registration (Test-drive)'),
+ 'url' => 'civicrm/event/register',
+ 'qs' => 'reset=1&action=preview&id=%%id%%',
+ 'fe' => TRUE,
+ ],
+ 'online_registration_live' => [
+ 'name' => ts('Registration (Live)'),
+ 'title' => ts('Online Registration (Live)'),
+ 'url' => 'civicrm/event/register',
+ 'qs' => 'reset=1&id=%%id%%',
+ 'fe' => TRUE,
+ ],
+ ];
+ }
+ return self::$_eventLinks;
+ }
+
/**
* Get tab Links for events.
*
@@ -108,74 +149,74 @@ public function &links() {
public static function &tabs($enableCart) {
$cacheKey = $enableCart ? 1 : 0;
if (!(self::$_tabLinks)) {
- self::$_tabLinks = array();
+ self::$_tabLinks = [];
}
if (!isset(self::$_tabLinks[$cacheKey])) {
self::$_tabLinks[$cacheKey]['settings']
- = array(
+ = [
'title' => ts('Info and Settings'),
'url' => 'civicrm/event/manage/settings',
'field' => 'id',
- );
+ ];
self::$_tabLinks[$cacheKey]['location']
- = array(
+ = [
'title' => ts('Location'),
'url' => 'civicrm/event/manage/location',
'field' => 'loc_block_id',
- );
+ ];
self::$_tabLinks[$cacheKey]['fee']
- = array(
+ = [
'title' => ts('Fees'),
'url' => 'civicrm/event/manage/fee',
'field' => 'is_monetary',
- );
+ ];
self::$_tabLinks[$cacheKey]['registration']
- = array(
+ = [
'title' => ts('Online Registration'),
'url' => 'civicrm/event/manage/registration',
'field' => 'is_online_registration',
- );
+ ];
if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
self::$_tabLinks[$cacheKey]['reminder']
- = array(
+ = [
'title' => ts('Schedule Reminders'),
'url' => 'civicrm/event/manage/reminder',
'field' => 'reminder',
- );
+ ];
}
self::$_tabLinks[$cacheKey]['conference']
- = array(
+ = [
'title' => ts('Conference Slots'),
'url' => 'civicrm/event/manage/conference',
'field' => 'slot_label_id',
- );
+ ];
self::$_tabLinks[$cacheKey]['friend']
- = array(
+ = [
'title' => ts('Tell a Friend'),
'url' => 'civicrm/event/manage/friend',
'field' => 'friend',
- );
+ ];
self::$_tabLinks[$cacheKey]['pcp']
- = array(
+ = [
'title' => ts('Personal Campaign Pages'),
'url' => 'civicrm/event/manage/pcp',
'field' => 'is_pcp_enabled',
- );
+ ];
self::$_tabLinks[$cacheKey]['repeat']
- = array(
+ = [
'title' => ts('Repeat'),
'url' => 'civicrm/event/manage/repeat',
'field' => 'is_repeating_event',
- );
+ ];
}
if (!$enableCart) {
unset(self::$_tabLinks[$cacheKey]['conference']);
}
- CRM_Utils_Hook::tabset('civicrm/event/manage', self::$_tabLinks[$cacheKey], array());
+ CRM_Utils_Hook::tabset('civicrm/event/manage', self::$_tabLinks[$cacheKey], []);
return self::$_tabLinks[$cacheKey];
}
@@ -210,12 +251,12 @@ public function run() {
}
if (!$this->_isTemplate && $id) {
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Manage Events'),
'url' => CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -266,16 +307,19 @@ public function browse() {
$this->search();
- $params = array();
+ $params = [];
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean',
$this, FALSE
);
$this->_searchResult = CRM_Utils_Request::retrieve('searchResult', 'Boolean', $this);
$whereClause = $this->whereClause($params, FALSE, $this->_force);
- $this->pagerAToZ($whereClause, $params);
- $params = array();
+ if (CRM_Core_Config::singleton()->includeAlphabeticalPager) {
+ $this->pagerAToZ($whereClause, $params);
+ }
+
+ $params = [];
$whereClause = $this->whereClause($params, TRUE, $this->_force);
// because is_template != 1 would be to simple
$whereClause .= ' AND (is_template = 0 OR is_template IS NULL)';
@@ -285,7 +329,7 @@ public function browse() {
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
// get all custom groups sorted by weight
- $manageEvent = array();
+ $manageEvent = [];
$query = "
SELECT *
@@ -295,13 +339,13 @@ public function browse() {
LIMIT $offset, $rowCount";
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Event_DAO_Event');
- $permissions = CRM_Event_BAO_Event::checkPermission();
+ $permittedEventsByAction = CRM_Event_BAO_Event::getAllPermissions();
//get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
// get the list of active event pcps
- $eventPCPS = array();
+ $eventPCPS = [];
$pcpDao = new CRM_PCP_DAO_PCPBlock();
$pcpDao->entity_table = 'civicrm_event';
@@ -313,17 +357,17 @@ public function browse() {
// check if we're in shopping cart mode for events
$enableCart = Civi::settings()->get('enable_cart');
$this->assign('eventCartEnabled', $enableCart);
- $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
+ $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
- )));
+ ]));
$eventType = CRM_Core_OptionGroup::values('event_type');
while ($dao->fetch()) {
- if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
- $manageEvent[$dao->id] = array();
+ if (in_array($dao->id, $permittedEventsByAction[CRM_Core_Permission::VIEW])) {
+ $manageEvent[$dao->id] = [];
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($dao->id, 'civicrm_event');
$manageEvent[$dao->id]['repeat'] = '';
if ($repeat) {
- $manageEvent[$dao->id]['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
+ $manageEvent[$dao->id]['repeat'] = ts('Repeating (%1 of %2)', [1 => $repeat[0], 2 => $repeat[1]]);
}
CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
@@ -337,16 +381,30 @@ public function browse() {
$action -= CRM_Core_Action::DISABLE;
}
- if (!in_array($dao->id, $permissions[CRM_Core_Permission::DELETE])) {
+ if (!in_array($dao->id, $permittedEventsByAction[CRM_Core_Permission::DELETE])) {
$action -= CRM_Core_Action::DELETE;
}
- if (!in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
+ if (!in_array($dao->id, $permittedEventsByAction[CRM_Core_Permission::EDIT])) {
$action -= CRM_Core_Action::UPDATE;
}
+ $eventLinks = self::eventLinks();
+ if (!CRM_Core_Permission::check('edit event participants')) {
+ unset($eventLinks['register_participant']);
+ }
+
+ $manageEvent[$dao->id]['eventlinks'] = CRM_Core_Action::formLink($eventLinks,
+ NULL,
+ ['id' => $dao->id],
+ ts('Event Links'),
+ TRUE,
+ 'event.manage.eventlinks',
+ 'Event',
+ $dao->id
+ );
$manageEvent[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(),
$action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
TRUE,
'event.manage.list',
@@ -354,11 +412,11 @@ public function browse() {
$dao->id
);
- $params = array(
+ $params = [
'entity_id' => $dao->id,
'entity_table' => 'civicrm_event',
'is_active' => 1,
- );
+ ];
$defaults['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
@@ -378,7 +436,7 @@ public function browse() {
$manageEvent[$dao->id]['event_type'] = CRM_Utils_Array::value($manageEvent[$dao->id]['event_type_id'], $eventType);
$manageEvent[$dao->id]['is_repeating_event'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_RecurringEntity', $dao->id, 'parent_id', 'entity_id');
// allow hooks to set 'field' value which allows configuration pop-up to show a tab as enabled/disabled
- CRM_Utils_Hook::tabset('civicrm/event/manage/rows', $manageEvent, array('event_id' => $dao->id));
+ CRM_Utils_Hook::tabset('civicrm/event/manage/rows', $manageEvent, ['event_id' => $dao->id]);
}
}
@@ -397,6 +455,7 @@ public function browse() {
* all the fields in the event wizard
*
* @return void
+ * @throws \CRM_Core_Exception
*/
public function copy() {
$id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE, 0, 'GET');
@@ -437,8 +496,8 @@ public function search() {
* @return string
*/
public function whereClause(&$params, $sortBy = TRUE, $force) {
- $values = array();
- $clauses = array();
+ $values = [];
+ $clauses = [];
$title = $this->get('title');
$createdId = $this->get('cid');
@@ -449,10 +508,10 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
if ($title) {
$clauses[] = "title LIKE %1";
if (strpos($title, '%') !== FALSE) {
- $params[1] = array(trim($title), 'String', FALSE);
+ $params[1] = [trim($title), 'String', FALSE];
}
else {
- $params[1] = array(trim($title), 'String', TRUE);
+ $params[1] = [trim($title), 'String', TRUE];
}
}
@@ -471,13 +530,13 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
$from = $this->get('start_date');
if (!CRM_Utils_System::isNull($from)) {
$clauses[] = '( end_date >= %3 OR end_date IS NULL )';
- $params[3] = array($from, 'String');
+ $params[3] = [$from, 'String'];
}
$to = $this->get('end_date');
if (!CRM_Utils_System::isNull($to)) {
$clauses[] = '( start_date <= %4 OR start_date IS NULL )';
- $params[4] = array($to, 'String');
+ $params[4] = [$to, 'String'];
}
}
else {
@@ -499,7 +558,7 @@ public function whereClause(&$params, $sortBy = TRUE, $force) {
$campaignIds = $this->get('campaign_id');
if (!CRM_Utils_System::isNull($campaignIds)) {
if (!is_array($campaignIds)) {
- $campaignIds = array($campaignIds);
+ $campaignIds = [$campaignIds];
}
$clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campaignIds)) . ' ) )';
}
diff --git a/CRM/Event/Page/ParticipantListing.php b/CRM/Event/Page/ParticipantListing.php
index abaf12c7c625..e58790c2a115 100644
--- a/CRM/Event/Page/ParticipantListing.php
+++ b/CRM/Event/Page/ParticipantListing.php
@@ -1,9 +1,9 @@
preProcess();
// get the class name from the participantListingID
- $className = CRM_Core_OptionGroup::getValue('participant_listing',
- $this->_participantListingID,
- 'value',
- 'Integer',
- 'description'
+ $className = CRM_Utils_Array::value($this->_participantListingID,
+ CRM_Core_PseudoConstant::get(
+ 'CRM_Event_BAO_Event',
+ 'participant_listing_id',
+ ['keyColumn' => 'value', 'labelColumn' => 'description']
+ )
);
-
if ($className == 'CRM_Event_Page_ParticipantListing') {
CRM_Core_Error::fatal(ts("Participant listing code file cannot be '%1'",
array(1 => $className)
diff --git a/CRM/Event/Page/ParticipantListing/Name.php b/CRM/Event/Page/ParticipantListing/Name.php
index c32386279375..d21bcddaef25 100644
--- a/CRM/Event/Page/ParticipantListing/Name.php
+++ b/CRM/Event/Page/ParticipantListing/Name.php
@@ -1,9 +1,9 @@
_participantListingType = 'Name';
diff --git a/CRM/Event/Page/ParticipantListing/NameAndEmail.php b/CRM/Event/Page/ParticipantListing/NameAndEmail.php
index 4fd01ed5c803..0b4c586936bc 100644
--- a/CRM/Event/Page/ParticipantListing/NameAndEmail.php
+++ b/CRM/Event/Page/ParticipantListing/NameAndEmail.php
@@ -1,9 +1,9 @@
_participantListingType = 'Name and Email';
diff --git a/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php b/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php
index 585814f2c80f..c2bf4eb3e229 100644
--- a/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php
+++ b/CRM/Event/Page/ParticipantListing/NameStatusAndDate.php
@@ -1,9 +1,9 @@
_id,
'title'
);
- CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Participants', [1 => $this->_eventTitle]));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
@@ -80,7 +80,7 @@ public function run() {
$whereClause = "
WHERE civicrm_event.id = %1";
- $params = array(1 => array($this->_id, 'Integer'));
+ $params = [1 => [$this->_id, 'Integer']];
$this->pager($fromClause, $whereClause, $params);
$orderBy = $this->orderBy();
@@ -98,7 +98,7 @@ public function run() {
ORDER BY $orderBy
LIMIT $offset, $rowCount";
- $rows = array();
+ $rows = [];
$object = CRM_Core_DAO::executeQuery($query, $params);
$statusLookup = CRM_Event_PseudoConstant::participantStatus();
while ($object->fetch()) {
@@ -106,13 +106,13 @@ public function run() {
if ($status) {
$status = ts($status);
}
- $row = array(
+ $row = [
'id' => $object->contact_id,
'participantID' => $object->participant_id,
'name' => $object->name,
'status' => $status,
'date' => $object->register_date,
- );
+ ];
$rows[] = $row;
}
$this->assign_by_ref('rows', $rows);
@@ -127,7 +127,7 @@ public function run() {
*/
public function pager($fromClause, $whereClause, $whereParams) {
- $params = array();
+ $params = [];
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
@@ -154,22 +154,22 @@ public function pager($fromClause, $whereClause, $whereParams) {
public function orderBy() {
static $headers = NULL;
if (!$headers) {
- $headers = array();
- $headers[1] = array(
+ $headers = [];
+ $headers[1] = [
'name' => ts('Name'),
'sort' => 'civicrm_contact.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- );
- $headers[2] = array(
+ ];
+ $headers[2] = [
'name' => ts('Status'),
'sort' => 'civicrm_participant.status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
- $headers[3] = array(
+ ];
+ $headers[3] = [
'name' => ts('Register Date'),
'sort' => 'civicrm_participant.register_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
+ ];
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
diff --git a/CRM/Event/Page/ParticipantListing/Simple.php b/CRM/Event/Page/ParticipantListing/Simple.php
index 3f7f75957e2a..c2db2255ee19 100644
--- a/CRM/Event/Page/ParticipantListing/Simple.php
+++ b/CRM/Event/Page/ParticipantListing/Simple.php
@@ -1,9 +1,9 @@
_id,
'title'
);
- CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Participants', [1 => $this->_eventTitle]));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
@@ -74,7 +74,7 @@ public function run() {
WHERE civicrm_event.id = %1
AND civicrm_participant.is_test = 0
AND civicrm_participant.status_id IN ( 1, 2 )";
- $params = array(1 => array($this->_id, 'Integer'));
+ $params = [1 => [$this->_id, 'Integer']];
$this->pager($fromClause, $whereClause, $params);
$orderBy = $this->orderBy();
@@ -91,15 +91,15 @@ public function run() {
ORDER BY $orderBy
LIMIT $offset, $rowCount";
- $rows = array();
+ $rows = [];
$object = CRM_Core_DAO::executeQuery($query, $params);
while ($object->fetch()) {
- $row = array(
+ $row = [
'id' => $object->contact_id,
'participantID' => $object->participant_id,
'name' => $object->name,
'email' => $object->email,
- );
+ ];
$rows[] = $row;
}
$this->assign_by_ref('rows', $rows);
@@ -114,7 +114,7 @@ public function run() {
*/
public function pager($fromClause, $whereClause, $whereParams) {
- $params = array();
+ $params = [];
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
@@ -142,18 +142,18 @@ public function pager($fromClause, $whereClause, $whereParams) {
public function orderBy() {
static $headers = NULL;
if (!$headers) {
- $headers = array();
- $headers[1] = array(
+ $headers = [];
+ $headers[1] = [
'name' => ts('Name'),
'sort' => 'civicrm_contact.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- );
+ ];
if ($this->_participantListingType == 'Name and Email') {
- $headers[2] = array(
+ $headers[2] = [
'name' => ts('Email'),
'sort' => 'civicrm_email.email',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
+ ];
}
}
$sortID = NULL;
diff --git a/CRM/Event/Page/Tab.php b/CRM/Event/Page/Tab.php
index 7dd25d396afb..dadc9244d9e6 100644
--- a/CRM/Event/Page/Tab.php
+++ b/CRM/Event/Page/Tab.php
@@ -1,9 +1,9 @@
assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactId);
// Refresh other tabs with related data
- $this->ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
- );
+ ];
if (CRM_Core_Permission::access('CiviContribute')) {
$this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
@@ -95,7 +95,7 @@ public function view() {
*/
public function edit() {
// set https for offline cc transaction
- $mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
if ($mode == 'test' || $mode == 'live') {
CRM_Utils_System::redirectToSSL();
}
@@ -118,8 +118,21 @@ public function edit() {
return $controller->run();
}
+ public function delete() {
+ $controller = new CRM_Core_Controller_Simple(
+ 'CRM_Event_Form_Participant',
+ ts('Delete Participant'),
+ $this->_action
+ );
+
+ $controller->setEmbedded(TRUE);
+ $controller->set('id', $this->_id);
+ $controller->set('cid', $this->_contactId);
+ $controller->run();
+ }
+
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -167,13 +180,12 @@ public function run() {
if ($this->_action & CRM_Core_Action::VIEW) {
$this->view();
}
- elseif ($this->_action & (CRM_Core_Action::UPDATE |
- CRM_Core_Action::ADD |
- CRM_Core_Action::DELETE
- )
- ) {
+ elseif ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
$this->edit();
}
+ elseif ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::DETACH)) {
+ $this->delete();
+ }
else {
$this->browse();
}
diff --git a/CRM/Event/Page/UserDashboard.php b/CRM/Event/Page/UserDashboard.php
index 23cf548d2675..5658480907ce 100644
--- a/CRM/Event/Page/UserDashboard.php
+++ b/CRM/Event/Page/UserDashboard.php
@@ -1,9 +1,9 @@
ts('Positive'),
'Pending' => ts('Pending'),
'Waiting' => ts('Waiting'),
'Negative' => ts('Negative'),
- );
+ ];
}
/**
@@ -199,7 +199,7 @@ public static function &participantStatusClass() {
public static function &participantRole($id = NULL, $cond = NULL) {
$index = $cond ? $cond : 'No Condition';
if (!CRM_Utils_Array::value($index, self::$participantRole)) {
- self::$participantRole[$index] = array();
+ self::$participantRole[$index] = [];
$condition = NULL;
@@ -229,7 +229,7 @@ public static function &participantRole($id = NULL, $cond = NULL) {
*/
public static function &participantListing($id = NULL) {
if (!self::$participantListing) {
- self::$participantListing = array();
+ self::$participantListing = [];
self::$participantListing = CRM_Core_OptionGroup::values('participant_listing');
}
@@ -250,7 +250,7 @@ public static function &participantListing($id = NULL) {
*/
public static function &eventType($id = NULL) {
if (!self::$eventType) {
- self::$eventType = array();
+ self::$eventType = [];
self::$eventType = CRM_Core_OptionGroup::values('event_type');
}
diff --git a/CRM/Event/Selector/Search.php b/CRM/Event/Selector/Search.php
index ce7ecfb53037..fb79e008db8e 100644
--- a/CRM/Event/Selector/Search.php
+++ b/CRM/Event/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=event' . $extraParams,
'title' => ts('View Participation'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Participation'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Participation'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -313,10 +313,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$this->_eventClause
);
// process the result of the query
- $rows = array();
+ $rows = [];
//lets handle view, edit and delete separately. CRM-4418
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit event participants')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -334,7 +334,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
@@ -363,45 +363,59 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['showConfirmUrl'] = ($statusClass == 'Pending') ? TRUE : FALSE;
if (!empty($row['participant_is_test'])) {
- $row['participant_status'] .= ' (' . ts('test') . ')';
+ $row['participant_status'] = CRM_Core_TestEntity::appendTestText($row['participant_status']);
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->participant_id;
$links = self::links($this->_key, $this->_context, $this->_compContext);
if ($statusTypes[$row['participant_status_id']] == 'Partially paid') {
- $links[CRM_Core_Action::ADD] = array(
+ $links[CRM_Core_Action::ADD] = [
'name' => ts('Record Payment'),
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event',
'title' => ts('Record Payment'),
- );
+ ];
if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
- $links[CRM_Core_Action::BASIC] = array(
+ $links[CRM_Core_Action::BASIC] = [
'name' => ts('Submit Credit Card payment'),
'url' => 'civicrm/payment/add',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event&mode=live',
'title' => ts('Submit Credit Card payment'),
- );
+ ];
}
}
if ($statusTypes[$row['participant_status_id']] == 'Pending refund') {
- $links[CRM_Core_Action::ADD] = array(
+ $links[CRM_Core_Action::ADD] = [
'name' => ts('Record Refund'),
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event',
'title' => ts('Record Refund'),
- );
+ ];
+ }
+
+ // CRM-20879: Show 'Transfer or Cancel' action only if logged in user
+ // have 'edit event participants' permission and participant status
+ // is not Cancelled or Transferred
+ if (in_array(CRM_Core_Permission::EDIT, $permissions) &&
+ !in_array($statusTypes[$row['participant_status_id']], ['Cancelled', 'Transferred'])
+ ) {
+ $links[] = [
+ 'name' => ts('Transfer or Cancel'),
+ 'url' => 'civicrm/event/selfsvcupdate',
+ 'qs' => 'reset=1&pid=%%id%%&is_backoffice=1&cs=' . CRM_Contact_BAO_Contact_Utils::generateChecksum($result->contact_id, NULL, 'inf'),
+ 'title' => ts('Transfer or Cancel'),
+ ];
}
$row['action'] = CRM_Core_Action::formLink($links,
$mask,
- array(
+ [
'id' => $result->participant_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'participant.selector.row',
@@ -424,7 +438,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
if (!empty($row['participant_role_id'])) {
- $viewRoles = array();
+ $viewRoles = [];
foreach (explode($sep, $row['participant_role_id']) as $k => $v) {
$viewRoles[] = $participantRoles[$v];
}
@@ -458,54 +472,54 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Event'),
'sort' => 'event_title',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Fee Level'),
'sort' => 'participant_fee_level',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Amount'),
'sort' => 'participant_fee_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Registered'),
'sort' => 'participant_register_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Event Date(s)'),
'sort' => 'event_start_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'participant_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Role'),
'sort' => 'participant_role_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact Type')),
- array(
+ $pre = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Participant'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
@@ -516,7 +530,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Event/StateMachine/Registration.php b/CRM/Event/StateMachine/Registration.php
index 0df4e4925d2b..d3120fb61c34 100644
--- a/CRM/Event/StateMachine/Registration.php
+++ b/CRM/Event/StateMachine/Registration.php
@@ -1,9 +1,9 @@
NULL);
+ $pages = ['CRM_Event_Form_Registration_Register' => NULL];
//handle additional participant scenario, where we need to insert participant pages on runtime
$additionalParticipant = NULL;
@@ -83,10 +83,10 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
$pages = array_merge($pages, $extraPages);
}
- $additionalPages = array(
+ $additionalPages = [
'CRM_Event_Form_Registration_Confirm' => NULL,
'CRM_Event_Form_Registration_ThankYou' => NULL,
- );
+ ];
$pages = array_merge($pages, $additionalPages);
diff --git a/CRM/Event/StateMachine/Search.php b/CRM/Event/StateMachine/Search.php
index c4ca4e7d5be9..f31b006fbadc 100644
--- a/CRM/Event/StateMachine/Search.php
+++ b/CRM/Event/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Event_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -82,7 +82,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Event/Task.php b/CRM/Event/Task.php
index 4bc04bf7bd55..82afc9194757 100644
--- a/CRM/Event/Task.php
+++ b/CRM/Event/Task.php
@@ -1,9 +1,9 @@
The Task title,
+ * 'class' => The Task Form class name,
+ * 'result => Boolean. FIXME: Not sure what this is for
+ * ]
*/
- public static function &tasks() {
- if (!(self::$_tasks)) {
- self::$_tasks = array(
- 1 => array(
+ public static function tasks() {
+ if (!self::$_tasks) {
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete participants from event'),
'class' => 'CRM_Event_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Event_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export participants'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
+ ],
+ self::BATCH_UPDATE => [
'title' => ts('Update multiple participants'),
- 'class' => array(
+ 'class' => [
'CRM_Event_Form_Task_PickProfile',
'CRM_Event_Form_Task_Batch',
- ),
+ ],
'result' => TRUE,
- ),
- 5 => array(
+ ],
+ self::CANCEL_REGISTRATION => [
'title' => ts('Cancel registration'),
'class' => 'CRM_Event_Form_Task_Cancel',
'result' => FALSE,
- ),
- 6 => array(
- 'title' => ts('Email - send now'),
+ ],
+ self::TASK_EMAIL => [
+ 'title' => ts('Email - send now (to %1 or less)', [
+ 1 => Civi::settings()
+ ->get('simple_mail_limit'),
+ ]),
'class' => 'CRM_Event_Form_Task_Email',
'result' => TRUE,
- ),
- 13 => array(
+ ],
+ self::SAVE_SEARCH => [
'title' => ts('Group - create smart group'),
'class' => 'CRM_Event_Form_Task_SaveSearch',
'result' => TRUE,
- ),
- 14 => array(
+ ],
+ self::SAVE_SEARCH_UPDATE => [
'title' => ts('Group - update smart group'),
'class' => 'CRM_Event_Form_Task_SaveSearch_Update',
'result' => TRUE,
- ),
- 15 => array(
+ ],
+ self::PARTICIPANT_STATUS => [
'title' => ts('Participant status - change'),
'class' => 'CRM_Event_Form_Task_ParticipantStatus',
'result' => TRUE,
- ),
- 16 => array(
+ ],
+ self::LABEL_CONTACTS => [
'title' => ts('Name badges - print'),
'class' => 'CRM_Event_Form_Task_Badge',
'result' => FALSE,
- ),
- 17 => array(
+ ],
+ self::PDF_LETTER => [
'title' => ts('PDF letter - print for participants'),
'class' => 'CRM_Event_Form_Task_PDF',
'result' => TRUE,
- ),
- 20 => array(
+ ],
+ self::GROUP_ADD => [
'title' => ts('Group - add contacts'),
'class' => 'CRM_Event_Form_Task_AddToGroup',
'result' => FALSE,
- ),
- );
+ ],
+ ];
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviEvent')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit event participants')) {
- unset(self::$_tasks[4], self::$_tasks[5], self::$_tasks[15]);
+ unset(self::$_tasks[self::BATCH_UPDATE], self::$_tasks[self::CANCEL_REGISTRATION], self::$_tasks[self::PARTICIPANT_STATUS]);
}
- CRM_Utils_Hook::searchTasks('event', self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles
- * for participants
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- // skip Update Smart Group task
- if ($id != self::SAVE_SEARCH_UPDATE) {
- $titles[$id] = $value['title'];
- }
- }
- return $titles;
- }
-
- /**
- * These tasks get added based on the context the user is in.
- *
- * @return array
- * the set of optional tasks for a group of contacts
- */
- public static function &optionalTaskTitle() {
- $tasks = array(
- 14 => self::$_tasks[14]['title'],
- );
- return $tasks;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit event participants')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- 6 => self::$_tasks[6]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ self::TASK_EMAIL => self::$_tasks[self::TASK_EMAIL]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviEvent')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -227,13 +195,9 @@ public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
- $value = 2;
+ $value = self::TASK_PRINT;
}
- asort(self::$_tasks);
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Event/Tokens.php b/CRM/Event/Tokens.php
index 423dd79a1d7a..1f1b1f716e68 100644
--- a/CRM/Event/Tokens.php
+++ b/CRM/Event/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -45,7 +45,7 @@ class CRM_Event_Tokens extends \Civi\Token\AbstractTokenSubscriber {
*/
public function __construct() {
parent::__construct('event', array_merge(
- array(
+ [
'event_type' => ts('Event Type'),
'title' => ts('Event Title'),
'event_id' => ts('Event ID'),
@@ -60,7 +60,7 @@ public function __construct() {
'contact_email' => ts('Event Contact (Email)'),
'contact_phone' => ts('Event Contact (Phone)'),
'balance' => ts('Event Balance'),
- ),
+ ],
CRM_Utils_Token::getCustomFieldTokens('Event')
));
}
@@ -70,8 +70,7 @@ public function __construct() {
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
- return
- !empty($processor->context['actionMapping'])
+ return !empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_participant';
}
@@ -85,7 +84,8 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
return;
}
- $e->query->select('e.*'); // FIXME: seems too broad.
+ // FIXME: seems too broad.
+ $e->query->select('e.*');
$e->query->select('ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone');
$e->query->join('participant_stuff', "
!casMailingJoinType civicrm_event ev ON e.event_id = ev.id
@@ -105,7 +105,7 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
$actionSearchResult = $row->context['actionSearchResult'];
if ($field == 'location') {
- $loc = array();
+ $loc = [];
$stateProvince = \CRM_Core_PseudoConstant::stateProvince();
$loc['street_address'] = $actionSearchResult->street_address;
$loc['city'] = $actionSearchResult->city;
@@ -122,7 +122,7 @@ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefe
$row
->tokens($entity, $field, \CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $actionSearchResult->event_id, TRUE, NULL, FALSE));
}
- elseif (in_array($field, array('start_date', 'end_date'))) {
+ elseif (in_array($field, ['start_date', 'end_date'])) {
$row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->$field));
}
elseif ($field == 'balance') {
diff --git a/CRM/Event/xml/Menu/Event.xml b/CRM/Event/xml/Menu/Event.xml
index f9d1d464eff6..7cc9a3ba6894 100644
--- a/CRM/Event/xml/Menu/Event.xml
+++ b/CRM/Event/xml/Menu/Event.xml
@@ -138,7 +138,7 @@
civicrm/admin/setting/preferences/eventCiviEvent Component Settings
- CRM_Admin_Form_Preferences_Event
+ CRM_Admin_Form_GenericConfigure global CiviEvent behaviors.access CiviEvent,administer CiviCRMCiviEvent
diff --git a/CRM/Export/BAO/Export.php b/CRM/Export/BAO/Export.php
index 4ddb9011172e..eb1e98a5c8d2 100644
--- a/CRM/Export/BAO/Export.php
+++ b/CRM/Export/BAO/Export.php
@@ -1,9 +1,9 @@
getExportMode();
+ $queryMode = $processor->getQueryMode();
if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
CRM_Utils_Array::value('notes', $returnProperties) ||
// CRM-9552
@@ -186,7 +140,7 @@ public static function getGroupBy($exportMode, $queryMode, $returnProperties, $q
$groupBy = 'civicrm_contribution.id';
if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
// especial group by when soft credit columns are included
- $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
+ $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
}
break;
@@ -203,58 +157,7 @@ public static function getGroupBy($exportMode, $queryMode, $returnProperties, $q
$groupBy = "civicrm_activity.id ";
}
- if (!empty($groupBy)) {
- $groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($query->_select, $groupBy);
- }
-
- return $groupBy;
- }
-
- /**
- * Define extra properties for the export based on query mode
- *
- * @param string $queryMode
- * Query Mode
- * @return array $extraProperties
- * Extra Properties
- */
- public static function defineExtraProperties($queryMode) {
- switch ($queryMode) {
- case CRM_Contact_BAO_Query::MODE_EVENT:
- $paymentFields = TRUE;
- $paymentTableId = 'participant_id';
- $extraReturnProperties = array();
- break;
-
- case CRM_Contact_BAO_Query::MODE_MEMBER:
- $paymentFields = TRUE;
- $paymentTableId = 'membership_id';
- $extraReturnProperties = array();
- break;
-
- case CRM_Contact_BAO_Query::MODE_PLEDGE:
- $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
- $paymentFields = TRUE;
- $paymentTableId = 'pledge_payment_id';
- break;
-
- case CRM_Contact_BAO_Query::MODE_CASE:
- $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
- $paymentFields = FALSE;
- $paymentTableId = '';
- break;
-
- default:
- $paymentFields = FALSE;
- $paymentTableId = '';
- $extraReturnProperties = array();
- }
- $extraProperties = array(
- 'paymentFields' => $paymentFields,
- 'paymentTableId' => $paymentTableId,
- 'extraReturnProperties' => $extraReturnProperties,
- );
- return $extraProperties;
+ return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
}
/**
@@ -286,6 +189,10 @@ public static function defineExtraProperties($queryMode) {
* @param array $exportParams
* @param string $queryOperator
*
+ * @return array|null
+ * An array can be requested from within a unit test.
+ *
+ * @throws \CRM_Core_Exception
*/
public static function exportComponents(
$selectAll,
@@ -299,121 +206,38 @@ public static function exportComponents(
$componentTable = NULL,
$mergeSameAddress = FALSE,
$mergeSameHousehold = FALSE,
- $exportParams = array(),
+ $exportParams = [],
$queryOperator = 'AND'
) {
- $returnProperties = array();
- $paymentFields = $selectedPaymentFields = FALSE;
-
- $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
- // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
- // without manually testing the export of IM provider still works.
- $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
- $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
- NULL,
- NULL,
- NULL,
- NULL,
- TRUE,
- 'name',
- FALSE
+ $isPostalOnly = (
+ isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
+ $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
);
- $queryMode = self::getQueryMode($exportMode);
+ $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly);
+ $returnProperties = [];
if ($fields) {
- //construct return properties
- $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
- $locationTypeFields = array(
- 'street_address',
- 'supplemental_address_1',
- 'supplemental_address_2',
- 'supplemental_address_3',
- 'city',
- 'postal_code',
- 'postal_code_suffix',
- 'geo_code_1',
- 'geo_code_2',
- 'state_province',
- 'country',
- 'phone',
- 'email',
- 'im',
- );
-
foreach ($fields as $key => $value) {
- $phoneTypeId = $imProviderId = $relationField = NULL;
- $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
- if (!$fieldName) {
+ $fieldName = CRM_Utils_Array::value(1, $value);
+ if (!$fieldName || $processor->isHouseholdMergeRelationshipTypeKey($fieldName)) {
continue;
}
- // get phoneType id and IM service provider id separately
- if ($fieldName == 'phone') {
- $phoneTypeId = CRM_Utils_Array::value(3, $value);
- }
- elseif ($fieldName == 'im') {
- $imProviderId = CRM_Utils_Array::value(3, $value);
- }
- if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
- if (!empty($value[2])) {
- $relationField = CRM_Utils_Array::value(2, $value);
- if (trim(CRM_Utils_Array::value(3, $value))) {
- $relLocTypeId = CRM_Utils_Array::value(3, $value);
- }
- else {
- $relLocTypeId = 'Primary';
- }
-
- if ($relationField == 'phone') {
- $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
- }
- elseif ($relationField == 'im') {
- $relIMProviderId = CRM_Utils_Array::value(4, $value);
- }
- }
- elseif (!empty($value[4])) {
- $relationField = CRM_Utils_Array::value(4, $value);
- $relLocTypeId = CRM_Utils_Array::value(5, $value);
- if ($relationField == 'phone') {
- $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
- }
- elseif ($relationField == 'im') {
- $relIMProviderId = CRM_Utils_Array::value(6, $value);
- }
- }
- }
-
- $contactType = CRM_Utils_Array::value(0, $value);
- $locTypeId = CRM_Utils_Array::value(2, $value);
-
- if ($relationField) {
- if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
- if ($relPhoneTypeId) {
- $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
- }
- elseif ($relIMProviderId) {
- $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
- }
- else {
- $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
- }
- $relPhoneTypeId = $relIMProviderId = NULL;
- }
- else {
- $returnProperties[$relationshipTypes][$relationField] = 1;
- }
+ if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) || !empty($value[4]))) {
+ $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
}
- elseif (is_numeric($locTypeId)) {
- if ($phoneTypeId) {
- $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
+ elseif (is_numeric(CRM_Utils_Array::value(2, $value))) {
+ $locationName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_Address', 'location_type_id', $value[2]);
+ if ($fieldName == 'phone') {
+ $returnProperties['location'][$locationName]['phone-' . CRM_Utils_Array::value(3, $value)] = 1;
}
- elseif ($imProviderId) {
- $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
+ elseif ($fieldName == 'im') {
+ $returnProperties['location'][$locationName]['im-' . CRM_Utils_Array::value(3, $value)] = 1;
}
else {
- $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
+ $returnProperties['location'][$locationName][$fieldName] = 1;
}
}
else {
@@ -422,14 +246,6 @@ public static function exportComponents(
if ($fieldName == 'event_id') {
$returnProperties['event_id'] = 1;
}
- elseif (
- $exportMode == CRM_Export_Form_Select::EVENT_EXPORT &&
- array_key_exists($fieldName, self::componentPaymentFields())
- ) {
- $selectedPaymentFields = TRUE;
- $paymentTableId = 'participant_id';
- $returnProperties[$fieldName] = 1;
- }
else {
$returnProperties[$fieldName] = 1;
}
@@ -441,56 +257,11 @@ public static function exportComponents(
}
}
else {
- $primary = TRUE;
- $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
- foreach ($fields as $key => $var) {
- if ($key && (substr($key, 0, 6) != 'custom')) {
- //for CRM=952
- $returnProperties[$key] = 1;
- }
- }
-
- if ($primary) {
- $returnProperties['location_type'] = 1;
- $returnProperties['im_provider'] = 1;
- $returnProperties['phone_type_id'] = 1;
- $returnProperties['provider_id'] = 1;
- $returnProperties['current_employer'] = 1;
- }
-
- $extraProperties = self::defineExtraProperties($queryMode);
- $paymentFields = $extraProperties['paymentFields'];
- $extraReturnProperties = $extraProperties['extraReturnProperties'];
- $paymentTableId = $extraProperties['paymentTableId'];
-
- if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
- $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
- if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
- // soft credit columns are not automatically populated, because contribution search doesn't require them by default
- $componentReturnProperties = array_merge(
- $componentReturnProperties,
- CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
- }
- $returnProperties = array_merge($returnProperties, $componentReturnProperties);
-
- if (!empty($extraReturnProperties)) {
- $returnProperties = array_merge($returnProperties, $extraReturnProperties);
- }
-
- // unset non exportable fields for components
- $nonExpoFields = array(
- 'groups',
- 'tags',
- 'notes',
- 'contribution_status_id',
- 'pledge_status_id',
- 'pledge_payment_status_id',
- );
- foreach ($nonExpoFields as $value) {
- unset($returnProperties[$value]);
- }
- }
+ $returnProperties = $processor->getDefaultReturnProperties();
}
+ // @todo - we are working towards this being entirely a property of the processor
+ $processor->setReturnProperties($returnProperties);
+ $paymentTableId = $processor->getPaymentTableID();
if ($mergeSameAddress) {
//make sure the addressee fields are selected
@@ -505,8 +276,8 @@ public static function exportComponents(
$returnProperties['state_province'] = 1;
// some columns are required for assistance incase they are not already present
- $exportParams['merge_same_address']['temp_columns'] = array();
- $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
+ $exportParams['merge_same_address']['temp_columns'] = [];
+ $tempColumns = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
foreach ($tempColumns as $column) {
if (!array_key_exists($column, $returnProperties)) {
$returnProperties[$column] = 1;
@@ -533,12 +304,12 @@ public static function exportComponents(
$returnProperties = array_merge($returnProperties, $moreReturnProperties);
}
- $exportParams['postal_mailing_export']['temp_columns'] = array();
+ $exportParams['postal_mailing_export']['temp_columns'] = [];
if ($exportParams['exportOption'] == 2 &&
isset($exportParams['postal_mailing_export']) &&
CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
) {
- $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
+ $postalColumns = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
foreach ($postalColumns as $column) {
if (!array_key_exists($column, $returnProperties)) {
$returnProperties[$column] = 1;
@@ -553,111 +324,17 @@ public static function exportComponents(
CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
}
- $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
- FALSE, FALSE, $queryMode,
- FALSE, TRUE, TRUE, NULL, $queryOperator
- );
-
- //sort by state
- //CRM-15301
- $query->_sort = $order;
- list($select, $from, $where, $having) = $query->query();
+ list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
if ($mergeSameHousehold == 1) {
if (empty($returnProperties['id'])) {
$returnProperties['id'] = 1;
}
- //also merge Head of Household
- $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
- $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
-
- foreach ($returnProperties as $key => $value) {
- if (!array_key_exists($key, $contactRelationshipTypes)) {
- $returnProperties[$relationKeyMOH][$key] = $value;
- $returnProperties[$relationKeyHOH][$key] = $value;
- }
- }
-
- unset($returnProperties[$relationKeyMOH]['location_type']);
- unset($returnProperties[$relationKeyMOH]['im_provider']);
- unset($returnProperties[$relationKeyHOH]['location_type']);
- unset($returnProperties[$relationKeyHOH]['im_provider']);
+ $processor->setHouseholdMergeReturnProperties(array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1)));
}
- $allRelContactArray = $relationQuery = array();
-
- foreach ($contactRelationshipTypes as $rel => $dnt) {
- if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
- $allRelContactArray[$rel] = array();
- // build Query for each relationship
- $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
- NULL, FALSE, FALSE, $queryMode
- );
- list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
-
- list($id, $direction) = explode('_', $rel, 2);
- // identify the relationship direction
- $contactA = 'contact_id_a';
- $contactB = 'contact_id_b';
- if ($direction == 'b_a') {
- $contactA = 'contact_id_b';
- $contactB = 'contact_id_a';
- }
- if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
- $relIDs = $ids;
- }
- elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
- $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
- $query = "SELECT contact_id FROM civicrm_activity_contact
- WHERE activity_id IN ( " . implode(',', $ids) . ") AND
- record_type_id = {$sourceID}";
- $dao = CRM_Core_DAO::executeQuery($query);
- while ($dao->fetch()) {
- $relIDs[] = $dao->contact_id;
- }
- }
- else {
- $component = self::exportComponent($exportMode);
-
- if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
- $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
- }
- else {
- $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
- }
- }
-
- $relationshipJoin = $relationshipClause = '';
- if (!$selectAll && $componentTable) {
- $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
- }
- elseif (!empty($relIDs)) {
- $relID = implode(',', $relIDs);
- $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
- }
-
- $relationFrom = " {$relationFrom}
- INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
- {$relationshipJoin} ";
-
- //check for active relationship status only
- $today = date('Ymd');
- $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
- $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
- $relationGroupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($relationQuery[$rel]->_select, "crel.{$contactA}");
- $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
- $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
-
- $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
- while ($allRelContactDAO->fetch()) {
- //FIX Me: Migrate this to table rather than array
- // build the array of all related contacts
- $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone($allRelContactDAO);
- }
- $allRelContactDAO->free();
- }
- }
+ self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
// make sure the groups stuff is included only if specifically specified
// by the fields param (CRM-1969), else we limit the contacts outputted to only
@@ -702,7 +379,7 @@ public static function exportComponents(
$queryString = "$select $from $where $having";
- $groupBy = self::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
+ $groupBy = self::getGroupBy($processor, $returnProperties, $query);
$queryString .= $groupBy;
@@ -724,31 +401,34 @@ public static function exportComponents(
$addPaymentHeader = FALSE;
- $paymentDetails = array();
- if ($paymentFields || $selectedPaymentFields) {
+ list($outputColumns, $metadata) = self::getExportStructureArrays($returnProperties, $processor);
+ if (!empty($exportParams['merge_same_address']['temp_columns'])) {
+ // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
+ // test exists covering this...
+ foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
+ $processor->setColumnAsCalculationOnly($field);
+ }
+ }
+
+ $paymentDetails = [];
+ if ($processor->isExportPaymentFields()) {
// get payment related in for event and members
$paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
//get all payment headers.
// If we haven't selected specific payment fields, load in all the
// payment headers.
- if (!$selectedPaymentFields) {
- $paymentHeaders = self::componentPaymentFields();
+ if (!$processor->isExportSpecifiedPaymentFields()) {
if (!empty($paymentDetails)) {
$addPaymentHeader = TRUE;
+ foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
+ $processor->addOutputSpecification($paymentField);
+ }
}
}
- // If we have selected specific payment fields, leave the payment headers
- // as an empty array; the headers for each selected field will be added
- // elsewhere.
- else {
- $paymentHeaders = array();
- }
- $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
}
- $componentDetails = array();
- $setHeader = TRUE;
+ $componentDetails = [];
$rowCount = self::EXPORT_ROW_COUNT;
$offset = 0;
@@ -757,302 +437,26 @@ public static function exportComponents(
$count = -1;
- // for CRM-3157 purposes
- $i18n = CRM_Core_I18n::singleton();
-
- list($outputColumns, $headerRows, $sqlColumns, $metadata) = self::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
-
+ $headerRows = $processor->getHeaderRows();
+ $sqlColumns = $processor->getSQLColumns();
+ $exportTempTable = self::createTempTable($sqlColumns);
$limitReached = FALSE;
+
while (!$limitReached) {
$limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
- $dao = CRM_Core_DAO::executeQuery($limitQuery);
+ CRM_Core_DAO::disableFullGroupByMode();
+ $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
+ CRM_Core_DAO::reenableFullGroupByMode();
// If this is less than our limit by the end of the iteration we do not need to run the query again to
// check if some remain.
$rowsThisIteration = 0;
- while ($dao->fetch()) {
+ while ($iterationDAO->fetch()) {
$count++;
$rowsThisIteration++;
- $row = array();
-
- //convert the pseudo constants
- // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
- // temporary iterationDAO object to get around it.
- // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
- // these additional properties are NOT reset when the $dao cycles through the while loop
- // nor are they overwritten as they are not in the loop
- // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
- // relevant property is set.
- // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
- // export class before tackling a better architectural fix
- $iterationDAO = clone $dao;
- $query->convertToPseudoNames($iterationDAO);
-
- //first loop through output columns so that we return what is required, and in same order.
- foreach ($outputColumns as $field => $value) {
-
- // add im_provider to $dao object
- if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
- $iterationDAO->im_provider = $iterationDAO->provider_id;
- }
-
- //build row values (data)
- $fieldValue = NULL;
- if (property_exists($iterationDAO, $field)) {
- $fieldValue = $iterationDAO->$field;
- // to get phone type from phone type id
- if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
- $fieldValue = $phoneTypes[$fieldValue];
- }
- elseif ($field == 'provider_id' || $field == 'im_provider') {
- $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
- }
- elseif (strstr($field, 'master_id')) {
- $masterAddressId = NULL;
- if (isset($iterationDAO->$field)) {
- $masterAddressId = $iterationDAO->$field;
- }
- // get display name of contact that address is shared.
- $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id);
- }
- }
-
- if ($field == 'id') {
- $row[$field] = $iterationDAO->contact_id;
- // special case for calculated field
- }
- elseif ($field == 'source_contact_id') {
- $row[$field] = $iterationDAO->contact_id;
- }
- elseif ($field == 'pledge_balance_amount') {
- $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
- // special case for calculated field
- }
- elseif ($field == 'pledge_next_pay_amount') {
- $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
- }
- elseif (array_key_exists($field, $contactRelationshipTypes)) {
- $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
- $relationQuery[$field]->convertToPseudoNames($relDAO);
- foreach ($value as $relationField => $relationValue) {
- if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
- $fieldValue = $relDAO->$relationField;
- if ($relationField == 'phone_type_id') {
- $fieldValue = $phoneTypes[$relationValue];
- }
- elseif ($relationField == 'provider_id') {
- $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
- }
- // CRM-13995
- elseif (is_object($relDAO) && in_array($relationField, array(
- 'email_greeting',
- 'postal_greeting',
- 'addressee',
- ))
- ) {
- //special case for greeting replacement
- $fldValue = "{$relationField}_display";
- $fieldValue = $relDAO->$fldValue;
- }
- }
- elseif (is_object($relDAO) && $relationField == 'state_province') {
- $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
- }
- elseif (is_object($relDAO) && $relationField == 'country') {
- $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
- }
- else {
- $fieldValue = '';
- }
- $field = $field . '_';
-
- if (is_object($relDAO) && $relationField == 'id') {
- $row[$field . $relationField] = $relDAO->contact_id;
- }
- elseif (is_array($relationValue) && $relationField == 'location') {
- foreach ($relationValue as $ltype => $val) {
- foreach (array_keys($val) as $fld) {
- $type = explode('-', $fld);
- $fldValue = "{$ltype}-" . $type[0];
- if (!empty($type[1])) {
- $fldValue .= "-" . $type[1];
- }
- // CRM-3157: localise country, region (both have ‘country’ context)
- // and state_province (‘province’ context)
- switch (TRUE) {
- case (!is_object($relDAO)):
- $row[$field . '_' . $fldValue] = '';
- break;
-
- case in_array('country', $type):
- case in_array('world_region', $type):
- $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
- array('context' => 'country')
- );
- break;
-
- case in_array('state_province', $type):
- $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
- array('context' => 'province')
- );
- break;
-
- default:
- $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
- break;
- }
- }
- }
- }
- elseif (isset($fieldValue) && $fieldValue != '') {
- //check for custom data
- if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
- $row[$field . $relationField] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
- }
- else {
- //normal relationship fields
- // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
- switch ($relationField) {
- case 'country':
- case 'world_region':
- $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
- break;
-
- case 'state_province':
- $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
- break;
-
- default:
- $row[$field . $relationField] = $fieldValue;
- break;
- }
- }
- }
- else {
- // if relation field is empty or null
- $row[$field . $relationField] = '';
- }
- }
- }
- elseif (isset($fieldValue) &&
- $fieldValue != ''
- ) {
- //check for custom data
- if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
- $row[$field] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
- }
-
- elseif (in_array($field, array(
- 'email_greeting',
- 'postal_greeting',
- 'addressee',
- ))) {
- //special case for greeting replacement
- $fldValue = "{$field}_display";
- $row[$field] = $iterationDAO->$fldValue;
- }
- else {
- //normal fields with a touch of CRM-3157
- switch ($field) {
- case 'country':
- case 'world_region':
- $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
- break;
-
- case 'state_province':
- $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
- break;
-
- case 'gender':
- case 'preferred_communication_method':
- case 'preferred_mail_format':
- case 'communication_style':
- $row[$field] = $i18n->crm_translate($fieldValue);
- break;
-
- default:
- if (isset($metadata[$field])) {
- // No I don't know why we do it this way & whether we could
- // make better use of pseudoConstants.
- if (!empty($metadata[$field]['context'])) {
- $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
- break;
- }
- if (!empty($metadata[$field]['pseudoconstant'])) {
- // This is not our normal syntax for pseudoconstants but I am a bit loath to
- // call an external function until sure it is not increasing php processing given this
- // may be iterated 100,000 times & we already have the $imProvider var loaded.
- // That can be next refactor...
- // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
- // but I have to reach a stable point....
- $varName = $metadata[$field]['pseudoconstant']['var'];
- $labels = $$varName;
- $row[$field] = $labels[$fieldValue];
- break;
- }
-
- }
- $row[$field] = $fieldValue;
- break;
- }
- }
- }
- elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
- $paymentData = CRM_Utils_Array::value($iterationDAO->$paymentTableId, $paymentDetails);
- $payFieldMapper = array(
- 'componentPaymentField_total_amount' => 'total_amount',
- 'componentPaymentField_contribution_status' => 'contribution_status',
- 'componentPaymentField_payment_instrument' => 'pay_instru',
- 'componentPaymentField_transaction_id' => 'trxn_id',
- 'componentPaymentField_received_date' => 'receive_date',
- );
- $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
- }
- else {
- // if field is empty or null
- $row[$field] = '';
- }
- }
-
- // add payment headers if required
- if ($addPaymentHeader && $paymentFields) {
- // @todo rather than do this for every single row do it before the loop starts.
- // where other header definitions take place.
- $headerRows = array_merge($headerRows, $paymentHeaders);
- foreach (array_keys($paymentHeaders) as $paymentHdr) {
- self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
- }
- }
-
- if ($setHeader) {
- $exportTempTable = self::createTempTable($sqlColumns);
- }
-
- //build header only once
- $setHeader = FALSE;
-
- // If specific payment fields have been selected for export, payment
- // data will already be in $row. Otherwise, add payment related
- // information, if appropriate.
- if ($addPaymentHeader) {
- if (!$selectedPaymentFields) {
- if ($paymentFields) {
- $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
- if (!is_array($paymentData) || empty($paymentData)) {
- $paymentData = $nullContributionDetails;
- }
- $row = array_merge($row, $paymentData);
- }
- elseif (!empty($paymentDetails)) {
- $row = array_merge($row, $nullContributionDetails);
- }
- }
- }
- //remove organization name for individuals if it is set for current employer
- if (!empty($row['contact_type']) &&
- $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
- ) {
- $row['organization_name'] = '';
+ $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
+ if ($row === FALSE) {
+ continue;
}
// add component info
@@ -1062,10 +466,9 @@ public static function exportComponents(
// output every $tempRowCount rows
if ($count % $tempRowCount == 0) {
self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
- $componentDetails = array();
+ $componentDetails = [];
}
}
- $dao->free();
if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
$limitReached = TRUE;
}
@@ -1077,83 +480,31 @@ public static function exportComponents(
// do merge same address and merge same household processing
if ($mergeSameAddress) {
- self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
- }
-
- // merge the records if they have corresponding households
- if ($mergeSameHousehold) {
- self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
- self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
- }
-
- // if postalMailing option is checked, exclude contacts who are deceased, have
- // "Do not mail" privacy setting, or have no street address
- if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
- $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
- ) {
- self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
+ self::mergeSameAddress($exportTempTable, $sqlColumns, $exportParams);
}
// call export hook
- CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
+ CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
// In order to be able to write a unit test against this function we need to suppress
// the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
if (empty($exportParams['suppress_csv_for_testing'])) {
- self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
+ self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor);
}
else {
- // return tableName and sqlColumns in test context
- return array($exportTempTable, $sqlColumns);
+ // return tableName sqlColumns headerRows in test context
+ return [$exportTempTable, $sqlColumns, $headerRows, $processor];
}
// delete the export temp table and component table
$sql = "DROP TABLE IF EXISTS {$exportTempTable}";
CRM_Core_DAO::executeQuery($sql);
-
+ CRM_Core_DAO::reenableFullGroupByMode();
CRM_Utils_System::civiExit();
}
else {
- CRM_Core_Error::fatal(ts('No records to export'));
- }
- }
-
- /**
- * Name of the export file based on mode.
- *
- * @param string $output
- * Type of output.
- * @param int $mode
- * Export mode.
- *
- * @return string
- * name of the file
- */
- public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) {
- switch ($mode) {
- case CRM_Export_Form_Select::CONTACT_EXPORT:
- return ts('CiviCRM Contact Search');
-
- case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
- return ts('CiviCRM Contribution Search');
-
- case CRM_Export_Form_Select::MEMBER_EXPORT:
- return ts('CiviCRM Member Search');
-
- case CRM_Export_Form_Select::EVENT_EXPORT:
- return ts('CiviCRM Participant Search');
-
- case CRM_Export_Form_Select::PLEDGE_EXPORT:
- return ts('CiviCRM Pledge Search');
-
- case CRM_Export_Form_Select::CASE_EXPORT:
- return ts('CiviCRM Case Search');
-
- case CRM_Export_Form_Select::GRANT_EXPORT:
- return ts('CiviCRM Grant Search');
-
- case CRM_Export_Form_Select::ACTIVITY_EXPORT:
- return ts('CiviCRM Activity Search');
+ CRM_Core_DAO::reenableFullGroupByMode();
+ throw new CRM_Core_Exception(ts('No records to export'));
}
}
@@ -1224,14 +575,14 @@ public static function exportCustom($customSearchClass, $formValues, $order) {
$header = array_keys($columns);
$fields = array_values($columns);
- $rows = array();
+ $rows = [];
$dao = CRM_Core_DAO::executeQuery($sql);
$alterRow = FALSE;
if (method_exists($search, 'alterRow')) {
$alterRow = TRUE;
}
while ($dao->fetch()) {
- $row = array();
+ $row = [];
foreach ($fields as $field) {
$unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
@@ -1243,152 +594,16 @@ public static function exportCustom($customSearchClass, $formValues, $order) {
$rows[] = $row;
}
- CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows);
+ CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
CRM_Utils_System::civiExit();
}
- /**
- * @param $query
- * @param $sqlColumns
- * @param $field
- */
- public static function sqlColumnDefn($query, &$sqlColumns, $field) {
- if (substr($field, -4) == '_a_b' || substr($field, -4) == '_b_a') {
- return;
- }
-
- $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
- if ($fieldName == 'id') {
- $fieldName = 'civicrm_primary_id';
- }
-
- // early exit for master_id, CRM-12100
- // in the DB it is an ID, but in the export, we retrive the display_name of the master record
- // also for current_employer, CRM-16939
- if ($fieldName == 'master_id' || $fieldName == 'current_employer') {
- $sqlColumns[$fieldName] = "$fieldName varchar(128)";
- return;
- }
-
- if (substr($fieldName, -11) == 'campaign_id') {
- // CRM-14398
- $sqlColumns[$fieldName] = "$fieldName varchar(128)";
- return;
- }
-
- $lookUp = array('prefix_id', 'suffix_id');
- // set the sql columns
- if (isset($query->_fields[$field]['type'])) {
- switch ($query->_fields[$field]['type']) {
- case CRM_Utils_Type::T_INT:
- case CRM_Utils_Type::T_BOOLEAN:
- if (in_array($field, $lookUp)) {
- $sqlColumns[$fieldName] = "$fieldName varchar(255)";
- }
- else {
- $sqlColumns[$fieldName] = "$fieldName varchar(16)";
- }
- break;
-
- case CRM_Utils_Type::T_STRING:
- if (isset($query->_fields[$field]['maxlength'])) {
- $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
- }
- else {
- $sqlColumns[$fieldName] = "$fieldName varchar(255)";
- }
- break;
-
- case CRM_Utils_Type::T_TEXT:
- case CRM_Utils_Type::T_LONGTEXT:
- case CRM_Utils_Type::T_BLOB:
- case CRM_Utils_Type::T_MEDIUMBLOB:
- $sqlColumns[$fieldName] = "$fieldName longtext";
- break;
-
- case CRM_Utils_Type::T_FLOAT:
- case CRM_Utils_Type::T_ENUM:
- case CRM_Utils_Type::T_DATE:
- case CRM_Utils_Type::T_TIME:
- case CRM_Utils_Type::T_TIMESTAMP:
- case CRM_Utils_Type::T_MONEY:
- case CRM_Utils_Type::T_EMAIL:
- case CRM_Utils_Type::T_URL:
- case CRM_Utils_Type::T_CCNUM:
- default:
- $sqlColumns[$fieldName] = "$fieldName varchar(32)";
- break;
- }
- }
- else {
- if (substr($fieldName, -3, 3) == '_id') {
- // for trxn_id and its variants use a longer buffer
- // to accommodate different systems - CRM-13739
- static $notRealIDFields = NULL;
- if ($notRealIDFields == NULL) {
- $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id', 'phone_type_id');
- }
-
- if (in_array($fieldName, $notRealIDFields)) {
- $sqlColumns[$fieldName] = "$fieldName varchar(255)";
- }
- else {
- $sqlColumns[$fieldName] = "$fieldName varchar(16)";
- }
- }
- elseif (substr($fieldName, -5, 5) == '_note') {
- $sqlColumns[$fieldName] = "$fieldName text";
- }
- else {
- $changeFields = array(
- 'groups',
- 'tags',
- 'notes',
- );
-
- if (in_array($fieldName, $changeFields)) {
- $sqlColumns[$fieldName] = "$fieldName text";
- }
- else {
- // set the sql columns for custom data
- if (isset($query->_fields[$field]['data_type'])) {
-
- switch ($query->_fields[$field]['data_type']) {
- case 'String':
- // May be option labels, which could be up to 512 characters
- $length = max(512, CRM_Utils_Array::value('text_length', $query->_fields[$field]));
- $sqlColumns[$fieldName] = "$fieldName varchar($length)";
- break;
-
- case 'Country':
- case 'StateProvince':
- case 'Link':
- $sqlColumns[$fieldName] = "$fieldName varchar(255)";
- break;
-
- case 'Memo':
- $sqlColumns[$fieldName] = "$fieldName text";
- break;
-
- default:
- $sqlColumns[$fieldName] = "$fieldName varchar(255)";
- break;
- }
- }
- else {
- $sqlColumns[$fieldName] = "$fieldName text";
- }
- }
- }
- }
- }
-
/**
* @param string $tableName
* @param $details
* @param $sqlColumns
*/
- public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
+ public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
if (empty($details)) {
return;
}
@@ -1403,12 +618,12 @@ public static function writeDetailsToTable($tableName, &$details, &$sqlColumns)
$id = 0;
}
- $sqlClause = array();
+ $sqlClause = [];
- foreach ($details as $dontCare => $row) {
+ foreach ($details as $row) {
$id++;
- $valueString = array($id);
- foreach ($row as $dontCare => $value) {
+ $valueString = [$id];
+ foreach ($row as $value) {
if (empty($value)) {
$valueString[] = "''";
}
@@ -1418,8 +633,8 @@ public static function writeDetailsToTable($tableName, &$details, &$sqlColumns)
}
$sqlClause[] = '(' . implode(',', $valueString) . ')';
}
-
- $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
+ $sqlColumns = array_merge(['id' => 1], $sqlColumns);
+ $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
$sqlValueString = implode(",\n", $sqlClause);
@@ -1427,7 +642,6 @@ public static function writeDetailsToTable($tableName, &$details, &$sqlColumns)
INSERT INTO $tableName $sqlColumnString
VALUES $sqlValueString
";
-
CRM_Core_DAO::executeQuery($sql);
}
@@ -1436,29 +650,26 @@ public static function writeDetailsToTable($tableName, &$details, &$sqlColumns)
*
* @return string
*/
- public static function createTempTable(&$sqlColumns) {
+ public static function createTempTable($sqlColumns) {
//creating a temporary table for the search result that need be exported
- $exportTempTable = CRM_Core_DAO::createTempTableName('civicrm_export', TRUE);
+ $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
// also create the sql table
- $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
- CRM_Core_DAO::executeQuery($sql);
+ $exportTempTable->drop();
- $sql = "
-CREATE TABLE {$exportTempTable} (
- id int unsigned NOT NULL AUTO_INCREMENT,
-";
- $sql .= implode(",\n", array_values($sqlColumns));
+ $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
+ if (!empty($sqlColumns)) {
+ $sql .= implode(",\n", array_values($sqlColumns)) . ',';
+ }
+
+ $sql .= "\n PRIMARY KEY ( id )";
- $sql .= ",
- PRIMARY KEY ( id )
-";
// add indexes for street_address and household_name if present
- $addIndices = array(
+ $addIndices = [
'street_address',
'household_name',
'civicrm_primary_id',
- );
+ ];
foreach ($addIndices as $index) {
if (isset($sqlColumns[$index])) {
@@ -1468,21 +679,16 @@ public static function createTempTable(&$sqlColumns) {
}
}
- $sql .= "
-) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
-";
-
- CRM_Core_DAO::executeQuery($sql);
- return $exportTempTable;
+ $exportTempTable->createWithColumns($sql);
+ return $exportTempTable->getName();
}
/**
* @param string $tableName
- * @param $headerRows
* @param $sqlColumns
* @param array $exportParams
*/
- public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
+ public static function mergeSameAddress($tableName, &$sqlColumns, $exportParams) {
// check if any records are present based on if they have used shared address feature,
// and not based on if city / state .. matches.
$sql = "
@@ -1533,7 +739,7 @@ public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns,
// unset ids from $merge already present in $linkedMerge
foreach ($linkedMerge as $masterID => $values) {
- $keys = array($masterID);
+ $keys = [$masterID];
$keys = array_merge($keys, array_keys($values['copy']));
foreach ($merge as $mid => $vals) {
if (in_array($mid, $keys)) {
@@ -1556,12 +762,12 @@ public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns,
SET addressee = %1, postal_greeting = %2, email_greeting = %3
WHERE id = %4
";
- $params = array(
- 1 => array($values['addressee'], 'String'),
- 2 => array($values['postalGreeting'], 'String'),
- 3 => array($values['emailGreeting'], 'String'),
- 4 => array($masterID, 'Integer'),
- );
+ $params = [
+ 1 => [$values['addressee'], 'String'],
+ 2 => [$values['postalGreeting'], 'String'],
+ 3 => [$values['emailGreeting'], 'String'],
+ 4 => [$masterID, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($sql, $params);
// delete all copies
@@ -1575,11 +781,12 @@ public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns,
}
// unset temporary columns that were added for postal mailing format
+ // @todo - this part is pretty close to ready to be removed....
if (!empty($exportParams['merge_same_address']['temp_columns'])) {
$unsetKeys = array_keys($sqlColumns);
foreach ($unsetKeys as $headerKey => $sqlColKey) {
if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
- unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
+ unset($sqlColumns[$sqlColKey]);
}
}
}
@@ -1592,21 +799,21 @@ public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns,
* @return array
*/
public static function _replaceMergeTokens($contactId, $exportParams) {
- $greetings = array();
+ $greetings = [];
$contact = NULL;
- $greetingFields = array(
+ $greetingFields = [
'postal_greeting',
'addressee',
- );
+ ];
foreach ($greetingFields as $greeting) {
if (!empty($exportParams[$greeting])) {
$greetingLabel = $exportParams[$greeting];
if (empty($contact)) {
- $values = array(
+ $values = [
'id' => $contactId,
'version' => 3,
- );
+ ];
$contact = civicrm_api('contact', 'get', $values);
if (!empty($contact['is_error'])) {
@@ -1615,7 +822,7 @@ public static function _replaceMergeTokens($contactId, $exportParams) {
$contact = $contact['values'][$contact['id']];
}
- $tokens = array('contact' => $greetingLabel);
+ $tokens = ['contact' => $greetingLabel];
$greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
}
}
@@ -1663,12 +870,12 @@ public static function _trimNonTokens(
* @return array
*/
public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
- static $contactGreetingTokens = array();
+ static $contactGreetingTokens = [];
$addresseeOptions = CRM_Core_OptionGroup::values('addressee');
$postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
- $merge = $parents = array();
+ $merge = $parents = [];
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
@@ -1710,11 +917,11 @@ public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress
$masterID = $parents[$masterID];
}
else {
- $merge[$masterID] = array(
+ $merge[$masterID] = [
'addressee' => $masterAddressee,
- 'copy' => array(),
+ 'copy' => [],
'postalGreeting' => $masterPostalGreeting,
- );
+ ];
$merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
}
}
@@ -1758,101 +965,14 @@ public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress
return $merge;
}
- /**
- * Merge household record into the individual record
- * if exists
- *
- * @param string $exportTempTable
- * Temporary temp table that stores the records.
- * @param array $headerRows
- * Array of headers for the export file.
- * @param array $sqlColumns
- * Array of names of the table columns of the temp table.
- * @param string $prefix
- * Name of the relationship type that is prefixed to the table columns.
- */
- public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
- $prefixColumn = $prefix . '_';
- $allKeys = array_keys($sqlColumns);
- $replaced = array();
- $headerRows = array_values($headerRows);
-
- // name map of the non standard fields in header rows & sql columns
- $mappingFields = array(
- 'civicrm_primary_id' => 'id',
- 'contact_source' => 'source',
- 'current_employer_id' => 'employer_id',
- 'contact_is_deleted' => 'is_deleted',
- 'name' => 'address_name',
- 'provider_id' => 'im_service_provider',
- 'phone_type_id' => 'phone_type',
- );
-
- //figure out which columns are to be replaced by which ones
- foreach ($sqlColumns as $columnNames => $dontCare) {
- if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) {
- $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64);
- }
- else {
- $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
-
- if (!empty($sqlColumns[$householdColName])) {
- $replaced[$columnNames] = $householdColName;
- }
- }
- }
- $query = "UPDATE $exportTempTable SET ";
-
- $clause = array();
- foreach ($replaced as $from => $to) {
- $clause[] = "$from = $to ";
- unset($sqlColumns[$to]);
- if ($key = CRM_Utils_Array::key($to, $allKeys)) {
- unset($headerRows[$key]);
- }
- }
- $query .= implode(",\n", $clause);
- $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
-
- CRM_Core_DAO::executeQuery($query);
-
- //drop the table columns that store redundant household info
- $dropQuery = "ALTER TABLE $exportTempTable ";
- foreach ($replaced as $householdColumns) {
- $dropClause[] = " DROP $householdColumns ";
- }
- $dropQuery .= implode(",\n", $dropClause);
-
- CRM_Core_DAO::executeQuery($dropQuery);
-
- // also drop the temp table if exists
- $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
- CRM_Core_DAO::executeQuery($sql);
-
- // clean up duplicate records
- $query = "
-CREATE TABLE {$exportTempTable}_temp SELECT *
-FROM {$exportTempTable}
-GROUP BY civicrm_primary_id ";
-
- CRM_Core_DAO::executeQuery($query);
-
- $query = "DROP TABLE $exportTempTable";
- CRM_Core_DAO::executeQuery($query);
-
- $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
- CRM_Core_DAO::executeQuery($query);
- }
-
/**
* @param $exportTempTable
* @param $headerRows
* @param $sqlColumns
- * @param $exportMode
- * @param null $saveFile
- * @param string $batchItems
+ * @param \CRM_Export_BAO_ExportProcessor $processor
*/
- public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
+ public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor) {
+ $exportMode = $processor->getExportMode();
$writeHeader = TRUE;
$offset = 0;
$limit = self::EXPORT_ROW_COUNT;
@@ -1869,241 +989,49 @@ public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColu
break;
}
- $componentDetails = array();
+ $componentDetails = [];
while ($dao->fetch()) {
- $row = array();
+ $row = [];
foreach ($sqlColumns as $column => $dontCare) {
$row[$column] = $dao->$column;
}
$componentDetails[] = $row;
}
- if ($exportMode == 'financial') {
- $getExportFileName = 'CiviCRM Contribution Search';
- }
- else {
- $getExportFileName = self::getExportFileName('csv', $exportMode);
- }
- $csvRows = CRM_Core_Report_Excel::writeCSVFile($getExportFileName,
+ CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
$headerRows,
$componentDetails,
NULL,
- $writeHeader,
- $saveFile);
-
- if ($saveFile && !empty($csvRows)) {
- $batchItems .= $csvRows;
- }
+ $writeHeader
+ );
$writeHeader = FALSE;
$offset += $limit;
}
}
- /**
- * Manipulate header rows for relationship fields.
- *
- * @param $headerRows
- * @param $contactRelationshipTypes
- */
- public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
- foreach ($headerRows as & $header) {
- $split = explode('-', $header);
- if ($relationTypeName = CRM_Utils_Array::value($split[0], $contactRelationshipTypes)) {
- $split[0] = $relationTypeName;
- $header = implode('-', $split);
- }
- }
- }
-
- /**
- * Exclude contacts who are deceased, have "Do not mail" privacy setting,
- * or have no street address
- * @param $exportTempTable
- * @param $headerRows
- * @param $sqlColumns
- * @param $exportParams
- */
- public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
- $whereClause = array();
-
- if (array_key_exists('is_deceased', $sqlColumns)) {
- $whereClause[] = 'is_deceased = 1';
- }
-
- if (array_key_exists('do_not_mail', $sqlColumns)) {
- $whereClause[] = 'do_not_mail = 1';
- }
-
- if (array_key_exists('street_address', $sqlColumns)) {
- $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
-
- // check for supplemental_address_1
- if (array_key_exists('supplemental_address_1', $sqlColumns)) {
- $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
- 'address_options', TRUE, NULL, TRUE
- );
- if (!empty($addressOptions['supplemental_address_1'])) {
- $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
- // enclose it again, since we are doing an AND in between a set of ORs
- $addressWhereClause = "( $addressWhereClause )";
- }
- }
-
- $whereClause[] = $addressWhereClause;
- }
-
- if (!empty($whereClause)) {
- $whereClause = implode(' OR ', $whereClause);
- $query = "
-DELETE
-FROM $exportTempTable
-WHERE {$whereClause}";
- CRM_Core_DAO::singleValueQuery($query);
- }
-
- // unset temporary columns that were added for postal mailing format
- if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
- $unsetKeys = array_keys($sqlColumns);
- foreach ($unsetKeys as $headerKey => $sqlColKey) {
- if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
- unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
- }
- }
- }
- }
-
/**
* Build componentPayment fields.
+ *
+ * This is no longer used by export but BAO_Mapping still calls it & we
+ * should find a generic way to handle this or move this to that class.
+ *
+ * @deprecated
*/
public static function componentPaymentFields() {
static $componentPaymentFields;
if (!isset($componentPaymentFields)) {
- $componentPaymentFields = array(
+ $componentPaymentFields = [
'componentPaymentField_total_amount' => ts('Total Amount'),
'componentPaymentField_contribution_status' => ts('Contribution Status'),
'componentPaymentField_received_date' => ts('Date Received'),
'componentPaymentField_payment_instrument' => ts('Payment Method'),
'componentPaymentField_transaction_id' => ts('Transaction ID'),
- );
+ ];
}
return $componentPaymentFields;
}
- /**
- * Set the definition for the header rows and sql columns based on the field to output.
- *
- * @param string $field
- * @param array $headerRows
- * @param array $sqlColumns
- * Columns to go in the temp table.
- * @param CRM_Contact_BAO_Query $query
- * @param array|string $value
- * @param array $phoneTypes
- * @param array $imProviders
- * @param array $contactRelationshipTypes
- * @param string $relationQuery
- * @param array $selectedPaymentFields
- * @return array
- */
- public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
-
- // Split campaign into 2 fields for id and title
- if (substr($field, -14) == 'campaign_title') {
- $headerRows[] = ts('Campaign Title');
- }
- elseif (substr($field, -11) == 'campaign_id') {
- $headerRows[] = ts('Campaign ID');
- }
- elseif (isset($query->_fields[$field]['title'])) {
- $headerRows[] = $query->_fields[$field]['title'];
- }
- elseif ($field == 'phone_type_id') {
- $headerRows[] = ts('Phone Type');
- }
- elseif ($field == 'provider_id') {
- $headerRows[] = ts('IM Service Provider');
- }
- elseif (substr($field, 0, 5) == 'case_') {
- if ($query->_fields['case'][$field]['title']) {
- $headerRows[] = $query->_fields['case'][$field]['title'];
- }
- elseif ($query->_fields['activity'][$field]['title']) {
- $headerRows[] = $query->_fields['activity'][$field]['title'];
- }
- }
- elseif (array_key_exists($field, $contactRelationshipTypes)) {
- foreach ($value as $relationField => $relationValue) {
- // below block is same as primary block (duplicate)
- if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
- if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
- $headerName = $field . '-' . $relationField;
- }
- else {
- if ($relationField == 'current_employer') {
- $headerName = $field . '-' . 'current_employer';
- }
- else {
- $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
- }
- }
-
- $headerRows[] = $headerName;
-
- self::sqlColumnDefn($query, $sqlColumns, $headerName);
- }
- elseif ($relationField == 'phone_type_id') {
- $headerName = $field . '-' . 'Phone Type';
- $headerRows[] = $headerName;
- self::sqlColumnDefn($query, $sqlColumns, $headerName);
- }
- elseif ($relationField == 'provider_id') {
- $headerName = $field . '-' . 'Im Service Provider';
- $headerRows[] = $headerName;
- self::sqlColumnDefn($query, $sqlColumns, $headerName);
- }
- elseif ($relationField == 'state_province_id') {
- $headerName = $field . '-' . 'state_province_id';
- $headerRows[] = $headerName;
- self::sqlColumnDefn($query, $sqlColumns, $headerName);
- }
- elseif (is_array($relationValue) && $relationField == 'location') {
- // fix header for location type case
- foreach ($relationValue as $ltype => $val) {
- foreach (array_keys($val) as $fld) {
- $type = explode('-', $fld);
-
- $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
-
- if (!empty($type[1])) {
- if (CRM_Utils_Array::value(0, $type) == 'phone') {
- $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
- }
- elseif (CRM_Utils_Array::value(0, $type) == 'im') {
- $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
- }
- }
- $headerName = $field . '-' . $hdr;
- $headerRows[] = $headerName;
- self::sqlColumnDefn($query, $sqlColumns, $headerName);
- }
- }
- }
- }
- self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
- }
- elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
- $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
- }
- else {
- $headerRows[] = $field;
- }
-
- self::sqlColumnDefn($query, $sqlColumns, $field);
-
- return array($headerRows, $sqlColumns);
- }
-
/**
* Get the various arrays that we use to structure our output.
*
@@ -2114,12 +1042,8 @@ public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $
* as a step on the refactoring path rather than how it should be.
*
* @param array $returnProperties
- * @param CRM_Contact_BAO_Contact $query
- * @param array $phoneTypes
- * @param array $imProviders
- * @param array $contactRelationshipTypes
- * @param string $relationQuery
- * @param array $selectedPaymentFields
+ * @param \CRM_Export_BAO_ExportProcessor $processor
+ *
* @return array
* - outputColumns Array of columns to be exported. The values don't matter but the key must match the
* alias for the field generated by BAO_Query object.
@@ -2136,13 +1060,31 @@ public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $
* - b) this code is old & outdated. Submit your answers to circular bin or better
* yet find a way to comment them for posterity.
*/
- public static function getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
- $metadata = $headerRows = $outputColumns = $sqlColumns = array();
-
+ public static function getExportStructureArrays($returnProperties, $processor) {
+ $outputColumns = $metadata = [];
+ $queryFields = $processor->getQueryFields();
foreach ($returnProperties as $key => $value) {
- if ($key != 'location' || !is_array($value)) {
+ if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
+ $outputColumns[$key] = $value;
+ $processor->addOutputSpecification($key);
+ }
+ elseif ($processor->isRelationshipTypeKey($key)) {
$outputColumns[$key] = $value;
- list($headerRows, $sqlColumns) = self::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
+ foreach ($value as $relationField => $relationValue) {
+ // below block is same as primary block (duplicate)
+ if (isset($queryFields[$relationField]['title'])) {
+ $processor->addOutputSpecification($relationField, $key);
+ }
+ elseif (is_array($relationValue) && $relationField == 'location') {
+ // fix header for location type case
+ foreach ($relationValue as $ltype => $val) {
+ foreach (array_keys($val) as $fld) {
+ $type = explode('-', $fld);
+ $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
+ }
+ }
+ }
+ }
}
else {
foreach ($value as $locationType => $locationFields) {
@@ -2150,36 +1092,250 @@ public static function getExportStructureArrays($returnProperties, $query, $phon
$type = explode('-', $locationFieldName);
$actualDBFieldName = $type[0];
- $outputFieldName = $locationType . '-' . $query->_fields[$actualDBFieldName]['title'];
$daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
if (!empty($type[1])) {
$daoFieldName .= "-" . $type[1];
- if ($actualDBFieldName == 'phone') {
- $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
- }
- elseif ($actualDBFieldName == 'im') {
- $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
- }
}
- if ($type[0] == 'im_provider') {
- // Warning: shame inducing hack.
- $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
+ $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
+ $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
+ $outputColumns[$daoFieldName] = TRUE;
+ }
+ }
+ }
+ }
+ return [$outputColumns, $metadata];
+ }
+
+ /**
+ * Get the values of linked household contact.
+ *
+ * @param CRM_Core_DAO $relDAO
+ * @param array $value
+ * @param string $field
+ * @param array $row
+ */
+ private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
+ $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
+ $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
+ $i18n = CRM_Core_I18n::singleton();
+ $field = $field . '_';
+
+ foreach ($value as $relationField => $relationValue) {
+ if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
+ $fieldValue = $relDAO->$relationField;
+ if ($relationField == 'phone_type_id') {
+ $fieldValue = $phoneTypes[$relationValue];
+ }
+ elseif ($relationField == 'provider_id') {
+ $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
+ }
+ // CRM-13995
+ elseif (is_object($relDAO) && in_array($relationField, [
+ 'email_greeting',
+ 'postal_greeting',
+ 'addressee',
+ ])) {
+ //special case for greeting replacement
+ $fldValue = "{$relationField}_display";
+ $fieldValue = $relDAO->$fldValue;
+ }
+ }
+ elseif (is_object($relDAO) && $relationField == 'state_province') {
+ $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
+ }
+ elseif (is_object($relDAO) && $relationField == 'country') {
+ $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
+ }
+ else {
+ $fieldValue = '';
+ }
+ $relPrefix = $field . $relationField;
+
+ if (is_object($relDAO) && $relationField == 'id') {
+ $row[$relPrefix] = $relDAO->contact_id;
+ }
+ elseif (is_array($relationValue) && $relationField == 'location') {
+ foreach ($relationValue as $ltype => $val) {
+ // If the location name has a space in it the we need to handle that. This
+ // is kinda hacky but specifically covered in the ExportTest so later efforts to
+ // improve it should be secure in the knowled it will be caught.
+ $ltype = str_replace(' ', '_', $ltype);
+ foreach (array_keys($val) as $fld) {
+ $type = explode('-', $fld);
+ $fldValue = "{$ltype}-" . $type[0];
+ if (!empty($type[1])) {
+ $fldValue .= "-" . $type[1];
}
- self::sqlColumnDefn($query, $sqlColumns, $outputFieldName);
- list($headerRows, $sqlColumns) = self::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
- if ($actualDBFieldName == 'country' || $actualDBFieldName == 'world_region') {
- $metadata[$daoFieldName] = array('context' => 'country');
+ // CRM-3157: localise country, region (both have ‘country’ context)
+ // and state_province (‘province’ context)
+ switch (TRUE) {
+ case (!is_object($relDAO)):
+ $row[$field . '_' . $fldValue] = '';
+ break;
+
+ case in_array('country', $type):
+ case in_array('world_region', $type):
+ $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
+ ['context' => 'country']
+ );
+ break;
+
+ case in_array('state_province', $type):
+ $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
+ ['context' => 'province']
+ );
+ break;
+
+ default:
+ $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
+ break;
}
- if ($actualDBFieldName == 'state_province') {
- $metadata[$daoFieldName] = array('context' => 'province');
+ }
+ }
+ }
+ elseif (isset($fieldValue) && $fieldValue != '') {
+ //check for custom data
+ if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
+ $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
+ }
+ else {
+ //normal relationship fields
+ // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
+ switch ($relationField) {
+ case 'country':
+ case 'world_region':
+ $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
+ break;
+
+ case 'state_province':
+ $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
+ break;
+
+ default:
+ $row[$relPrefix] = $fieldValue;
+ break;
+ }
+ }
+ }
+ else {
+ // if relation field is empty or null
+ $row[$relPrefix] = '';
+ }
+ }
+ }
+
+ /**
+ * Get the ids that we want to get related contact details for.
+ *
+ * @param array $ids
+ * @param int $exportMode
+ *
+ * @return array
+ */
+ protected static function getIDsForRelatedContact($ids, $exportMode) {
+ if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
+ return $ids;
+ }
+ if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
+ $relIDs = [];
+ $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
+ $dao = CRM_Core_DAO::executeQuery("
+ SELECT contact_id FROM civicrm_activity_contact
+ WHERE activity_id IN ( " . implode(',', $ids) . ") AND
+ record_type_id = {$sourceID}
+ ");
+
+ while ($dao->fetch()) {
+ $relIDs[] = $dao->contact_id;
+ }
+ return $relIDs;
+ }
+ $component = self::exportComponent($exportMode);
+
+ if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
+ return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
+ }
+ else {
+ return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
+ }
+ }
+
+ /**
+ * @param $selectAll
+ * @param $ids
+ * @param \CRM_Export_BAO_ExportProcessor $processor
+ * @param $componentTable
+ */
+ protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
+ $allRelContactArray = $relationQuery = [];
+ $queryMode = $processor->getQueryMode();
+ $exportMode = $processor->getExportMode();
+
+ foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
+ $allRelContactArray[$relationshipKey] = [];
+ // build Query for each relationship
+ $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
+ NULL, FALSE, FALSE, $queryMode
+ );
+ list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
+
+ list($id, $direction) = explode('_', $relationshipKey, 2);
+ // identify the relationship direction
+ $contactA = 'contact_id_a';
+ $contactB = 'contact_id_b';
+ if ($direction == 'b_a') {
+ $contactA = 'contact_id_b';
+ $contactB = 'contact_id_a';
+ }
+ $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
+
+ $relationshipJoin = $relationshipClause = '';
+ if (!$selectAll && $componentTable) {
+ $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
+ }
+ elseif (!empty($relIDs)) {
+ $relID = implode(',', $relIDs);
+ $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
+ }
+
+ $relationFrom = " {$relationFrom}
+ INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
+ {$relationshipJoin} ";
+
+ //check for active relationship status only
+ $today = date('Ymd');
+ $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
+ $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
+ CRM_Core_DAO::disableFullGroupByMode();
+ $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
+ $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
+
+ $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
+ CRM_Core_DAO::reenableFullGroupByMode();
+
+ while ($allRelContactDAO->fetch()) {
+ $relationQuery->convertToPseudoNames($allRelContactDAO);
+ $row = [];
+ // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
+ self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
+ foreach (array_keys($relationReturnProperties) as $property) {
+ if ($property === 'location') {
+ // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
+ // $processor->setRelationshipValue from fetchRelationshipDetails
+ foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
+ foreach (array_keys($locationValues) as $locationValue) {
+ $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
+ $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
+ }
}
- $outputColumns[$daoFieldName] = TRUE;
+ }
+ else {
+ $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
}
}
}
}
- return array($outputColumns, $headerRows, $sqlColumns, $metadata);
}
}
diff --git a/CRM/Export/BAO/ExportProcessor.php b/CRM/Export/BAO/ExportProcessor.php
new file mode 100644
index 000000000000..2e8513c831a8
--- /dev/null
+++ b/CRM/Export/BAO/ExportProcessor.php
@@ -0,0 +1,1359 @@
+ 'Household Member Is', '8_a_b = 'Household Member Of'.....]
+ *
+ * @var array
+ */
+ protected $relationshipTypes = [];
+
+ /**
+ * Array of properties to retrieve for relationships.
+ *
+ * @var array
+ */
+ protected $relationshipReturnProperties = [];
+
+ /**
+ * IDs of households that have already been exported.
+ *
+ * @var array
+ */
+ protected $exportedHouseholds = [];
+
+ /**
+ * Get return properties by relationship.
+ * @return array
+ */
+ public function getRelationshipReturnProperties() {
+ return $this->relationshipReturnProperties;
+ }
+
+ /**
+ * Export values for related contacts.
+ *
+ * @var array
+ */
+ protected $relatedContactValues = [];
+
+ /**
+ * @var array
+ */
+ protected $returnProperties = [];
+
+ /**
+ * @var array
+ */
+ protected $outputSpecification = [];
+
+ /**
+ * CRM_Export_BAO_ExportProcessor constructor.
+ *
+ * @param int $exportMode
+ * @param array|NULL $requestedFields
+ * @param string $queryOperator
+ * @param bool $isMergeSameHousehold
+ * @param bool $isPostalableOnly
+ */
+ public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE) {
+ $this->setExportMode($exportMode);
+ $this->setQueryMode();
+ $this->setQueryOperator($queryOperator);
+ $this->setRequestedFields($requestedFields);
+ $this->setRelationshipTypes();
+ $this->setIsMergeSameHousehold($isMergeSameHousehold);
+ $this->setisPostalableOnly($isPostalableOnly);
+ }
+
+ /**
+ * @return bool
+ */
+ public function isPostalableOnly() {
+ return $this->isPostalableOnly;
+ }
+
+ /**
+ * @param bool $isPostalableOnly
+ */
+ public function setIsPostalableOnly($isPostalableOnly) {
+ $this->isPostalableOnly = $isPostalableOnly;
+ }
+
+ /**
+ * @return array|null
+ */
+ public function getRequestedFields() {
+ return $this->requestedFields;
+ }
+
+ /**
+ * @param array|null $requestedFields
+ */
+ public function setRequestedFields($requestedFields) {
+ $this->requestedFields = $requestedFields;
+ }
+
+ /**
+ * @return array
+ */
+ public function getReturnProperties() {
+ return $this->returnProperties;
+ }
+
+ /**
+ * @param array $returnProperties
+ */
+ public function setReturnProperties($returnProperties) {
+ $this->returnProperties = $returnProperties;
+ }
+
+ /**
+ * @return array
+ */
+ public function getRelationshipTypes() {
+ return $this->relationshipTypes;
+ }
+
+ /**
+ */
+ public function setRelationshipTypes() {
+ $this->relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ TRUE,
+ 'name',
+ FALSE
+ );
+ }
+
+ /**
+ * Set the value for a relationship type field.
+ *
+ * In this case we are building up an array of properties for a related contact.
+ *
+ * These may be used for direct exporting or for merge to household depending on the
+ * options selected.
+ *
+ * @param string $relationshipType
+ * @param int $contactID
+ * @param string $field
+ * @param string $value
+ */
+ public function setRelationshipValue($relationshipType, $contactID, $field, $value) {
+ $this->relatedContactValues[$relationshipType][$contactID][$field] = $value;
+ }
+
+ /**
+ * Get the value for a relationship type field.
+ *
+ * In this case we are building up an array of properties for a related contact.
+ *
+ * These may be used for direct exporting or for merge to household depending on the
+ * options selected.
+ *
+ * @param string $relationshipType
+ * @param int $contactID
+ * @param string $field
+ *
+ * @return string
+ */
+ public function getRelationshipValue($relationshipType, $contactID, $field) {
+ return isset($this->relatedContactValues[$relationshipType][$contactID][$field]) ? $this->relatedContactValues[$relationshipType][$contactID][$field] : '';
+ }
+
+ /**
+ * Get the id of the related household.
+ *
+ * @param int $contactID
+ * @param string $relationshipType
+ *
+ * @return int
+ */
+ public function getRelatedHouseholdID($contactID, $relationshipType) {
+ return $this->relatedContactValues[$relationshipType][$contactID]['id'];
+ }
+
+ /**
+ * Has the household already been exported.
+ *
+ * @param int $housholdContactID
+ *
+ * @return bool
+ */
+ public function isHouseholdExported($housholdContactID) {
+ return isset($this->exportedHouseholds[$housholdContactID]);
+
+ }
+
+ /**
+ * @return bool
+ */
+ public function isMergeSameHousehold() {
+ return $this->isMergeSameHousehold;
+ }
+
+ /**
+ * @param bool $isMergeSameHousehold
+ */
+ public function setIsMergeSameHousehold($isMergeSameHousehold) {
+ $this->isMergeSameHousehold = $isMergeSameHousehold;
+ }
+
+ /**
+ * Return relationship types for household merge.
+ *
+ * @return mixed
+ */
+ public function getHouseholdRelationshipTypes() {
+ if (!$this->isMergeSameHousehold()) {
+ return [];
+ }
+ return [
+ CRM_Utils_Array::key('Household Member of', $this->getRelationshipTypes()),
+ CRM_Utils_Array::key('Head of Household for', $this->getRelationshipTypes()),
+ ];
+ }
+
+ /**
+ * @param $fieldName
+ * @return bool
+ */
+ public function isRelationshipTypeKey($fieldName) {
+ return array_key_exists($fieldName, $this->relationshipTypes);
+ }
+
+ /**
+ * @param $fieldName
+ * @return bool
+ */
+ public function isHouseholdMergeRelationshipTypeKey($fieldName) {
+ return in_array($fieldName, $this->getHouseholdRelationshipTypes());
+ }
+
+ /**
+ * @return string
+ */
+ public function getQueryOperator() {
+ return $this->queryOperator;
+ }
+
+ /**
+ * @param string $queryOperator
+ */
+ public function setQueryOperator($queryOperator) {
+ $this->queryOperator = $queryOperator;
+ }
+
+ /**
+ * @return array
+ */
+ public function getQueryFields() {
+ return $this->queryFields;
+ }
+
+ /**
+ * @param array $queryFields
+ */
+ public function setQueryFields($queryFields) {
+ // legacy hacks - we add these to queryFields because this
+ // pseudometadata is currently required.
+ $queryFields['im_provider']['pseudoconstant']['var'] = 'imProviders';
+ $queryFields['country']['context'] = 'country';
+ $queryFields['world_region']['context'] = 'country';
+ $queryFields['state_province']['context'] = 'province';
+ $this->queryFields = $queryFields;
+ }
+
+ /**
+ * @return int
+ */
+ public function getQueryMode() {
+ return $this->queryMode;
+ }
+
+ /**
+ * Set the query mode based on the export mode.
+ */
+ public function setQueryMode() {
+
+ switch ($this->getExportMode()) {
+ case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
+ break;
+
+ case CRM_Export_Form_Select::EVENT_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
+ break;
+
+ case CRM_Export_Form_Select::MEMBER_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
+ break;
+
+ case CRM_Export_Form_Select::PLEDGE_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
+ break;
+
+ case CRM_Export_Form_Select::CASE_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_CASE;
+ break;
+
+ case CRM_Export_Form_Select::GRANT_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
+ break;
+
+ case CRM_Export_Form_Select::ACTIVITY_EXPORT:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
+ break;
+
+ default:
+ $this->queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
+ }
+ }
+
+ /**
+ * @return int
+ */
+ public function getExportMode() {
+ return $this->exportMode;
+ }
+
+ /**
+ * @param int $exportMode
+ */
+ public function setExportMode($exportMode) {
+ $this->exportMode = $exportMode;
+ }
+
+ /**
+ * Get the name for the export file.
+ *
+ * @return string
+ */
+ public function getExportFileName() {
+ switch ($this->getExportMode()) {
+ case CRM_Export_Form_Select::CONTACT_EXPORT:
+ return ts('CiviCRM Contact Search');
+
+ case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
+ return ts('CiviCRM Contribution Search');
+
+ case CRM_Export_Form_Select::MEMBER_EXPORT:
+ return ts('CiviCRM Member Search');
+
+ case CRM_Export_Form_Select::EVENT_EXPORT:
+ return ts('CiviCRM Participant Search');
+
+ case CRM_Export_Form_Select::PLEDGE_EXPORT:
+ return ts('CiviCRM Pledge Search');
+
+ case CRM_Export_Form_Select::CASE_EXPORT:
+ return ts('CiviCRM Case Search');
+
+ case CRM_Export_Form_Select::GRANT_EXPORT:
+ return ts('CiviCRM Grant Search');
+
+ case CRM_Export_Form_Select::ACTIVITY_EXPORT:
+ return ts('CiviCRM Activity Search');
+
+ default:
+ // Legacy code suggests the value could be 'financial' - ie. something
+ // other than what should be accepted. However, I suspect that this line is
+ // never hit.
+ return ts('CiviCRM Search');
+ }
+ }
+
+ /**
+ * Get the label for the header row based on the field to output.
+ *
+ * @param string $field
+ *
+ * @return string
+ */
+ public function getHeaderForRow($field) {
+ if (substr($field, -11) == 'campaign_id') {
+ // @todo - set this correctly in the xml rather than here.
+ // This will require a generalised handling cleanup
+ return ts('Campaign ID');
+ }
+ if ($this->isMergeSameHousehold() && $field === 'id') {
+ return ts('Household ID');
+ }
+ elseif (isset($this->getQueryFields()[$field]['title'])) {
+ return $this->getQueryFields()[$field]['title'];
+ }
+ elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
+ return CRM_Utils_Array::value($field, $this->getcomponentPaymentFields());
+ }
+ else {
+ return $field;
+ }
+ }
+
+ /**
+ * @param $params
+ * @param $order
+ * @param $returnProperties
+ * @return array
+ */
+ public function runQuery($params, $order, $returnProperties) {
+ $addressWhere = '';
+ $params = array_merge($params, $this->getWhereParams());
+ if ($this->isPostalableOnly) {
+ if (array_key_exists('street_address', $returnProperties)) {
+ $addressWhere = " civicrm_address.street_address <> ''";
+ if (array_key_exists('supplemental_address_1', $returnProperties)) {
+ // We need this to be an OR rather than AND on the street_address so, hack it in.
+ $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+ 'address_options', TRUE, NULL, TRUE
+ );
+ if (!empty($addressOptions['supplemental_address_1'])) {
+ $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
+ }
+ }
+ $addressWhere = ' AND (' . $addressWhere . ')';
+ }
+ }
+ $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
+ FALSE, FALSE, $this->getQueryMode(),
+ FALSE, TRUE, TRUE, NULL, $this->getQueryOperator()
+ );
+
+ //sort by state
+ //CRM-15301
+ $query->_sort = $order;
+ list($select, $from, $where, $having) = $query->query();
+ $this->setQueryFields($query->_fields);
+ return [$query, $select, $from, $where . $addressWhere, $having];
+ }
+
+ /**
+ * Add a row to the specification for how to output data.
+ *
+ * @param string $key
+ * @param string $relationshipType
+ * @param string $locationType
+ * @param int $entityTypeID phone_type_id or provider_id for phone or im fields.
+ */
+ public function addOutputSpecification($key, $relationshipType = NULL, $locationType = NULL, $entityTypeID = NULL) {
+ $entityLabel = '';
+ if ($entityTypeID) {
+ if ($key === 'phone') {
+ $entityLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $entityTypeID);
+ }
+ if ($key === 'im') {
+ $entityLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_IM', 'provider_id', $entityTypeID);
+ }
+ }
+
+ // These oddly constructed keys are for legacy reasons. Altering them will affect test success
+ // but in time it may be good to rationalise them.
+ $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
+ $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel);
+ $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel);
+
+ $this->outputSpecification[$index]['header'] = $label;
+ $this->outputSpecification[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
+
+ if ($relationshipType && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
+ $this->setColumnAsCalculationOnly($index);
+ }
+ $this->outputSpecification[$index]['metadata'] = $this->getMetaDataForField($key);
+ }
+
+ /**
+ * Get the metadata for the given field.
+ *
+ * @param $key
+ *
+ * @return array
+ */
+ public function getMetaDataForField($key) {
+ $mappings = ['contact_id' => 'id'];
+ if (isset($this->getQueryFields()[$key])) {
+ return $this->getQueryFields()[$key];
+ }
+ if (isset($mappings[$key])) {
+ return $this->getQueryFields()[$mappings[$key]];
+ }
+ return [];
+ }
+
+ /**
+ * @param $key
+ */
+ public function setSqlColumnDefn($key) {
+ $this->outputSpecification[$this->getMungedFieldName($key)]['sql_columns'] = $this->getSqlColumnDefinition($key, $this->getMungedFieldName($key));
+ }
+
+ /**
+ * Mark a column as only required for calculations.
+ *
+ * Do not include the row with headers.
+ *
+ * @param string $column
+ */
+ public function setColumnAsCalculationOnly($column) {
+ $this->outputSpecification[$column]['do_not_output_to_csv'] = TRUE;
+ }
+
+ /**
+ * @return array
+ */
+ public function getHeaderRows() {
+ $headerRows = [];
+ foreach ($this->outputSpecification as $key => $spec) {
+ if (empty($spec['do_not_output_to_csv'])) {
+ $headerRows[] = $spec['header'];
+ }
+ }
+ return $headerRows;
+ }
+
+ /**
+ * @return array
+ */
+ public function getSQLColumns() {
+ $sqlColumns = [];
+ foreach ($this->outputSpecification as $key => $spec) {
+ if (empty($spec['do_not_output_to_sql'])) {
+ $sqlColumns[$key] = $spec['sql_columns'];
+ }
+ }
+ return $sqlColumns;
+ }
+
+ /**
+ * @return array
+ */
+ public function getMetadata() {
+ $metadata = [];
+ foreach ($this->outputSpecification as $key => $spec) {
+ $metadata[$key] = $spec['metadata'];
+ }
+ return $metadata;
+ }
+
+ /**
+ * Build the row for output.
+ *
+ * @param \CRM_Contact_BAO_Query $query
+ * @param CRM_Core_DAO $iterationDAO
+ * @param array $outputColumns
+ * @param $metadata
+ * @param $paymentDetails
+ * @param $addPaymentHeader
+ * @param $paymentTableId
+ *
+ * @return array|bool
+ */
+ public function buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId) {
+ $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
+ $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
+
+ $row = [];
+ $householdMergeRelationshipType = $this->getHouseholdMergeTypeForRow($iterationDAO->contact_id);
+ if ($householdMergeRelationshipType) {
+ $householdID = $this->getRelatedHouseholdID($iterationDAO->contact_id, $householdMergeRelationshipType);
+ if ($this->isHouseholdExported($householdID)) {
+ return FALSE;
+ }
+ foreach (array_keys($outputColumns) as $column) {
+ $row[$column] = $this->getRelationshipValue($householdMergeRelationshipType, $iterationDAO->contact_id, $column);
+ }
+ $this->markHouseholdExported($householdID);
+ return $row;
+ }
+
+ $query->convertToPseudoNames($iterationDAO);
+
+ //first loop through output columns so that we return what is required, and in same order.
+ foreach ($outputColumns as $field => $value) {
+ // add im_provider to $dao object
+ if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
+ $iterationDAO->im_provider = $iterationDAO->provider_id;
+ }
+
+ //build row values (data)
+ $fieldValue = NULL;
+ if (property_exists($iterationDAO, $field)) {
+ $fieldValue = $iterationDAO->$field;
+ // to get phone type from phone type id
+ if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
+ $fieldValue = $phoneTypes[$fieldValue];
+ }
+ elseif ($field == 'provider_id' || $field == 'im_provider') {
+ $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
+ }
+ elseif (strstr($field, 'master_id')) {
+ $masterAddressId = NULL;
+ if (isset($iterationDAO->$field)) {
+ $masterAddressId = $iterationDAO->$field;
+ }
+ // get display name of contact that address is shared.
+ $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId);
+ }
+ }
+
+ if ($this->isRelationshipTypeKey($field)) {
+ $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id, $value, $field);
+ }
+ else {
+ $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails);
+ }
+ }
+
+ // If specific payment fields have been selected for export, payment
+ // data will already be in $row. Otherwise, add payment related
+ // information, if appropriate.
+ if ($addPaymentHeader) {
+ if (!$this->isExportSpecifiedPaymentFields()) {
+ $nullContributionDetails = array_fill_keys(array_keys($this->getPaymentHeaders()), NULL);
+ if ($this->isExportPaymentFields()) {
+ $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
+ if (!is_array($paymentData) || empty($paymentData)) {
+ $paymentData = $nullContributionDetails;
+ }
+ $row = array_merge($row, $paymentData);
+ }
+ elseif (!empty($paymentDetails)) {
+ $row = array_merge($row, $nullContributionDetails);
+ }
+ }
+ }
+ //remove organization name for individuals if it is set for current employer
+ if (!empty($row['contact_type']) &&
+ $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
+ ) {
+ $row['organization_name'] = '';
+ }
+ return $row;
+ }
+
+ /**
+ * If this row has a household whose details we should use get the relationship type key.
+ *
+ * @param $contactID
+ *
+ * @return bool
+ */
+ public function getHouseholdMergeTypeForRow($contactID) {
+ if (!$this->isMergeSameHousehold()) {
+ return FALSE;
+ }
+ foreach ($this->getHouseholdRelationshipTypes() as $relationshipType) {
+ if (isset($this->relatedContactValues[$relationshipType][$contactID])) {
+ return $relationshipType;
+ }
+ }
+ }
+
+ /**
+ * Mark the given household as already exported.
+ *
+ * @param $householdID
+ */
+ public function markHouseholdExported($householdID) {
+ $this->exportedHouseholds[$householdID] = $householdID;
+ }
+
+ /**
+ * @param $field
+ * @param $iterationDAO
+ * @param $fieldValue
+ * @param $metadata
+ * @param $paymentDetails
+ *
+ * @return string
+ */
+ public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails) {
+
+ $i18n = CRM_Core_I18n::singleton();
+ if ($field == 'id') {
+ return $iterationDAO->contact_id;
+ // special case for calculated field
+ }
+ elseif ($field == 'source_contact_id') {
+ return $iterationDAO->contact_id;
+ }
+ elseif ($field == 'pledge_balance_amount') {
+ return $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
+ // special case for calculated field
+ }
+ elseif ($field == 'pledge_next_pay_amount') {
+ return $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
+ }
+ elseif (isset($fieldValue) &&
+ $fieldValue != ''
+ ) {
+ //check for custom data
+ if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
+ return CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
+ }
+
+ elseif (in_array($field, [
+ 'email_greeting',
+ 'postal_greeting',
+ 'addressee',
+ ])) {
+ //special case for greeting replacement
+ $fldValue = "{$field}_display";
+ return $iterationDAO->$fldValue;
+ }
+ else {
+ //normal fields with a touch of CRM-3157
+ switch ($field) {
+ case 'country':
+ case 'world_region':
+ return $i18n->crm_translate($fieldValue, ['context' => 'country']);
+
+ case 'state_province':
+ return $i18n->crm_translate($fieldValue, ['context' => 'province']);
+
+ case 'gender':
+ case 'preferred_communication_method':
+ case 'preferred_mail_format':
+ case 'communication_style':
+ return $i18n->crm_translate($fieldValue);
+
+ default:
+ if (isset($metadata[$field])) {
+ // No I don't know why we do it this way & whether we could
+ // make better use of pseudoConstants.
+ if (!empty($metadata[$field]['context'])) {
+ return $i18n->crm_translate($fieldValue, $metadata[$field]);
+ }
+ if (!empty($metadata[$field]['pseudoconstant'])) {
+ if (!empty($metadata[$field]['bao'])) {
+ return CRM_Core_PseudoConstant::getLabel($metadata[$field]['bao'], $metadata[$field]['name'], $fieldValue);
+ }
+ // This is not our normal syntax for pseudoconstants but I am a bit loath to
+ // call an external function until sure it is not increasing php processing given this
+ // may be iterated 100,000 times & we already have the $imProvider var loaded.
+ // That can be next refactor...
+ // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
+ // but I have to reach a stable point....
+ $varName = $metadata[$field]['pseudoconstant']['var'];
+ if ($varName === 'imProviders') {
+ return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
+ }
+ if ($varName === 'phoneTypes') {
+ return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
+ }
+ }
+
+ }
+ return $fieldValue;
+ }
+ }
+ }
+ elseif ($this->isExportSpecifiedPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
+ $paymentTableId = $this->getPaymentTableID();
+ $paymentData = CRM_Utils_Array::value($iterationDAO->$paymentTableId, $paymentDetails);
+ $payFieldMapper = [
+ 'componentPaymentField_total_amount' => 'total_amount',
+ 'componentPaymentField_contribution_status' => 'contribution_status',
+ 'componentPaymentField_payment_instrument' => 'pay_instru',
+ 'componentPaymentField_transaction_id' => 'trxn_id',
+ 'componentPaymentField_received_date' => 'receive_date',
+ ];
+ return CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
+ }
+ else {
+ // if field is empty or null
+ return '';
+ }
+ }
+
+ /**
+ * Get array of fields to return, over & above those defined in the main contact exportable fields.
+ *
+ * These include export mode specific fields & some fields apparently required as 'exportableFields'
+ * but not returned by the function of the same name.
+ *
+ * @return array
+ * Array of fields to return in the format ['field_name' => 1,...]
+ */
+ public function getAdditionalReturnProperties() {
+ if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTACTS) {
+ $componentSpecificFields = [];
+ }
+ else {
+ $componentSpecificFields = CRM_Contact_BAO_Query::defaultReturnProperties($this->getQueryMode());
+ }
+ if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_PLEDGE) {
+ $componentSpecificFields = array_merge($componentSpecificFields, CRM_Pledge_BAO_Query::extraReturnProperties($this->getQueryMode()));
+ unset($componentSpecificFields['contribution_status_id']);
+ unset($componentSpecificFields['pledge_status_id']);
+ unset($componentSpecificFields['pledge_payment_status_id']);
+ }
+ if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CASE) {
+ $componentSpecificFields = array_merge($componentSpecificFields, CRM_Case_BAO_Query::extraReturnProperties($this->getQueryMode()));
+ }
+ if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
+ $componentSpecificFields = array_merge($componentSpecificFields, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
+ unset($componentSpecificFields['contribution_status_id']);
+ }
+ return $componentSpecificFields;
+ }
+
+ /**
+ * Should payment fields be appended to the export.
+ *
+ * (This is pretty hacky so hopefully this function won't last long - notice
+ * how obviously it should be part of the above function!).
+ */
+ public function isExportPaymentFields() {
+ if ($this->getRequestedFields() === NULL
+ && in_array($this->getQueryMode(), [
+ CRM_Contact_BAO_Query::MODE_EVENT,
+ CRM_Contact_BAO_Query::MODE_MEMBER,
+ CRM_Contact_BAO_Query::MODE_PLEDGE,
+ ])) {
+ return TRUE;
+ }
+ elseif ($this->isExportSpecifiedPaymentFields()) {
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Has specific payment fields been requested (as opposed to via all fields).
+ *
+ * If specific fields have been requested then they get added at various points.
+ *
+ * @return bool
+ */
+ public function isExportSpecifiedPaymentFields() {
+ if ($this->getRequestedFields() !== NULL && $this->hasRequestedComponentPaymentFields()) {
+ return TRUE;
+ }
+ }
+
+ /**
+ * Get the name of the id field in the table that connects contributions to the export entity.
+ */
+ public function getPaymentTableID() {
+ if ($this->getRequestedFields() === NULL) {
+ $mapping = [
+ CRM_Contact_BAO_Query::MODE_EVENT => 'participant_id',
+ CRM_Contact_BAO_Query::MODE_MEMBER => 'membership_id',
+ CRM_Contact_BAO_Query::MODE_PLEDGE => 'pledge_payment_id',
+ ];
+ return isset($mapping[$this->getQueryMode()]) ? $mapping[$this->getQueryMode()] : '';
+ }
+ elseif ($this->hasRequestedComponentPaymentFields()) {
+ return 'participant_id';
+ }
+ return FALSE;
+ }
+
+ /**
+ * Have component payment fields been requested.
+ *
+ * @return bool
+ */
+ protected function hasRequestedComponentPaymentFields() {
+ if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_EVENT) {
+ $participantPaymentFields = array_intersect_key($this->getComponentPaymentFields(), $this->getReturnProperties());
+ if (!empty($participantPaymentFields)) {
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+
+ /**
+ * Get fields that indicate payment fields have been requested for a component.
+ *
+ * Ideally this should be protected but making it temporarily public helps refactoring..
+ *
+ * @return array
+ */
+ public function getComponentPaymentFields() {
+ return [
+ 'componentPaymentField_total_amount' => ts('Total Amount'),
+ 'componentPaymentField_contribution_status' => ts('Contribution Status'),
+ 'componentPaymentField_received_date' => ts('Date Received'),
+ 'componentPaymentField_payment_instrument' => ts('Payment Method'),
+ 'componentPaymentField_transaction_id' => ts('Transaction ID'),
+ ];
+ }
+
+ /**
+ * Get headers for payment fields.
+ *
+ * Returns an array of contribution fields when the entity supports payment fields and specific fields
+ * are not specified. This is a transitional function for refactoring legacy code.
+ */
+ public function getPaymentHeaders() {
+ if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
+ return $this->getcomponentPaymentFields();
+ }
+ return [];
+ }
+
+ /**
+ * Get the default properties when not specified.
+ *
+ * In the UI this appears as 'Primary fields only' but in practice it's
+ * most of the kitchen sink and the hallway closet thrown in.
+ *
+ * Since CRM-952 custom fields are excluded, but no other form of mercy is shown.
+ *
+ * @return array
+ */
+ public function getDefaultReturnProperties() {
+ $returnProperties = [];
+ $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
+ $skippedFields = ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTACTS) ? [] : [
+ 'groups',
+ 'tags',
+ 'notes',
+ ];
+
+ foreach ($fields as $key => $var) {
+ if ($key && (substr($key, 0, 6) != 'custom') && !in_array($key, $skippedFields)) {
+ $returnProperties[$key] = 1;
+ }
+ }
+ $returnProperties = array_merge($returnProperties, $this->getAdditionalReturnProperties());
+ return $returnProperties;
+ }
+
+ /**
+ * Add the field to relationship return properties & return it.
+ *
+ * This function is doing both setting & getting which is yuck but it is an interim
+ * refactor.
+ *
+ * @param array $value
+ * @param string $relationshipKey
+ *
+ * @return array
+ */
+ public function setRelationshipReturnProperties($value, $relationshipKey) {
+ $relPhoneTypeId = $relIMProviderId = NULL;
+ if (!empty($value[2])) {
+ $relationField = CRM_Utils_Array::value(2, $value);
+ if (trim(CRM_Utils_Array::value(3, $value))) {
+ $relLocTypeId = CRM_Utils_Array::value(3, $value);
+ }
+ else {
+ $relLocTypeId = 'Primary';
+ }
+
+ if ($relationField == 'phone') {
+ $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
+ }
+ elseif ($relationField == 'im') {
+ $relIMProviderId = CRM_Utils_Array::value(4, $value);
+ }
+ }
+ elseif (!empty($value[4])) {
+ $relationField = CRM_Utils_Array::value(4, $value);
+ $relLocTypeId = CRM_Utils_Array::value(5, $value);
+ if ($relationField == 'phone') {
+ $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
+ }
+ elseif ($relationField == 'im') {
+ $relIMProviderId = CRM_Utils_Array::value(6, $value);
+ }
+ }
+ if (in_array($relationField, $this->getValidLocationFields()) && is_numeric($relLocTypeId)) {
+ $locationName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_Address', 'location_type_id', $relLocTypeId);
+ if ($relPhoneTypeId) {
+ $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName]['phone-' . $relPhoneTypeId] = 1;
+ }
+ elseif ($relIMProviderId) {
+ $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName]['im-' . $relIMProviderId] = 1;
+ }
+ else {
+ $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName][$relationField] = 1;
+ }
+ }
+ else {
+ $this->relationshipReturnProperties[$relationshipKey][$relationField] = 1;
+ }
+ return $this->relationshipReturnProperties[$relationshipKey];
+ }
+
+ /**
+ * Add the main return properties to the household merge properties if needed for merging.
+ *
+ * If we are using household merge we need to add these to the relationship properties to
+ * be retrieved.
+ *
+ * @param $returnProperties
+ */
+ public function setHouseholdMergeReturnProperties($returnProperties) {
+ foreach ($this->getHouseholdRelationshipTypes() as $householdRelationshipType) {
+ $this->relationshipReturnProperties[$householdRelationshipType] = $returnProperties;
+ }
+ }
+
+ /**
+ * Get the default location fields to request.
+ *
+ * @return array
+ */
+ public function getValidLocationFields() {
+ return [
+ 'street_address',
+ 'supplemental_address_1',
+ 'supplemental_address_2',
+ 'supplemental_address_3',
+ 'city',
+ 'postal_code',
+ 'postal_code_suffix',
+ 'geo_code_1',
+ 'geo_code_2',
+ 'state_province',
+ 'country',
+ 'phone',
+ 'email',
+ 'im',
+ ];
+ }
+
+ /**
+ * Get the sql column definition for the given field.
+ *
+ * @param string $fieldName
+ * @param string $columnName
+ *
+ * @return mixed
+ */
+ public function getSqlColumnDefinition($fieldName, $columnName) {
+
+ // early exit for master_id, CRM-12100
+ // in the DB it is an ID, but in the export, we retrive the display_name of the master record
+ // also for current_employer, CRM-16939
+ if ($columnName == 'master_id' || $columnName == 'current_employer') {
+ return "$fieldName varchar(128)";
+ }
+
+ if (substr($fieldName, -11) == 'campaign_id') {
+ // CRM-14398
+ return "$fieldName varchar(128)";
+ }
+
+ $queryFields = $this->getQueryFields();
+ $lookUp = ['prefix_id', 'suffix_id'];
+ // set the sql columns
+ if (isset($queryFields[$columnName]['type'])) {
+ switch ($queryFields[$columnName]['type']) {
+ case CRM_Utils_Type::T_INT:
+ case CRM_Utils_Type::T_BOOLEAN:
+ if (in_array($columnName, $lookUp)) {
+ return "$fieldName varchar(255)";
+ }
+ else {
+ return "$fieldName varchar(16)";
+ }
+
+ case CRM_Utils_Type::T_STRING:
+ if (isset($queryFields[$columnName]['maxlength'])) {
+ return "$fieldName varchar({$queryFields[$columnName]['maxlength']})";
+ }
+ else {
+ return "$fieldName varchar(255)";
+ }
+
+ case CRM_Utils_Type::T_TEXT:
+ case CRM_Utils_Type::T_LONGTEXT:
+ case CRM_Utils_Type::T_BLOB:
+ case CRM_Utils_Type::T_MEDIUMBLOB:
+ return "$fieldName longtext";
+
+ case CRM_Utils_Type::T_FLOAT:
+ case CRM_Utils_Type::T_ENUM:
+ case CRM_Utils_Type::T_DATE:
+ case CRM_Utils_Type::T_TIME:
+ case CRM_Utils_Type::T_TIMESTAMP:
+ case CRM_Utils_Type::T_MONEY:
+ case CRM_Utils_Type::T_EMAIL:
+ case CRM_Utils_Type::T_URL:
+ case CRM_Utils_Type::T_CCNUM:
+ default:
+ return "$fieldName varchar(32)";
+ }
+ }
+ else {
+ if (substr($fieldName, -3, 3) == '_id') {
+ return "$fieldName varchar(255)";
+ }
+ elseif (substr($fieldName, -5, 5) == '_note') {
+ return "$fieldName text";
+ }
+ else {
+ $changeFields = [
+ 'groups',
+ 'tags',
+ 'notes',
+ ];
+
+ if (in_array($fieldName, $changeFields)) {
+ return "$fieldName text";
+ }
+ else {
+ // set the sql columns for custom data
+ if (isset($queryFields[$columnName]['data_type'])) {
+
+ switch ($queryFields[$columnName]['data_type']) {
+ case 'String':
+ // May be option labels, which could be up to 512 characters
+ $length = max(512, CRM_Utils_Array::value('text_length', $queryFields[$columnName]));
+ return "$fieldName varchar($length)";
+
+ case 'Country':
+ case 'StateProvince':
+ case 'Link':
+ return "$fieldName varchar(255)";
+
+ case 'Memo':
+ return "$fieldName text";
+
+ default:
+ return "$fieldName varchar(255)";
+ }
+ }
+ else {
+ return "$fieldName text";
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Get the munged field name.
+ *
+ * @param string $field
+ * @return string
+ */
+ public function getMungedFieldName($field) {
+ $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
+ if ($fieldName == 'id') {
+ $fieldName = 'civicrm_primary_id';
+ }
+ return $fieldName;
+ }
+
+ /**
+ * In order to respect the history of this class we need to index kinda illogically.
+ *
+ * On the bright side - this stuff is tested within a nano-byte of it's life.
+ *
+ * e.g '2-a-b_Home-City'
+ *
+ * @param string $key
+ * @param string $relationshipType
+ * @param string $locationType
+ * @param $entityLabel
+ *
+ * @return string
+ */
+ protected function getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel) {
+ if ($entityLabel || $key === 'im') {
+ // Just cos that's the history...
+ if ($key !== 'master_id') {
+ $key = $this->getHeaderForRow($key);
+ }
+ }
+ if (!$relationshipType || $key !== 'id') {
+ $key = $this->getMungedFieldName($key);
+ }
+ return $this->getMungedFieldName(
+ ($relationshipType ? ($relationshipType . '_') : '')
+ . ($locationType ? ($locationType . '_') : '')
+ . $key
+ . ($entityLabel ? ('_' . $entityLabel) : '')
+ );
+ }
+
+ /**
+ * Get the compiled label for the column.
+ *
+ * e.g 'Gender', 'Employee Of-Home-city'
+ *
+ * @param string $key
+ * @param string $relationshipType
+ * @param string $locationType
+ * @param string $entityLabel
+ *
+ * @return string
+ */
+ protected function getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel) {
+ return ($relationshipType ? $this->getRelationshipTypes()[$relationshipType] . '-' : '')
+ . ($locationType ? $locationType . '-' : '')
+ . $this->getHeaderForRow($key)
+ . ($entityLabel ? '-' . $entityLabel : '');
+ }
+
+ /**
+ * Get the mysql field name key.
+ *
+ * This key is locked in by tests but the reasons for the specific conventions -
+ * ie. headings are used for keying fields in some cases, are likely
+ * accidental rather than deliberate.
+ *
+ * This key is used for the output sql array.
+ *
+ * @param string $key
+ * @param $relationshipType
+ * @param $locationType
+ * @param $entityLabel
+ *
+ * @return string
+ */
+ protected function getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel) {
+ if ($entityLabel || $key === 'im') {
+ if ($key !== 'state_province' && $key !== 'id') {
+ // @todo - test removing this - indexing by $key should be fine...
+ $key = $this->getHeaderForRow($key);
+ }
+ }
+ if (!$relationshipType || $key !== 'id') {
+ $key = $this->getMungedFieldName($key);
+ }
+ $fieldKey = $this->getMungedFieldName(
+ ($relationshipType ? ($relationshipType . '_') : '')
+ . ($locationType ? ($locationType . '_') : '')
+ . $key
+ . ($entityLabel ? ('_' . $entityLabel) : '')
+ );
+ return $fieldKey;
+ }
+
+ /**
+ * Get params for the where criteria.
+ *
+ * @return mixed
+ */
+ public function getWhereParams() {
+ if (!$this->isPostalableOnly()) {
+ return [];
+ }
+ $params['is_deceased'] = ['is_deceased', '=', 0, CRM_Contact_BAO_Query::MODE_CONTACTS];
+ $params['do_not_mail'] = ['do_not_mail', '=', 0, CRM_Contact_BAO_Query::MODE_CONTACTS];
+ return $params;
+ }
+
+ /**
+ * @param $row
+ * @param $contactID
+ * @param $value
+ * @param $field
+ */
+ protected function buildRelationshipFieldsForRow(&$row, $contactID, $value, $field) {
+ foreach (array_keys($value) as $property) {
+ if ($property === 'location') {
+ // @todo just undo all this nasty location wrangling!
+ foreach ($value['location'] as $locationKey => $locationFields) {
+ foreach (array_keys($locationFields) as $locationField) {
+ $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
+ $row[$field . '_' . $fieldKey] = $this->getRelationshipValue($field, $contactID, $fieldKey);
+ }
+ }
+ }
+ else {
+ $row[$field . '_' . $property] = $this->getRelationshipValue($field, $contactID, $property);
+ }
+ }
+ }
+
+}
diff --git a/CRM/Export/Controller/Standalone.php b/CRM/Export/Controller/Standalone.php
new file mode 100644
index 000000000000..f91363906faf
--- /dev/null
+++ b/CRM/Export/Controller/Standalone.php
@@ -0,0 +1,96 @@
+set('entity', $entity);
+ $id = explode(',', CRM_Utils_Request::retrieve('id', 'CommaSeparatedIntegers', $this, TRUE));
+
+ // Check permissions
+ $perm = civicrm_api3($entity, 'get', [
+ 'return' => 'id',
+ 'options' => ['limit' => 0],
+ 'check_permissions' => 1,
+ 'id' => ['IN' => $id],
+ ]);
+
+ $this->set('id', implode(',', array_keys($perm['values'])));
+ if ($entity == 'Contact') {
+ $this->set('cids', implode(',', array_keys($perm['values'])));
+ }
+
+ $this->_stateMachine = new CRM_Export_StateMachine_Standalone($this, $action);
+
+ // create and instantiate the pages
+ $this->addPages($this->_stateMachine, $action);
+
+ // add all the actions
+ $this->addActions();
+ }
+
+ /**
+ * Export forms are historically tightly coupled to search forms,so this simulates
+ * the output of a search form, with an array of checkboxes for each selected entity.
+ *
+ * @param string $pageName
+ * @return array
+ */
+ public function exportValues($pageName = NULL) {
+ $values = parent::exportValues();
+ $values['radio_ts'] = 'ts_sel';
+ foreach (explode(',', $this->get('id')) as $id) {
+ if ($id) {
+ $values[CRM_Core_Form::CB_PREFIX . $id] = 1;
+ }
+ }
+ // Set the "task" selector value to Export
+ $className = 'CRM_' . $this->get('entity') . '_Task';
+ foreach ($className::tasks() as $taskId => $task) {
+ $taskForm = (array) $task['class'];
+ if ($taskForm[0] == 'CRM_Export_Form_Select') {
+ $values['task'] = $taskId;
+ }
+ }
+ return $values;
+ }
+
+}
diff --git a/CRM/Export/Form/Map.php b/CRM/Export/Form/Map.php
index d9c35180d2fb..60d6002dff2c 100644
--- a/CRM/Export/Form/Map.php
+++ b/CRM/Export/Form/Map.php
@@ -1,9 +1,9 @@
get('exportMode')
);
- $this->addButtons(array(
- array(
- 'type' => 'back',
- 'name' => ts('Previous'),
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Export'),
- 'spacing' => ' ',
- ),
- array(
- 'type' => 'done',
- 'icon' => 'fa-times',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'back',
+ 'name' => ts('Previous'),
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Export'),
+ 'spacing' => ' ',
+ ],
+ [
+ 'type' => 'done',
+ 'icon' => 'fa-times',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
@@ -125,7 +124,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($fields, $values, $mappingTypeId) {
- $errors = array();
+ $errors = [];
if (!empty($fields['saveMapping']) && !empty($fields['_qf_Map_next'])) {
$nameField = CRM_Utils_Array::value('saveMappingName', $fields);
@@ -221,11 +220,11 @@ public function postProcess() {
}
if (!empty($params['saveMapping'])) {
- $mappingParams = array(
+ $mappingParams = [
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
'mapping_type_id' => $this->get('mappingTypeId'),
- );
+ ];
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
@@ -237,7 +236,7 @@ public function postProcess() {
//get the csv file
CRM_Export_BAO_Export::exportComponents($this->get('selectAll'),
$this->get('componentIds'),
- $this->get('queryParams'),
+ (array) $this->get('queryParams'),
$this->get(CRM_Utils_Sort::SORT_ORDER),
$mapperKeys,
$this->get('returnProperties'),
diff --git a/CRM/Export/Form/Select.php b/CRM/Export/Form/Select.php
index 72fff6929659..7395ac1672f9 100644
--- a/CRM/Export/Form/Select.php
+++ b/CRM/Export/Form/Select.php
@@ -1,9 +1,9 @@
preventAjaxSubmit();
+
//special case for custom search, directly give option to download csv file
$customSearchID = $this->get('customSearchID');
if ($customSearchID) {
@@ -89,9 +91,79 @@ public function preProcess() {
$this->_selectAll = FALSE;
$this->_exportMode = self::CONTACT_EXPORT;
- $this->_componentIds = array();
+ $this->_componentIds = [];
$this->_componentClause = NULL;
+ // we need to determine component export
+ $components = ['Contact', 'Contribute', 'Member', 'Event', 'Pledge', 'Case', 'Grant', 'Activity'];
+
+ // FIXME: This should use a modified version of CRM_Contact_Form_Search::getModeValue but it doesn't have all the contexts
+ // FIXME: Or better still, use CRM_Core_DAO_AllCoreTables::getBriefName($daoName) to get the $entityShortName
+ switch ($this->getQueryMode()) {
+ case CRM_Contact_BAO_Query::MODE_CONTRIBUTE:
+ $entityShortname = 'Contribute';
+ $entityDAOName = $entityShortname;
+ break;
+
+ case CRM_Contact_BAO_Query::MODE_MEMBER:
+ $entityShortname = 'Member';
+ $entityDAOName = 'Membership';
+ break;
+
+ case CRM_Contact_BAO_Query::MODE_EVENT:
+ $entityShortname = 'Event';
+ $entityDAOName = $entityShortname;
+ break;
+
+ case CRM_Contact_BAO_Query::MODE_PLEDGE:
+ $entityShortname = 'Pledge';
+ $entityDAOName = $entityShortname;
+ break;
+
+ case CRM_Contact_BAO_Query::MODE_CASE:
+ $entityShortname = 'Case';
+ $entityDAOName = $entityShortname;
+ break;
+
+ case CRM_Contact_BAO_Query::MODE_GRANT:
+ $entityShortname = 'Grant';
+ $entityDAOName = $entityShortname;
+ break;
+
+ case CRM_Contact_BAO_Query::MODE_ACTIVITY:
+ $entityShortname = 'Activity';
+ $entityDAOName = $entityShortname;
+ break;
+
+ default:
+ // FIXME: Code cleanup, we may not need to do this $componentName code here.
+ $formName = CRM_Utils_System::getClassName($this->controller->getStateMachine());
+ $componentName = explode('_', $formName);
+ if ($formName == 'CRM_Export_StateMachine_Standalone') {
+ $componentName = ['CRM', $this->controller->get('entity')];
+ }
+ // Contact
+ $entityShortname = $componentName[1];
+ $entityDAOName = $entityShortname;
+ break;
+ }
+
+ if (in_array($entityShortname, $components)) {
+ $this->_exportMode = constant('CRM_Export_Form_Select::' . strtoupper($entityShortname) . '_EXPORT');
+ $formTaskClassName = "CRM_{$entityShortname}_Form_Task";
+ $taskClassName = "CRM_{$entityShortname}_Task";
+ if (isset($formTaskClassName::$entityShortname)) {
+ $this::$entityShortname = $formTaskClassName::$entityShortname;
+ if (isset($formTaskClassName::$tableName)) {
+ $this::$tableName = $formTaskClassName::$tableName;
+ }
+ }
+ else {
+ $this::$entityShortname = $entityShortname;
+ $this::$tableName = CRM_Core_DAO_AllCoreTables::getTableForClass(CRM_Core_DAO_AllCoreTables::getFullName($entityDAOName));
+ }
+ }
+
// get the submitted values based on search
if ($this->_action == CRM_Core_Action::ADVANCED) {
$values = $this->controller->exportValues('Advanced');
@@ -103,46 +175,7 @@ public function preProcess() {
$values = $this->controller->exportValues('Custom');
}
else {
- // we need to determine component export
- $stateMachine = $this->controller->getStateMachine();
-
- $formName = CRM_Utils_System::getClassName($stateMachine);
- $componentName = explode('_', $formName);
- $components = array('Contribute', 'Member', 'Event', 'Pledge', 'Case', 'Grant', 'Activity');
-
- if (in_array($componentName[1], $components)) {
- switch ($componentName[1]) {
- case 'Contribute':
- $this->_exportMode = self::CONTRIBUTE_EXPORT;
- break;
-
- case 'Member':
- $this->_exportMode = self::MEMBER_EXPORT;
- break;
-
- case 'Event':
- $this->_exportMode = self::EVENT_EXPORT;
- break;
-
- case 'Pledge':
- $this->_exportMode = self::PLEDGE_EXPORT;
- break;
-
- case 'Case':
- $this->_exportMode = self::CASE_EXPORT;
- break;
-
- case 'Grant':
- $this->_exportMode = self::GRANT_EXPORT;
- break;
-
- case 'Activity':
- $this->_exportMode = self::ACTIVITY_EXPORT;
- break;
- }
-
- $className = "CRM_{$componentName[1]}_Form_Task";
- $className::preProcessCommon($this, TRUE);
+ if (in_array($entityShortname, $components) && $entityShortname !== 'Contact') {
$values = $this->controller->exportValues('Search');
}
else {
@@ -164,53 +197,17 @@ public function preProcess() {
}
}
- $componentMode = $this->get('component_mode');
- switch ($componentMode) {
- case 2:
- CRM_Contribute_Form_Task::preProcessCommon($this, TRUE);
- $this->_exportMode = self::CONTRIBUTE_EXPORT;
- $componentName = array('', 'Contribute');
- break;
-
- case 3:
- CRM_Event_Form_Task::preProcessCommon($this, TRUE);
- $this->_exportMode = self::EVENT_EXPORT;
- $componentName = array('', 'Event');
- break;
-
- case 4:
- CRM_Activity_Form_Task::preProcessCommon($this, TRUE);
- $this->_exportMode = self::ACTIVITY_EXPORT;
- $componentName = array('', 'Activity');
- break;
-
- case 5:
- CRM_Member_Form_Task::preProcessCommon($this, TRUE);
- $this->_exportMode = self::MEMBER_EXPORT;
- $componentName = array('', 'Member');
- break;
+ $formTaskClassName::preProcessCommon($this);
- case 6:
- CRM_Case_Form_Task::preProcessCommon($this, TRUE);
- $this->_exportMode = self::CASE_EXPORT;
- $componentName = array('', 'Case');
- break;
- }
+ // $component is used on CRM/Export/Form/Select.tpl to display extra information for contact export
+ ($this->_exportMode == self::CONTACT_EXPORT) ? $component = FALSE : $component = TRUE;
+ $this->assign('component', $component);
+ // Set the task title
+ $componentTasks = $taskClassName::taskTitles();
$this->_task = $values['task'];
- if ($this->_exportMode == self::CONTACT_EXPORT) {
- $contactTasks = CRM_Contact_Task::taskTitles();
- $taskName = $contactTasks[$this->_task];
- $component = FALSE;
- CRM_Contact_Form_Task::preProcessCommon($this, TRUE);
- }
- else {
- $this->assign('taskName', "Export $componentName[1]");
- $className = "CRM_{$componentName[1]}_Task";
- $componentTasks = $className::tasks();
- $taskName = $componentTasks[$this->_task];
- $component = TRUE;
- }
+ $taskName = $componentTasks[$this->_task];
+ $this->assign('taskName', $taskName);
if ($this->_componentTable) {
$query = "
@@ -223,8 +220,7 @@ public function preProcess() {
$totalSelectedRecords = count($this->_componentIds);
}
$this->assign('totalSelectedRecords', $totalSelectedRecords);
- $this->assign('taskName', $taskName);
- $this->assign('component', $component);
+
// all records actions = save a search
if (($values['radio_ts'] == 'ts_all') || ($this->_task == CRM_Contact_Task::SAVE_SEARCH)) {
$this->_selectAll = TRUE;
@@ -250,37 +246,37 @@ public function preProcess() {
*/
public function buildQuickForm() {
//export option
- $exportOptions = $mergeOptions = $postalMailing = array();
+ $exportOptions = $mergeOptions = $postalMailing = [];
$exportOptions[] = $this->createElement('radio',
NULL, NULL,
ts('Export PRIMARY fields'),
self::EXPORT_ALL,
- array('onClick' => 'showMappingOption( );')
+ ['onClick' => 'showMappingOption( );']
);
$exportOptions[] = $this->createElement('radio',
NULL, NULL,
ts('Select fields for export'),
self::EXPORT_SELECTED,
- array('onClick' => 'showMappingOption( );')
+ ['onClick' => 'showMappingOption( );']
);
$mergeOptions[] = $this->createElement('radio',
NULL, NULL,
ts('Do not merge'),
self::EXPORT_MERGE_DO_NOT_MERGE,
- array('onclick' => 'showGreetingOptions( );')
+ ['onclick' => 'showGreetingOptions( );']
);
$mergeOptions[] = $this->createElement('radio',
NULL, NULL,
ts('Merge All Contacts with the Same Address'),
self::EXPORT_MERGE_SAME_ADDRESS,
- array('onclick' => 'showGreetingOptions( );')
+ ['onclick' => 'showGreetingOptions( );']
);
$mergeOptions[] = $this->createElement('radio',
NULL, NULL,
ts('Merge Household Members into their Households'),
self::EXPORT_MERGE_HOUSEHOLD,
- array('onclick' => 'showGreetingOptions( );')
+ ['onclick' => 'showGreetingOptions( );']
);
$postalMailing[] = $this->createElement('advcheckbox',
@@ -295,9 +291,9 @@ public function buildQuickForm() {
$this->_greetingOptions = self::getGreetingOptions();
foreach ($this->_greetingOptions as $key => $value) {
- $fieldLabel = ts('%1 (merging > 2 contacts)', array(1 => ucwords(str_replace('_', ' ', $key))));
+ $fieldLabel = ts('%1 (merging > 2 contacts)', [1 => ucwords(str_replace('_', ' ', $key))]);
$this->addElement('select', $key, $fieldLabel,
- $value, array('onchange' => "showOther(this);")
+ $value, ['onchange' => "showOther(this);"]
);
$this->addElement('text', "{$key}_other", '');
}
@@ -308,33 +304,32 @@ public function buildQuickForm() {
$this->addGroup($postalMailing, 'postal_mailing_export', ts('Postal Mailing Export'), ' ');
$this->addElement('select', 'additional_group', ts('Additional Group for Export'),
- array('' => ts('- select group -')) + CRM_Core_PseudoConstant::nestedGroup(),
- array('class' => 'crm-select2 huge')
+ ['' => ts('- select group -')] + CRM_Core_PseudoConstant::nestedGroup(),
+ ['class' => 'crm-select2 huge']
);
}
$this->buildMapping();
- $this->setDefaults(array(
+ $this->setDefaults([
'exportOption' => self::EXPORT_ALL,
'mergeOption' => self::EXPORT_MERGE_DO_NOT_MERGE,
- ));
-
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Continue'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $this->addFormRule(array('CRM_Export_Form_Select', 'formRule'), $this);
+ ]);
+
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Continue'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFormRule(['CRM_Export_Form_Select', 'formRule'], $this);
}
/**
@@ -349,16 +344,16 @@ public function buildQuickForm() {
* @return bool|array
* mixed true or array of errors
*/
- static public function formRule($params, $files, $self) {
- $errors = array();
+ public static function formRule($params, $files, $self) {
+ $errors = [];
if (CRM_Utils_Array::value('mergeOption', $params) == self::EXPORT_MERGE_SAME_ADDRESS &&
$self->_matchingContacts
) {
- $greetings = array(
+ $greetings = [
'postal_greeting' => 'postal_greeting_other',
'addressee' => 'addressee_other',
- );
+ ];
foreach ($greetings as $key => $value) {
$otherOption = CRM_Utils_Array::value($key, $params);
@@ -366,7 +361,7 @@ static public function formRule($params, $files, $self) {
if ((CRM_Utils_Array::value($otherOption, $self->_greetingOptions[$key]) == ts('Other')) && empty($params[$value])) {
$label = ucwords(str_replace('_', ' ', $key));
- $errors[$value] = ts('Please enter a value for %1 (merging > 2 contacts), or select a pre-configured option from the list.', array(1 => $label));
+ $errors[$value] = ts('Please enter a value for %1 (merging > 2 contacts), or select a pre-configured option from the list.', [1 => $label]);
}
}
}
@@ -377,7 +372,7 @@ static public function formRule($params, $files, $self) {
/**
* Process the uploaded file.
*
- * @return void
+ * @throws \CRM_Core_Exception
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
@@ -420,7 +415,7 @@ public function postProcess() {
if ($exportOption == self::EXPORT_ALL) {
CRM_Export_BAO_Export::exportComponents($this->_selectAll,
$this->_componentIds,
- $this->get('queryParams'),
+ (array) $this->get('queryParams'),
$this->get(CRM_Utils_Sort::SORT_ORDER),
NULL,
$this->get('returnProperties'),
@@ -485,12 +480,11 @@ public function buildMapping() {
break;
}
- $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', $exportType, 'name');
- $this->set('mappingTypeId', $mappingTypeId);
+ $this->set('mappingTypeId', CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', $exportType));
$mappings = CRM_Core_BAO_Mapping::getMappings($exportType);
if (!empty($mappings)) {
- $this->add('select', 'mapping', ts('Use Saved Field Mapping'), array('' => '-select-') + $mappings);
+ $this->add('select', 'mapping', ts('Use Saved Field Mapping'), ['' => '-select-'] + $mappings);
}
}
@@ -498,22 +492,22 @@ public function buildMapping() {
* @return array
*/
public static function getGreetingOptions() {
- $options = array();
- $greetings = array(
+ $options = [];
+ $greetings = [
'postal_greeting' => 'postal_greeting_other',
'addressee' => 'addressee_other',
- );
+ ];
foreach ($greetings as $key => $value) {
- $params = array();
+ $params = [];
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $key, 'id', 'name');
CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_OptionValue', 'option_group_id', $optionGroupId,
- $params, array('label', 'filter')
+ $params, ['label', 'filter']
);
$greetingCount = 1;
- $options[$key] = array("$greetingCount" => ts('List of names'));
+ $options[$key] = ["$greetingCount" => ts('List of names')];
foreach ($params as $id => $field) {
if (CRM_Utils_Array::value('filter', $field) == 4) {
@@ -527,4 +521,13 @@ public static function getGreetingOptions() {
return $options;
}
+ /**
+ * Get the query mode (eg. CRM_Core_BAO_Query::MODE_CASE)
+ *
+ * @return int
+ */
+ public function getQueryMode() {
+ return (int) ($this->queryMode ?: $this->controller->get('component_mode'));
+ }
+
}
diff --git a/tests/phpunit/WebTest/AllTests.php b/CRM/Export/Form/Select/Case.php
similarity index 71%
rename from tests/phpunit/WebTest/AllTests.php
rename to CRM/Export/Form/Select/Case.php
index fe90870f509d..3c09b2645197 100644
--- a/tests/phpunit/WebTest/AllTests.php
+++ b/CRM/Export/Form/Select/Case.php
@@ -1,9 +1,9 @@
implSuite(__FILE__);
+ public function getTemplateFileName() {
+ return 'CRM/Export/Form/Select.tpl';
}
}
diff --git a/CRM/Export/StateMachine/Standalone.php b/CRM/Export/StateMachine/Standalone.php
new file mode 100644
index 000000000000..375013a7f73d
--- /dev/null
+++ b/CRM/Export/StateMachine/Standalone.php
@@ -0,0 +1,68 @@
+_pages = [
+ 'CRM_Export_Form_Select' => NULL,
+ 'CRM_Export_Form_Map' => NULL,
+ ];
+
+ $this->addSequentialPages($this->_pages, $action);
+ }
+
+ /**
+ * @todo So far does nothing.
+ *
+ * @return string
+ */
+ public function getTaskFormName() {
+ return '';
+ }
+
+ /**
+ * @todo not sure if this is needed
+ */
+ public function shouldReset() {
+ return FALSE;
+ }
+
+}
diff --git a/CRM/Extension/Browser.php b/CRM/Extension/Browser.php
index 82d8f47606ba..15b5a84c558f 100644
--- a/CRM/Extension/Browser.php
+++ b/CRM/Extension/Browser.php
@@ -1,9 +1,9 @@
baseDir) || !is_dir($this->baseDir)) {
- $errors[] = array(
+ $errors[] = [
'title' => ts('Invalid Base Directory'),
'message' => ts('An extension container has been defined with a blank directory.'),
- );
+ ];
}
if (empty($this->baseUrl)) {
- $errors[] = array(
+ $errors[] = [
'title' => ts('Invalid Base URL'),
'message' => ts('An extension container has been defined with a blank URL.'),
- );
+ ];
}
return $errors;
@@ -146,10 +146,10 @@ public function getResUrl($key) {
if (!$this->baseUrl) {
CRM_Core_Session::setStatus(
ts('Failed to determine URL for extension (%1). Please update Resource URLs.',
- array(
+ [
1 => $key,
2 => CRM_Utils_System::url('civicrm/admin/setting/url', 'reset=1'),
- )
+ ]
)
);
}
@@ -202,7 +202,7 @@ protected function getRelPaths() {
$this->relPaths = $this->cache->get($this->cacheKey);
}
if (!is_array($this->relPaths)) {
- $this->relPaths = array();
+ $this->relPaths = [];
$infoPaths = CRM_Utils_File::findFiles($this->baseDir, 'info.xml');
foreach ($infoPaths as $infoPath) {
$relPath = CRM_Utils_File::relativize(dirname($infoPath), $this->baseDir);
@@ -210,9 +210,9 @@ protected function getRelPaths() {
$info = CRM_Extension_Info::loadFromFile($infoPath);
}
catch (CRM_Extension_Exception_ParseException $e) {
- CRM_Core_Session::setStatus(ts('Parse error in extension: %1', array(
+ CRM_Core_Session::setStatus(ts('Parse error in extension: %1', [
1 => $e->getMessage(),
- )), '', 'error');
+ ]), '', 'error');
CRM_Core_Error::debug_log_message("Parse error in extension: " . $e->getMessage());
continue;
}
@@ -272,7 +272,7 @@ protected function getRelUrls() {
* Array($key => $relUrl).
*/
public static function convertPathsToUrls($dirSep, $relPaths) {
- $relUrls = array();
+ $relUrls = [];
foreach ($relPaths as $key => $relPath) {
$relUrls[$key] = str_replace($dirSep, '/', $relPath);
}
diff --git a/CRM/Extension/Container/Collection.php b/CRM/Extension/Container/Collection.php
index 91169296052f..0258c3689690 100644
--- a/CRM/Extension/Container/Collection.php
+++ b/CRM/Extension/Container/Collection.php
@@ -1,9 +1,9 @@
containers as $container) {
$errors = array_merge($errors, $container->checkRequirements());
}
@@ -163,7 +163,7 @@ public function getKeysToContainer() {
$k2c = $this->cache->get($this->cacheKey);
}
if (!isset($k2c) || !is_array($k2c)) {
- $k2c = array();
+ $k2c = [];
$containerNames = array_reverse(array_keys($this->containers));
foreach ($containerNames as $name) {
$keys = $this->containers[$name]->getKeys();
diff --git a/CRM/Extension/Container/Default.php b/CRM/Extension/Container/Default.php
index 4b3f2be9a446..674e46584df0 100644
--- a/CRM/Extension/Container/Default.php
+++ b/CRM/Extension/Container/Default.php
@@ -1,9 +1,9 @@
array $spec) List of extensions.
@@ -47,7 +48,7 @@ public function __construct($exts) {
* @inheritDoc
*/
public function checkRequirements() {
- return array();
+ return [];
}
/**
diff --git a/CRM/Extension/Downloader.php b/CRM/Extension/Downloader.php
index e071841ee6f7..64f83178a425 100644
--- a/CRM/Extension/Downloader.php
+++ b/CRM/Extension/Downloader.php
@@ -1,9 +1,9 @@
'psr4', 'namespace'=>'Foo\Bar', 'path'=>'/foo/bar').
*/
- public $classloader = array();
+ public $classloader = [];
+
+ /**
+ * @var array
+ * Each item is they key-name of an extension required by this extension.
+ */
+ public $requires = [];
/**
* Load extension info an XML file.
@@ -90,6 +99,27 @@ public static function loadFromString($string) {
return $instance;
}
+ /**
+ * Build a reverse-dependency map.
+ *
+ * @param array $infos
+ * The universe of available extensions.
+ * Ex: $infos['org.civicrm.foobar'] = new CRM_Extension_Info().
+ * @return array
+ * If "org.civicrm.api" is required by "org.civicrm.foo", then return
+ * array('org.civicrm.api' => array(CRM_Extension_Info[org.civicrm.foo])).
+ * Array(string $key => array $requiredBys).
+ */
+ public static function buildReverseMap($infos) {
+ $revMap = [];
+ foreach ($infos as $info) {
+ foreach ($info->requires as $key) {
+ $revMap[$key][] = $info;
+ }
+ }
+ return $revMap;
+ }
+
/**
* @param null $key
* @param null $type
@@ -124,7 +154,7 @@ public function parse($info) {
$this->$attr = (string) $val;
}
elseif ($attr === 'urls') {
- $this->urls = array();
+ $this->urls = [];
foreach ($val->url as $url) {
$urlAttr = (string) $url->attributes()->desc;
$this->urls[$urlAttr] = (string) $url;
@@ -132,19 +162,40 @@ public function parse($info) {
ksort($this->urls);
}
elseif ($attr === 'classloader') {
- $this->classloader = array();
+ $this->classloader = [];
foreach ($val->psr4 as $psr4) {
- $this->classloader[] = array(
+ $this->classloader[] = [
'type' => 'psr4',
'prefix' => (string) $psr4->attributes()->prefix,
'path' => (string) $psr4->attributes()->path,
- );
+ ];
}
}
+ elseif ($attr === 'requires') {
+ $this->requires = $this->filterRequirements($val);
+ }
else {
$this->$attr = CRM_Utils_XML::xmlObjToArray($val);
}
}
}
+ /**
+ * Filter out invalid requirements, e.g. extensions that have been moved to core.
+ *
+ * @param SimpleXMLElement $requirements
+ * @return array
+ */
+ public function filterRequirements($requirements) {
+ $filtered = [];
+ $compatInfo = CRM_Extension_System::getCompatibilityInfo();
+ foreach ($requirements->ext as $ext) {
+ $ext = (string) $ext;
+ if (empty($compatInfo[$ext]['obsolete'])) {
+ $filtered[] = $ext;
+ }
+ }
+ return $filtered;
+ }
+
}
diff --git a/CRM/Extension/Manager.php b/CRM/Extension/Manager.php
index 6ef8c6e55fb2..7770d5a8e143 100644
--- a/CRM/Extension/Manager.php
+++ b/CRM/Extension/Manager.php
@@ -1,9 +1,9 @@
_getInfoTypeHandler($newInfo->key); // throws Exception
+ // throws Exception
+ list ($oldInfo, $typeManager) = $this->_getInfoTypeHandler($newInfo->key);
$tgtPath = $this->fullContainer->getPath($newInfo->key);
if (!CRM_Utils_File::isChildPath($this->defaultContainer->getBaseDir(), $tgtPath)) {
// force installation in the default-container
$oldPath = $tgtPath;
$tgtPath = $this->defaultContainer->getBaseDir() . DIRECTORY_SEPARATOR . $newInfo->key;
- CRM_Core_Session::setStatus(ts('A copy of the extension (%1) is in a system folder (%2). The system copy will be preserved, but the new copy will be used.', array(
+ CRM_Core_Session::setStatus(ts('A copy of the extension (%1) is in a system folder (%2). The system copy will be preserved, but the new copy will be used.', [
1 => $newInfo->key,
2 => $oldPath,
- )));
+ ]));
}
break;
@@ -152,7 +153,8 @@ public function replace($tmpCodeDir) {
case self::STATUS_DISABLED_MISSING:
// the extension does not exist in any container; we're free to put it anywhere
$tgtPath = $this->defaultContainer->getBaseDir() . DIRECTORY_SEPARATOR . $newInfo->key;
- list ($oldInfo, $typeManager) = $this->_getMissingInfoTypeHandler($newInfo->key); // throws Exception
+ // throws Exception
+ list ($oldInfo, $typeManager) = $this->_getMissingInfoTypeHandler($newInfo->key);
break;
case self::STATUS_UNKNOWN:
@@ -210,7 +212,8 @@ public function install($keys) {
// keys/statuses/types before doing anything
foreach ($keys as $key) {
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
switch ($origStatuses[$key]) {
case self::STATUS_INSTALLED:
@@ -222,6 +225,11 @@ public function install($keys) {
$typeManager->onPreEnable($info);
$this->_setExtensionActive($info, 1);
$typeManager->onPostEnable($info);
+
+ // A full refresh would be preferrable but very slow. This at least allows
+ // later extensions to access classes from earlier extensions.
+ $this->statuses = NULL;
+ $this->mapper->refresh();
break;
case self::STATUS_UNINSTALLED:
@@ -229,6 +237,11 @@ public function install($keys) {
$typeManager->onPreInstall($info);
$this->_createExtensionEntry($info);
$typeManager->onPostInstall($info);
+
+ // A full refresh would be preferrable but very slow. This at least allows
+ // later extensions to access classes from earlier extensions.
+ $this->statuses = NULL;
+ $this->mapper->refresh();
break;
case self::STATUS_UNKNOWN:
@@ -244,7 +257,8 @@ public function install($keys) {
$schema->fixSchemaDifferences();
foreach ($keys as $key) {
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
switch ($origStatuses[$key]) {
case self::STATUS_INSTALLED:
@@ -292,17 +306,27 @@ public function disable($keys) {
// TODO: to mitigate the risk of crashing during installation, scan
// keys/statuses/types before doing anything
+ sort($keys);
+ $disableRequirements = $this->findDisableRequirements($keys);
+ // This munges order, but makes it comparable.
+ sort($disableRequirements);
+ if ($keys !== $disableRequirements) {
+ throw new CRM_Extension_Exception_DependencyException("Cannot disable extension due dependencies. Consider disabling all these: " . implode(',', $disableRequirements));
+ }
+
foreach ($keys as $key) {
switch ($origStatuses[$key]) {
case self::STATUS_INSTALLED:
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
$typeManager->onPreDisable($info);
$this->_setExtensionActive($info, 0);
$typeManager->onPostDisable($info);
break;
case self::STATUS_INSTALLED_MISSING:
- list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key);
$typeManager->onPreDisable($info);
$this->_setExtensionActive($info, 0);
$typeManager->onPostDisable($info);
@@ -347,14 +371,16 @@ public function uninstall($keys) {
throw new CRM_Extension_Exception("Cannot uninstall extension; disable it first: $key");
case self::STATUS_DISABLED:
- list ($info, $typeManager) = $this->_getInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getInfoTypeHandler($key);
$typeManager->onPreUninstall($info);
$this->_removeExtensionEntry($info);
$typeManager->onPostUninstall($info);
break;
case self::STATUS_DISABLED_MISSING:
- list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key); // throws Exception
+ // throws Exception
+ list ($info, $typeManager) = $this->_getMissingInfoTypeHandler($key);
$typeManager->onPreUninstall($info);
$this->_removeExtensionEntry($info);
$typeManager->onPostUninstall($info);
@@ -401,7 +427,7 @@ public function getStatus($key) {
*/
public function getStatuses() {
if (!is_array($this->statuses)) {
- $this->statuses = array();
+ $this->statuses = [];
foreach ($this->fullContainer->getKeys() as $key) {
$this->statuses[$key] = self::STATUS_UNINSTALLED;
@@ -433,7 +459,8 @@ public function getStatuses() {
public function refresh() {
$this->statuses = NULL;
- $this->fullContainer->refresh(); // and, indirectly, defaultContainer
+ // and, indirectly, defaultContainer
+ $this->fullContainer->refresh();
$this->mapper->refresh();
}
@@ -449,9 +476,10 @@ public function refresh() {
* (0 => CRM_Extension_Info, 1 => CRM_Extension_Manager_Interface)
*/
private function _getInfoTypeHandler($key) {
- $info = $this->mapper->keyToInfo($key); // throws Exception
+ // throws Exception
+ $info = $this->mapper->keyToInfo($key);
if (array_key_exists($info->type, $this->typeManagers)) {
- return array($info, $this->typeManagers[$info->type]);
+ return [$info, $this->typeManagers[$info->type]];
}
else {
throw new CRM_Extension_Exception("Unrecognized extension type: " . $info->type);
@@ -471,7 +499,7 @@ private function _getMissingInfoTypeHandler($key) {
$info = $this->createInfoFromDB($key);
if ($info) {
if (array_key_exists($info->type, $this->typeManagers)) {
- return array($info, $this->typeManagers[$info->type]);
+ return [$info, $this->typeManagers[$info->type]];
}
else {
throw new CRM_Extension_Exception("Unrecognized extension type: " . $info->type);
@@ -543,10 +571,10 @@ private function _removeExtensionEntry(CRM_Extension_Info $info) {
* @param $isActive
*/
private function _setExtensionActive(CRM_Extension_Info $info, $isActive) {
- CRM_Core_DAO::executeQuery('UPDATE civicrm_extension SET is_active = %1 where full_name = %2', array(
- 1 => array($isActive, 'Integer'),
- 2 => array($info->key, 'String'),
- ));
+ CRM_Core_DAO::executeQuery('UPDATE civicrm_extension SET is_active = %1 where full_name = %2', [
+ 1 => [$isActive, 'Integer'],
+ 2 => [$info->key, 'String'],
+ ]);
}
/**
@@ -568,4 +596,98 @@ public function createInfoFromDB($key) {
}
}
+ /**
+ * Build a list of extensions to install, in an order that will satisfy dependencies.
+ *
+ * @param array $keys
+ * List of extensions to install.
+ * @return array
+ * List of extension keys, including dependencies, in order of installation.
+ */
+ public function findInstallRequirements($keys) {
+ $infos = $this->mapper->getAllInfos();
+ // array(string $key).
+ $todoKeys = array_unique($keys);
+ // array(string $key => 1);
+ $doneKeys = [];
+ $sorter = new \MJS\TopSort\Implementations\FixedArraySort();
+
+ while (!empty($todoKeys)) {
+ $key = array_shift($todoKeys);
+ if (isset($doneKeys[$key])) {
+ continue;
+ }
+ $doneKeys[$key] = 1;
+
+ /** @var CRM_Extension_Info $info */
+ $info = @$infos[$key];
+
+ if ($this->getStatus($key) === self::STATUS_INSTALLED) {
+ $sorter->add($key, []);
+ }
+ elseif ($info && $info->requires) {
+ $sorter->add($key, $info->requires);
+ $todoKeys = array_merge($todoKeys, $info->requires);
+ }
+ else {
+ $sorter->add($key, []);
+ }
+ }
+ return $sorter->sort();
+ }
+
+ /**
+ * Build a list of extensions to remove, in an order that will satisfy dependencies.
+ *
+ * @param array $keys
+ * List of extensions to install.
+ * @return array
+ * List of extension keys, including dependencies, in order of removal.
+ */
+ public function findDisableRequirements($keys) {
+ $INSTALLED = [
+ self::STATUS_INSTALLED,
+ self::STATUS_INSTALLED_MISSING,
+ ];
+ $installedInfos = $this->filterInfosByStatus($this->mapper->getAllInfos(), $INSTALLED);
+ $revMap = CRM_Extension_Info::buildReverseMap($installedInfos);
+ $todoKeys = array_unique($keys);
+ $doneKeys = [];
+ $sorter = new \MJS\TopSort\Implementations\FixedArraySort();
+
+ while (!empty($todoKeys)) {
+ $key = array_shift($todoKeys);
+ if (isset($doneKeys[$key])) {
+ continue;
+ }
+ $doneKeys[$key] = 1;
+
+ if (isset($revMap[$key])) {
+ $requiredBys = CRM_Utils_Array::collect('key',
+ $this->filterInfosByStatus($revMap[$key], $INSTALLED));
+ $sorter->add($key, $requiredBys);
+ $todoKeys = array_merge($todoKeys, $requiredBys);
+ }
+ else {
+ $sorter->add($key, []);
+ }
+ }
+ return $sorter->sort();
+ }
+
+ /**
+ * @param $infos
+ * @param $filterStatuses
+ * @return array
+ */
+ protected function filterInfosByStatus($infos, $filterStatuses) {
+ $matches = [];
+ foreach ($infos as $k => $v) {
+ if (in_array($this->getStatus($v->key), $filterStatuses)) {
+ $matches[$k] = $v;
+ }
+ }
+ return $matches;
+ }
+
}
diff --git a/CRM/Extension/Manager/Base.php b/CRM/Extension/Manager/Base.php
index 6d2509e77b70..4fed2bc68eeb 100644
--- a/CRM/Extension/Manager/Base.php
+++ b/CRM/Extension/Manager/Base.php
@@ -1,9 +1,9 @@
$id)
*/
private function _getAllPaymentProcessorTypes($attr) {
- $ppt = array();
+ $ppt = [];
$dao = new CRM_Financial_DAO_PaymentProcessorType();
$dao->find();
while ($dao->fetch()) {
@@ -204,11 +204,11 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
$paymentClass = $this->mapper->keyToClass($info->key, 'payment');
$file = $this->mapper->classToPath($paymentClass);
if (!file_exists($file)) {
- CRM_Core_Session::setStatus(ts('Failed to load file (%3) for payment processor (%1) while running "%2"', array(
- 1 => $info->key,
- 2 => $method,
- 3 => $file,
- )), '', 'error');
+ CRM_Core_Session::setStatus(ts('Failed to load file (%3) for payment processor (%1) while running "%2"', [
+ 1 => $info->key,
+ 2 => $method,
+ 3 => $file,
+ ]), '', 'error');
return;
}
else {
@@ -216,10 +216,10 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
}
}
catch (CRM_Extension_Exception $e) {
- CRM_Core_Session::setStatus(ts('Failed to determine file path for payment processor (%1) while running "%2"', array(
- 1 => $info->key,
- 2 => $method,
- )), '', 'error');
+ CRM_Core_Session::setStatus(ts('Failed to determine file path for payment processor (%1) while running "%2"', [
+ 1 => $info->key,
+ 2 => $method,
+ ]), '', 'error');
return;
}
@@ -233,9 +233,9 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
WHERE ext.type = 'payment'
AND ext.full_name = %1
",
- array(
- 1 => array($info->key, 'String'),
- )
+ [
+ 1 => [$info->key, 'String'],
+ ]
);
while ($processorDAO->fetch()) {
@@ -262,11 +262,10 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
$processorInstance = Civi\Payment\System::singleton()->getByClass($class_name);
// Does PP implement this method, and can we call it?
- if (method_exists($processorInstance, $method) && is_callable(array(
- $processorInstance,
- $method,
- ))
- ) {
+ if (method_exists($processorInstance, $method) && is_callable([
+ $processorInstance,
+ $method,
+ ])) {
// If so, call it ...
$processorInstance->$method();
}
@@ -274,7 +273,7 @@ private function _runPaymentHook(CRM_Extension_Info $info, $method) {
default:
CRM_Core_Session::setStatus(ts("Unrecognized payment hook (%1) in %2::%3",
- array(1 => $method, 2 => __CLASS__, 3 => __METHOD__)),
+ [1 => $method, 2 => __CLASS__, 3 => __METHOD__]),
'', 'error');
}
}
diff --git a/CRM/Extension/Manager/Report.php b/CRM/Extension/Manager/Report.php
index 8f92b9a7cdf9..3302ec291824 100644
--- a/CRM/Extension/Manager/Report.php
+++ b/CRM/Extension/Manager/Report.php
@@ -1,9 +1,9 @@
typeInfo['component'] . ") is currently disabled.");
}
$weight = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
- array('option_group_id' => $this->groupId)
+ ['option_group_id' => $this->groupId]
);
- $ids = array();
- $params = array(
+ $ids = [];
+ $params = [
'label' => $info->label . ' (' . $info->key . ')',
'value' => $info->typeInfo['reportUrl'],
'name' => $info->key,
@@ -79,7 +79,7 @@ public function onPreInstall(CRM_Extension_Info $info) {
'component_id' => $compId,
'option_group_id' => $this->groupId,
'is_active' => 1,
- );
+ ];
$optionValue = CRM_Core_BAO_OptionValue::add($params, $ids);
}
diff --git a/CRM/Extension/Manager/Search.php b/CRM/Extension/Manager/Search.php
index 684d1027ca38..1f0b291bf80c 100644
--- a/CRM/Extension/Manager/Search.php
+++ b/CRM/Extension/Manager/Search.php
@@ -1,9 +1,9 @@
$this->groupId)
+ ['option_group_id' => $this->groupId]
);
- $params = array(
+ $params = [
'option_group_id' => $this->groupId,
'weight' => $weight,
'description' => $info->label . ' (' . $info->key . ')',
@@ -69,9 +69,9 @@ public function onPreInstall(CRM_Extension_Info $info) {
'value' => max($customSearchesByName) + 1,
'label' => $info->key,
'is_active' => 1,
- );
+ ];
- $ids = array();
+ $ids = [];
$optionValue = CRM_Core_BAO_OptionValue::add($params, $ids);
return $optionValue ? TRUE : FALSE;
diff --git a/CRM/Extension/Mapper.php b/CRM/Extension/Mapper.php
index de31e82d9198..b9cc7ed18210 100644
--- a/CRM/Extension/Mapper.php
+++ b/CRM/Extension/Mapper.php
@@ -1,9 +1,9 @@
CRM_Extension_Info)
*/
- protected $infos = array();
+ protected $infos = [];
/**
* @var array
@@ -275,19 +275,19 @@ public function keyToUrl($key) {
* array(array('prefix' => $, 'file' => $))
*/
public function getActiveModuleFiles($fresh = FALSE) {
- $config = CRM_Core_Config::singleton();
- if ($config->isUpgradeMode() || !defined('CIVICRM_DSN')) {
- return array(); // hmm, ok
+ if (!defined('CIVICRM_DSN')) {
+ // hmm, ok
+ return [];
}
$moduleExtensions = NULL;
if ($this->cache && !$fresh) {
- $moduleExtensions = $this->cache->get($this->cacheKey . '/moduleFiles');
+ $moduleExtensions = $this->cache->get($this->cacheKey . '_moduleFiles');
}
if (!is_array($moduleExtensions)) {
// Check canonical module list
- $moduleExtensions = array();
+ $moduleExtensions = [];
$sql = '
SELECT full_name, file
FROM civicrm_extension
@@ -297,25 +297,25 @@ public function getActiveModuleFiles($fresh = FALSE) {
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
try {
- $moduleExtensions[] = array(
+ $moduleExtensions[] = [
'prefix' => $dao->file,
'filePath' => $this->keyToPath($dao->full_name),
- );
+ ];
}
catch (CRM_Extension_Exception $e) {
// Putting a stub here provides more consistency
// in how getActiveModuleFiles when racing between
// dirty file-removals and cache-clears.
CRM_Core_Session::setStatus($e->getMessage(), '', 'error');
- $moduleExtensions[] = array(
+ $moduleExtensions[] = [
'prefix' => $dao->file,
'filePath' => NULL,
- );
+ ];
}
}
if ($this->cache) {
- $this->cache->set($this->cacheKey . '/moduleFiles', $moduleExtensions);
+ $this->cache->set($this->cacheKey . '_moduleFiles', $moduleExtensions);
}
}
return $moduleExtensions;
@@ -329,7 +329,7 @@ public function getActiveModuleFiles($fresh = FALSE) {
*/
public function getActiveModuleUrls() {
// TODO optimization/caching
- $urls = array();
+ $urls = [];
$urls['civicrm'] = $this->keyToUrl('civicrm');
foreach ($this->getModules() as $module) {
/** @var $module CRM_Core_Module */
@@ -340,6 +340,54 @@ public function getActiveModuleUrls() {
return $urls;
}
+ /**
+ * Get a list of extension keys, filtered by the corresponding file path.
+ *
+ * @param string $pattern
+ * A file path. To search subdirectories, append "*".
+ * Ex: "/var/www/extensions/*"
+ * Ex: "/var/www/extensions/org.foo.bar"
+ * @return array
+ * Array(string $key).
+ * Ex: array("org.foo.bar").
+ */
+ public function getKeysByPath($pattern) {
+ $keys = [];
+
+ if (CRM_Utils_String::endsWith($pattern, '*')) {
+ $prefix = rtrim($pattern, '*');
+ foreach ($this->container->getKeys() as $key) {
+ $path = CRM_Utils_File::addTrailingSlash($this->container->getPath($key));
+ if (realpath($prefix) == realpath($path) || CRM_Utils_File::isChildPath($prefix, $path)) {
+ $keys[] = $key;
+ }
+ }
+ }
+ else {
+ foreach ($this->container->getKeys() as $key) {
+ $path = CRM_Utils_File::addTrailingSlash($this->container->getPath($key));
+ if (realpath($pattern) == realpath($path)) {
+ $keys[] = $key;
+ }
+ }
+ }
+
+ return $keys;
+ }
+
+ /**
+ * @return array
+ * Ex: $result['org.civicrm.foobar'] = new CRM_Extension_Info(...).
+ * @throws \CRM_Extension_Exception
+ * @throws \Exception
+ */
+ public function getAllInfos() {
+ foreach ($this->container->getKeys() as $key) {
+ $this->keyToInfo($key);
+ }
+ return $this->infos;
+ }
+
/**
* @param string $name
*
@@ -362,7 +410,7 @@ public function isActiveModule($name) {
* CRM_Core_Module
*/
public function getModules() {
- $result = array();
+ $result = [];
$dao = new CRM_Core_DAO_Extension();
$dao->type = 'module';
$dao->find();
@@ -410,10 +458,10 @@ public function getTemplateName($clazz) {
}
public function refresh() {
- $this->infos = array();
+ $this->infos = [];
$this->moduleExtensions = NULL;
if ($this->cache) {
- $this->cache->delete($this->cacheKey . '/moduleFiles');
+ $this->cache->delete($this->cacheKey . '_moduleFiles');
}
// FIXME: How can code so code wrong be so right?
CRM_Extension_System::singleton()->getClassLoader()->refresh();
diff --git a/CRM/Extension/System.php b/CRM/Extension/System.php
index d83263a5795d..6aeaa30baed7 100644
--- a/CRM/Extension/System.php
+++ b/CRM/Extension/System.php
@@ -1,9 +1,9 @@
extensionsDir);
$parameters['extensionsURL'] = CRM_Utils_Array::value('extensionsURL', $parameters, $config->extensionsURL);
@@ -109,7 +109,8 @@ public function __construct($parameters = array()) {
if (!array_key_exists('domain_id', $parameters)) {
$parameters['domain_id'] = CRM_Core_Config::domainID();
}
- ksort($parameters); // guaranteed ordering - useful for md5(serialize($parameters))
+ // guaranteed ordering - useful for md5(serialize($parameters))
+ ksort($parameters);
$this->parameters = $parameters;
}
@@ -121,7 +122,7 @@ public function __construct($parameters = array()) {
*/
public function getFullContainer() {
if ($this->fullContainer === NULL) {
- $containers = array();
+ $containers = [];
if ($this->getDefaultContainer()) {
$containers['default'] = $this->getDefaultContainer();
@@ -205,12 +206,12 @@ public function getClassLoader() {
*/
public function getManager() {
if ($this->manager === NULL) {
- $typeManagers = array(
+ $typeManagers = [
'payment' => new CRM_Extension_Manager_Payment($this->getMapper()),
'report' => new CRM_Extension_Manager_Report(),
'search' => new CRM_Extension_Manager_Search(),
'module' => new CRM_Extension_Manager_Module($this->getMapper()),
- );
+ ];
$this->manager = new CRM_Extension_Manager($this->getFullContainer(), $this->getDefaultContainer(), $this->getMapper(), $typeManagers);
}
return $this->manager;
@@ -243,7 +244,8 @@ public function getDownloader() {
$this->downloader = new CRM_Extension_Downloader(
$this->getManager(),
$basedir,
- CRM_Utils_File::tempdir() // WAS: $config->extensionsDir . DIRECTORY_SEPARATOR . 'tmp';
+ // WAS: $config->extensionsDir . DIRECTORY_SEPARATOR . 'tmp';
+ CRM_Utils_File::tempdir()
);
}
return $this->downloader;
@@ -254,13 +256,13 @@ public function getDownloader() {
*/
public function getCache() {
if ($this->cache === NULL) {
- $cacheGroup = md5(serialize(array('ext', $this->parameters)));
+ $cacheGroup = md5(serialize(['ext', $this->parameters]));
// Extension system starts before container. Manage our own cache.
- $this->cache = CRM_Utils_Cache::create(array(
+ $this->cache = CRM_Utils_Cache::create([
'name' => $cacheGroup,
- 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
+ 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
'prefetch' => TRUE,
- ));
+ ]);
}
return $this->cache;
}
@@ -286,6 +288,18 @@ public function getRepositoryUrl() {
return $this->_repoUrl;
}
+ /**
+ * Returns a list keyed by extension key
+ *
+ * @return array
+ */
+ public static function getCompatibilityInfo() {
+ if (!isset(Civi::$statics[__CLASS__]['compatibility'])) {
+ Civi::$statics[__CLASS__]['compatibility'] = json_decode(file_get_contents(Civi::paths()->getPath('[civicrm.root]/extension-compatibility.json')), TRUE);
+ }
+ return Civi::$statics[__CLASS__]['compatibility'];
+ }
+
/**
* Take an extension's raw XML info and add information about the
* extension's status on the local system.
@@ -311,7 +325,8 @@ public static function createExtendedInfo(CRM_Extension_Info $obj) {
switch ($extensionRow['status']) {
case CRM_Extension_Manager::STATUS_UNINSTALLED:
- $extensionRow['statusLabel'] = ''; // ts('Uninstalled');
+ // ts('Uninstalled');
+ $extensionRow['statusLabel'] = '';
break;
case CRM_Extension_Manager::STATUS_DISABLED:
@@ -319,7 +334,8 @@ public static function createExtendedInfo(CRM_Extension_Info $obj) {
break;
case CRM_Extension_Manager::STATUS_INSTALLED:
- $extensionRow['statusLabel'] = ts('Enabled'); // ts('Installed');
+ // ts('Installed');
+ $extensionRow['statusLabel'] = ts('Enabled');
break;
case CRM_Extension_Manager::STATUS_DISABLED_MISSING:
@@ -327,7 +343,8 @@ public static function createExtendedInfo(CRM_Extension_Info $obj) {
break;
case CRM_Extension_Manager::STATUS_INSTALLED_MISSING:
- $extensionRow['statusLabel'] = ts('Enabled (Missing)'); // ts('Installed');
+ // ts('Installed');
+ $extensionRow['statusLabel'] = ts('Enabled (Missing)');
break;
default:
diff --git a/CRM/Extension/Upgrades.php b/CRM/Extension/Upgrades.php
index 7e020578cbe5..a81a5b65f768 100644
--- a/CRM/Extension/Upgrades.php
+++ b/CRM/Extension/Upgrades.php
@@ -1,9 +1,9 @@
create(array(
+ $queue = CRM_Queue_Service::singleton()->create([
'type' => 'Sql',
'name' => self::QUEUE_NAME,
'reset' => TRUE,
- ));
+ ]);
CRM_Utils_Hook::upgrade('enqueue', $queue);
diff --git a/CRM/Financial/BAO/ExportFormat.php b/CRM/Financial/BAO/ExportFormat.php
index 438efb682f60..1f465383698b 100644
--- a/CRM/Financial/BAO/ExportFormat.php
+++ b/CRM/Financial/BAO/ExportFormat.php
@@ -1,9 +1,9 @@
_isDownloadFile) {
+ return NULL;
+ }
$config = CRM_Core_Config::singleton();
// zip files if more than one.
if (count($this->_downloadFile) > 1) {
@@ -153,7 +163,8 @@ public function initiateDownload() {
ob_clean();
flush();
readfile($config->customFileUploadDir . CRM_Utils_File::cleanFileName(basename($zip)));
- unlink($zip); //delete the zip to avoid clutter.
+ //delete the zip to avoid clutter.
+ unlink($zip);
CRM_Utils_System::civiExit();
}
}
@@ -176,8 +187,8 @@ public function initiateDownload() {
*/
public static function createActivityExport($batchIds, $fileName) {
$session = CRM_Core_Session::singleton();
- $values = array();
- $params = array('id' => $batchIds);
+ $values = [];
+ $params = ['id' => $batchIds];
CRM_Batch_BAO_Batch::retrieve($params, $values);
$createdBy = CRM_Contact_BAO_Contact::displayName($values['created_id']);
$modifiedBy = CRM_Contact_BAO_Contact::displayName($values['modified_id']);
@@ -199,7 +210,7 @@ public static function createActivityExport($batchIds, $fileName) {
// create activity.
$subject .= ' ' . ts('Batch') . '[' . $values['title'] . ']';
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
- $activityParams = array(
+ $activityParams = [
'activity_type_id' => array_search('Export Accounting Batch', $activityTypes),
'subject' => $subject,
'status_id' => 2,
@@ -208,13 +219,13 @@ public static function createActivityExport($batchIds, $fileName) {
'source_record_id' => $values['id'],
'target_contact_id' => $session->get('userID'),
'details' => $details,
- 'attachFile_1' => array(
+ 'attachFile_1' => [
'uri' => $fileName,
'type' => 'text/csv',
'location' => $fileName,
'upload_date' => date('YmdHis'),
- ),
- );
+ ],
+ ];
CRM_Activity_BAO_Activity::create($activityParams);
}
@@ -226,12 +237,12 @@ public static function createActivityExport($batchIds, $fileName) {
*
* @return bool
*/
- public function createZip($files = array(), $destination = NULL, $overwrite = FALSE) {
+ public function createZip($files = [], $destination = NULL, $overwrite = FALSE) {
// if the zip file already exists and overwrite is false, return false
if (file_exists($destination) && !$overwrite) {
return FALSE;
}
- $valid_files = array();
+ $valid_files = [];
if (is_array($files)) {
foreach ($files as $file) {
// make sure the file exists
@@ -242,7 +253,7 @@ public function createZip($files = array(), $destination = NULL, $overwrite = FA
}
if (count($validFiles)) {
$zip = new ZipArchive();
- if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== TRUE) {
+ if ($zip->open($destination, $overwrite ? ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== TRUE) {
return FALSE;
}
foreach ($validFiles as $file) {
diff --git a/CRM/Financial/BAO/ExportFormat/CSV.php b/CRM/Financial/BAO/ExportFormat/CSV.php
index fcb0d05c349b..c38c11ca9b84 100644
--- a/CRM/Financial/BAO/ExportFormat/CSV.php
+++ b/CRM/Financial/BAO/ExportFormat/CSV.php
@@ -1,9 +1,9 @@
array($batchId, 'String'));
+ $params = [1 => [$batchId, 'String']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
return $dao;
@@ -160,7 +161,7 @@ public function putFile($export) {
*/
public function formatHeaders($values) {
$arrayKeys = array_keys($values);
- $headers = '';
+ $headers = [];
if (!empty($arrayKeys)) {
foreach ($values[$arrayKeys[0]] as $title => $value) {
$headers[] = $title;
@@ -179,11 +180,10 @@ public function makeExport($export) {
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
foreach ($export as $batchId => $dao) {
- $financialItems = array();
+ $financialItems = [];
$this->_batchIds = $batchId;
- $batchItems = array();
- $queryResults = array();
+ $queryResults = [];
while ($dao->fetch()) {
$creditAccountName = $creditAccountType = $creditAccount = NULL;
@@ -200,7 +200,7 @@ public function makeExport($export) {
$invoiceNo = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $dao->contribution_id;
- $financialItems[] = array(
+ $financialItems[] = [
'Batch ID' => $dao->batch_id,
'Invoice No' => $invoiceNo,
'Contact ID' => $dao->contact_id,
@@ -222,14 +222,13 @@ public function makeExport($export) {
'Credit Account Name' => $creditAccountName,
'Credit Account Type' => $creditAccountType,
'Item Description' => $dao->item_description,
- );
+ ];
end($financialItems);
- $batchItems[] = &$financialItems[key($financialItems)];
$queryResults[] = get_object_vars($dao);
}
- CRM_Utils_Hook::batchItems($queryResults, $batchItems);
+ CRM_Utils_Hook::batchItems($queryResults, $financialItems);
$financialItems['headers'] = self::formatHeaders($financialItems);
self::export($financialItems);
diff --git a/CRM/Financial/BAO/ExportFormat/IIF.php b/CRM/Financial/BAO/ExportFormat/IIF.php
index b6ab465cf889..71c615394899 100644
--- a/CRM/Financial/BAO/ExportFormat/IIF.php
+++ b/CRM/Financial/BAO/ExportFormat/IIF.php
@@ -1,9 +1,9 @@
array($batchId, 'String'));
+ $params = [1 => [$batchId, 'String']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
return $dao;
@@ -165,47 +167,47 @@ public function makeExport($export) {
// include those in the output. Only want to include ones used in the batch, not everything in the db,
// since would increase the chance of messing up user's existing Quickbooks entries.
foreach ($export as $batchId => $dao) {
- $accounts = $contacts = $journalEntries = $exportParams = array();
+ $accounts = $contacts = $journalEntries = $exportParams = [];
$this->_batchIds = $batchId;
while ($dao->fetch()) {
// add to running list of accounts
if (!empty($dao->from_account_id) && !isset($accounts[$dao->from_account_id])) {
- $accounts[$dao->from_account_id] = array(
+ $accounts[$dao->from_account_id] = [
'name' => $this->format($dao->from_account_name),
'account_code' => $this->format($dao->from_account_code),
'description' => $this->format($dao->from_account_description),
'type' => $this->format($dao->from_account_type_code),
- );
+ ];
}
if (!empty($dao->to_account_id) && !isset($accounts[$dao->to_account_id])) {
- $accounts[$dao->to_account_id] = array(
+ $accounts[$dao->to_account_id] = [
'name' => $this->format($dao->to_account_name),
'account_code' => $this->format($dao->to_account_code),
'description' => $this->format($dao->to_account_description),
'type' => $this->format($dao->to_account_type_code),
- );
+ ];
}
// add to running list of contacts
if (!empty($dao->contact_from_id) && !isset($contacts[$dao->contact_from_id])) {
- $contacts[$dao->contact_from_id] = array(
+ $contacts[$dao->contact_from_id] = [
'name' => $this->format($dao->contact_from_name),
'first_name' => $this->format($dao->contact_from_first_name),
'last_name' => $this->format($dao->contact_from_last_name),
- );
+ ];
}
if (!empty($dao->contact_to_id) && !isset($contacts[$dao->contact_to_id])) {
- $contacts[$dao->contact_to_id] = array(
+ $contacts[$dao->contact_to_id] = [
'name' => $this->format($dao->contact_to_name),
'first_name' => $this->format($dao->contact_to_first_name),
'last_name' => $this->format($dao->contact_to_last_name),
- );
+ ];
}
// set up the journal entries for this financial trxn
- $journalEntries[$dao->financial_trxn_id] = array(
- 'to_account' => array(
+ $journalEntries[$dao->financial_trxn_id] = [
+ 'to_account' => [
'trxn_date' => $this->format($dao->trxn_date, 'date'),
'trxn_id' => $this->format($dao->trxn_id),
'account_name' => $this->format($dao->to_account_name),
@@ -213,9 +215,9 @@ public function makeExport($export) {
'contact_name' => $this->format($dao->contact_to_name),
'payment_instrument' => $this->format($dao->payment_instrument),
'check_number' => $this->format($dao->check_number),
- ),
- 'splits' => array(),
- );
+ ],
+ 'splits' => [],
+ ];
/*
* splits has two possibilities depending on FROM account
@@ -249,30 +251,30 @@ public function makeExport($export) {
WHERE eft.entity_table = 'civicrm_financial_item'
AND eft.financial_trxn_id = %1";
- $itemParams = array(1 => array($dao->financial_trxn_id, 'Integer'));
+ $itemParams = [1 => [$dao->financial_trxn_id, 'Integer']];
$itemDAO = CRM_Core_DAO::executeQuery($item_sql, $itemParams);
while ($itemDAO->fetch()) {
// add to running list of accounts
if (!empty($itemDAO->account_id) && !isset($accounts[$itemDAO->account_id])) {
- $accounts[$itemDAO->account_id] = array(
+ $accounts[$itemDAO->account_id] = [
'name' => $this->format($itemDAO->account_name),
'account_code' => $this->format($itemDAO->account_code),
'description' => $this->format($itemDAO->account_description),
'type' => $this->format($itemDAO->account_type_code),
- );
+ ];
}
if (!empty($itemDAO->contact_id) && !isset($contacts[$itemDAO->contact_id])) {
- $contacts[$itemDAO->contact_id] = array(
+ $contacts[$itemDAO->contact_id] = [
'name' => $this->format($itemDAO->contact_name),
'first_name' => $this->format($itemDAO->contact_first_name),
'last_name' => $this->format($itemDAO->contact_last_name),
- );
+ ];
}
// add split line for this item
- $journalEntries[$dao->financial_trxn_id]['splits'][$itemDAO->financial_item_id] = array(
+ $journalEntries[$dao->financial_trxn_id]['splits'][$itemDAO->financial_item_id] = [
'trxn_date' => $this->format($itemDAO->transaction_date, 'date'),
'spl_id' => $this->format($itemDAO->financial_item_id),
'account_name' => $this->format($itemDAO->account_name),
@@ -282,13 +284,12 @@ public function makeExport($export) {
'description' => $this->format($itemDAO->description),
'check_number' => $this->format($itemDAO->check_number),
'currency' => $this->format($itemDAO->currency),
- );
+ ];
} // end items loop
- $itemDAO->free();
}
else {
// In this case, split record just uses the FROM account from the trxn, and there's only one record here
- $journalEntries[$dao->financial_trxn_id]['splits'][] = array(
+ $journalEntries[$dao->financial_trxn_id]['splits'][] = [
'trxn_date' => $this->format($dao->trxn_date, 'date'),
'spl_id' => $this->format($dao->financial_trxn_id),
'account_name' => $this->format($dao->from_account_name),
@@ -298,14 +299,14 @@ public function makeExport($export) {
'payment_instrument' => $this->format($dao->payment_instrument),
'check_number' => $this->format($dao->check_number),
'currency' => $this->format($dao->currency),
- );
+ ];
}
}
- $exportParams = array(
+ $exportParams = [
'accounts' => $accounts,
'contacts' => $contacts,
'journalEntries' => $journalEntries,
- );
+ ];
self::export($exportParams);
}
parent::initiateDownload();
diff --git a/CRM/Financial/BAO/FinancialAccount.php b/CRM/Financial/BAO/FinancialAccount.php
index 5b321634d8ce..02ff4d9de89d 100644
--- a/CRM/Financial/BAO/FinancialAccount.php
+++ b/CRM/Financial/BAO/FinancialAccount.php
@@ -1,9 +1,9 @@
contribution_status_id == array_search('Partially paid', $contributionStatuses)) {
$itemStatus = array_search('Partially paid', $financialItemStatus);
}
- $params = array(
+ $params = [
'transaction_date' => CRM_Utils_Date::isoToMysql($contribution->receive_date),
'contact_id' => $contribution->contact_id,
'amount' => $lineItem->line_total,
@@ -98,7 +98,7 @@ public static function add($lineItem, $contribution, $taxTrxnID = FALSE, $trxnId
'entity_id' => $lineItem->id,
'description' => ($lineItem->qty != 1 ? $lineItem->qty . ' of ' : '') . $lineItem->label,
'status_id' => $itemStatus,
- );
+ ];
if ($taxTrxnID) {
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
@@ -114,7 +114,7 @@ public static function add($lineItem, $contribution, $taxTrxnID = FALSE, $trxnId
}
}
if ($lineItem->financial_type_id) {
- $params['financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
+ $params['financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
$lineItem->financial_type_id,
$accountRelName
);
@@ -161,15 +161,15 @@ public static function create(&$params, $ids = NULL, $trxnIds = NULL) {
$financialtrxnIDS = CRM_Utils_Array::value('id', $trxnIds);
if (!empty($financialtrxnIDS)) {
if (!is_array($financialtrxnIDS)) {
- $financialtrxnIDS = array($financialtrxnIDS);
+ $financialtrxnIDS = [$financialtrxnIDS];
}
foreach ($financialtrxnIDS as $tID) {
- $entity_financial_trxn_params = array(
+ $entity_financial_trxn_params = [
'entity_table' => "civicrm_financial_item",
'entity_id' => $financialItem->id,
'financial_trxn_id' => $tID,
'amount' => $params['amount'],
- );
+ ];
if (!empty($ids['entityFinancialTrxnId'])) {
$entity_financial_trxn_params['id'] = $ids['entityFinancialTrxnId'];
}
@@ -189,9 +189,9 @@ public static function create(&$params, $ids = NULL, $trxnIds = NULL) {
* Takes an associative array and creates a entity financial transaction object.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * an assoc array of name/value pairs.
*
- * @return CRM_Core_BAO_FinancialTrxn
+ * @return CRM_Financial_DAO_EntityFinancialTrxn
*/
public static function createEntityTrxn($params) {
$entity_trxn = new CRM_Financial_DAO_EntityFinancialTrxn();
@@ -204,9 +204,9 @@ public static function createEntityTrxn($params) {
* Retrive entity financial trxn details.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * an assoc array of name/value pairs.
* @param bool $maxId
- * To retrive max id.
+ * To retrieve max id.
*
* @return array
*/
@@ -220,13 +220,13 @@ public static function retrieveEntityFinancialTrxn($params, $maxId = FALSE) {
}
$financialItem->find();
while ($financialItem->fetch()) {
- $financialItems[$financialItem->id] = array(
+ $financialItems[$financialItem->id] = [
'id' => $financialItem->id,
'entity_table' => $financialItem->entity_table,
'entity_id' => $financialItem->entity_id,
'financial_trxn_id' => $financialItem->financial_trxn_id,
'amount' => $financialItem->amount,
- );
+ ];
}
if (!empty($financialItems)) {
return $financialItems;
@@ -247,7 +247,7 @@ public static function retrieveEntityFinancialTrxn($params, $maxId = FALSE) {
* @param array $error
* Error to display.
*
- * @return array
+ * @return array|bool
*/
public static function checkContactPresent($contactIds, &$error) {
if (empty($contactIds)) {
@@ -286,17 +286,17 @@ public static function checkContactPresent($contactIds, &$error) {
*
* @param int $entityId
*
- * @return object CRM_Core_DAO
+ * @return array
*/
public static function getPreviousFinancialItem($entityId) {
- $params = array(
+ $params = [
'entity_id' => $entityId,
'entity_table' => 'civicrm_line_item',
- 'options' => array('limit' => 1, 'sort' => 'id DESC'),
- );
- $salesTaxFinancialAccounts = civicrm_api3('FinancialAccount', 'get', array('is_tax' => 1));
+ 'options' => ['limit' => 1, 'sort' => 'id DESC'],
+ ];
+ $salesTaxFinancialAccounts = civicrm_api3('FinancialAccount', 'get', ['is_tax' => 1]);
if ($salesTaxFinancialAccounts['count']) {
- $params['financial_account_id'] = array('NOT IN' => array_keys($salesTaxFinancialAccounts['values']));
+ $params['financial_account_id'] = ['NOT IN' => array_keys($salesTaxFinancialAccounts['values'])];
}
return civicrm_api3('FinancialItem', 'getsingle', $params);
}
diff --git a/CRM/Financial/BAO/FinancialType.php b/CRM/Financial/BAO/FinancialType.php
index b8a95c53d328..1d49d6193199 100644
--- a/CRM/Financial/BAO/FinancialType.php
+++ b/CRM/Financial/BAO/FinancialType.php
@@ -1,9 +1,9 @@
id = $financialTypeId;
$financialType->find(TRUE);
- // tables to ingore checks for financial_type_id
- $ignoreTables = array('CRM_Financial_DAO_EntityFinancialAccount');
+ // tables to ignore checks for financial_type_id
+ $ignoreTables = ['CRM_Financial_DAO_EntityFinancialAccount'];
// TODO: if (!$financialType->find(true)) {
// ensure that we have no objects that have an FK to this financial type id TODO: that cannot be null
$occurrences = $financialType->findReferences();
if ($occurrences) {
- $tables = array();
+ $tables = [];
foreach ($occurrences as $occurrence) {
$className = get_class($occurrence);
if (!in_array($className, $tables) && !in_array($className, $ignoreTables)) {
@@ -155,9 +153,9 @@ public static function del($financialTypeId) {
}
}
if (!empty($tables)) {
- $message = ts('The following tables have an entry for this financial type: %1', array('%1' => implode(', ', $tables)));
+ $message = ts('The following tables have an entry for this financial type: %1', ['%1' => implode(', ', $tables)]);
- $errors = array();
+ $errors = [];
$errors['is_error'] = 1;
$errors['error_message'] = $message;
return $errors;
@@ -184,7 +182,7 @@ public static function del($financialTypeId) {
public static function getIncomeFinancialType() {
// Financial Type
$financialType = CRM_Contribute_PseudoConstant::financialType();
- $revenueFinancialType = array();
+ $revenueFinancialType = [];
$relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
CRM_Core_PseudoConstant::populate(
$revenueFinancialType,
@@ -220,14 +218,14 @@ public static function permissionedFinancialTypes(&$permissions, $descriptions)
}
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
$prefix = ts('CiviCRM') . ': ';
- $actions = array('add', 'view', 'edit', 'delete');
+ $actions = ['add', 'view', 'edit', 'delete'];
foreach ($financialTypes as $id => $type) {
foreach ($actions as $action) {
if ($descriptions) {
- $permissions[$action . ' contributions of type ' . $type] = array(
+ $permissions[$action . ' contributions of type ' . $type] = [
$prefix . ts($action . ' contributions of type ') . $type,
ts(ucfirst($action) . ' contributions of type ') . $type,
- );
+ ];
}
else {
$permissions[$action . ' contributions of type ' . $type] = $prefix . ts($action . ' contributions of type ') . $type;
@@ -238,10 +236,10 @@ public static function permissionedFinancialTypes(&$permissions, $descriptions)
$permissions['administer CiviCRM Financial Types'] = $prefix . ts('administer CiviCRM Financial Types');
}
else {
- $permissions['administer CiviCRM Financial Types'] = array(
+ $permissions['administer CiviCRM Financial Types'] = [
$prefix . ts('administer CiviCRM Financial Types'),
ts('Administer access to Financial Types'),
- );
+ ];
}
}
@@ -298,24 +296,23 @@ public static function getAvailableFinancialTypes(&$financialTypes = NULL, $acti
if (!self::isACLFinancialTypeStatus()) {
return $financialTypes;
}
- $actions = array(
+ $actions = [
CRM_Core_Action::VIEW => 'view',
CRM_Core_Action::UPDATE => 'edit',
CRM_Core_Action::ADD => 'add',
CRM_Core_Action::DELETE => 'delete',
- );
- // check cached value
- if (CRM_Utils_Array::value($action, self::$_availableFinancialTypes) && !$resetCache) {
- $financialTypes = self::$_availableFinancialTypes[$action];
- return self::$_availableFinancialTypes[$action];
- }
- foreach ($financialTypes as $finTypeId => $type) {
- if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $type)) {
- unset($financialTypes[$finTypeId]);
+ ];
+
+ if (!isset(\Civi::$statics[__CLASS__]['available_types_' . $action])) {
+ foreach ($financialTypes as $finTypeId => $type) {
+ if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $type)) {
+ unset($financialTypes[$finTypeId]);
+ }
}
+ \Civi::$statics[__CLASS__]['available_types_' . $action] = $financialTypes;
}
- self::$_availableFinancialTypes[$action] = $financialTypes;
- return $financialTypes;
+ $financialTypes = \Civi::$statics[__CLASS__]['available_types_' . $action];
+ return \Civi::$statics[__CLASS__]['available_types_' . $action];
}
/**
@@ -335,12 +332,12 @@ public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $ac
if (!self::isACLFinancialTypeStatus()) {
return $membershipTypes;
}
- $actions = array(
+ $actions = [
CRM_Core_Action::VIEW => 'view',
CRM_Core_Action::UPDATE => 'edit',
CRM_Core_Action::ADD => 'add',
CRM_Core_Action::DELETE => 'delete',
- );
+ ];
foreach ($membershipTypes as $memTypeId => $type) {
$finTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memTypeId, 'financial_type_id');
$finType = CRM_Contribute_PseudoConstant::financialType($finTypeId);
@@ -351,6 +348,26 @@ public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $ac
return $membershipTypes;
}
+ /**
+ * This function adds the Financial ACL clauses to the where clause.
+ *
+ * This is currently somewhat mocking the native hook implementation
+ * for the acls that are in core. If the financialaclreport extension is installed
+ * core acls are not applied as that would result in them being applied twice.
+ *
+ * Long term we should either consolidate the financial acls in core or use only the extension.
+ * Both require substantial clean up before implementing and by the time the code is clean enough to
+ * take the final step we should
+ * be able to implement by removing one half of the other of this function.
+ *
+ * @param array $whereClauses
+ */
+ public static function addACLClausesToWhereClauses(&$whereClauses) {
+ $contributionBAO = new CRM_Contribute_BAO_Contribution();
+ $whereClauses = array_merge($whereClauses, $contributionBAO->addSelectWhereClause());
+
+ }
+
/**
* Function to build a permissioned sql where clause based on available financial types.
*
@@ -363,6 +380,7 @@ public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $ac
*
*/
public static function buildPermissionedClause(&$whereClauses, $component = NULL, $alias = NULL) {
+ // @todo the relevant addSelectWhere clause should be called.
if (!self::isACLFinancialTypeStatus()) {
return FALSE;
}
@@ -459,15 +477,17 @@ public static function checkPermissionToEditFinancialType($financialTypeID) {
* @return bool
*/
public static function isACLFinancialTypeStatus() {
- if (array_key_exists('acl_financial_type', self::$_statusACLFt)) {
- return self::$_statusACLFt['acl_financial_type'];
- }
- $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
- self::$_statusACLFt['acl_financial_type'] = FALSE;
- if (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
- self::$_statusACLFt['acl_financial_type'] = TRUE;
+ if (!isset(\Civi::$statics[__CLASS__]['is_acl_enabled'])) {
+ \Civi::$statics[__CLASS__]['is_acl_enabled'] = FALSE;
+ $realSetting = \Civi::$statics[__CLASS__]['is_acl_enabled'] = Civi::settings()->get('acl_financial_type');
+ if (!$realSetting) {
+ $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
+ if (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
+ \Civi::$statics[__CLASS__]['is_acl_enabled'] = TRUE;
+ }
+ }
}
- return self::$_statusACLFt['acl_financial_type'];
+ return \Civi::$statics[__CLASS__]['is_acl_enabled'];
}
}
diff --git a/CRM/Financial/BAO/FinancialTypeAccount.php b/CRM/Financial/BAO/FinancialTypeAccount.php
index f26a3d9351d2..faa84e3f69f6 100644
--- a/CRM/Financial/BAO/FinancialTypeAccount.php
+++ b/CRM/Financial/BAO/FinancialTypeAccount.php
@@ -1,9 +1,9 @@
copyValues($params);
$financialTypeAccount->find();
@@ -105,16 +105,16 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $financialTypeAccountId, 'entity_id');
// check dependencies
// FIXME more table containing financial_type_id to come
- $dependency = array(
- array('Contribute', 'Contribution'),
- array('Contribute', 'ContributionPage'),
- array('Member', 'MembershipType'),
- array('Price', 'PriceFieldValue'),
- array('Grant', 'Grant'),
- array('Contribute', 'PremiumsProduct'),
- array('Contribute', 'Product'),
- array('Price', 'LineItem'),
- );
+ $dependency = [
+ ['Contribute', 'Contribution'],
+ ['Contribute', 'ContributionPage'],
+ ['Member', 'MembershipType'],
+ ['Price', 'PriceFieldValue'],
+ ['Grant', 'Grant'],
+ ['Contribute', 'PremiumsProduct'],
+ ['Contribute', 'Product'],
+ ['Price', 'LineItem'],
+ ];
foreach ($dependency as $name) {
$daoString = 'CRM_' . $name[0] . '_DAO_' . $name[1];
@@ -128,11 +128,11 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
if ($check) {
if ($name[1] == 'PremiumsProduct' || $name[1] == 'Product') {
- CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship while the Financial Type is used for a Premium.', array(1 => $relationValues[$financialTypeAccountId])));
+ CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship while the Financial Type is used for a Premium.', [1 => $relationValues[$financialTypeAccountId]]));
}
else {
$accountRelationShipId = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_EntityFinancialAccount', $financialTypeAccountId, 'account_relationship');
- CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship because it is being referenced by one or more of the following types of records: Contributions, Contribution Pages, or Membership Types. Consider disabling this type instead if you no longer want it used.', array(1 => $relationValues[$accountRelationShipId])), NULL, 'error');
+ CRM_Core_Session::setStatus(ts('You cannot remove an account with a %1 relationship because it is being referenced by one or more of the following types of records: Contributions, Contribution Pages, or Membership Types. Consider disabling this type instead if you no longer want it used.', [1 => $relationValues[$accountRelationShipId]]), NULL, 'error');
}
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', "reset=1&action=browse&aid={$accountId}"));
}
@@ -142,7 +142,7 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
$financialType->id = $financialTypeAccountId;
$financialType->find(TRUE);
$financialType->delete();
- CRM_Core_Session::setStatus(ts('Unbalanced transactions may be created if you delete the account of type: %1.', array(1 => $relationValues[$financialType->account_relationship])));
+ CRM_Core_Session::setStatus(ts('Unbalanced transactions may be created if you delete the account of type: %1.', [1 => $relationValues[$financialType->account_relationship]]));
}
/**
@@ -154,17 +154,27 @@ public static function del($financialTypeAccountId, $accountId = NULL) {
* @return null|int
*/
public static function getInstrumentFinancialAccount($paymentInstrumentValue) {
- $paymentInstrument = civicrm_api3('OptionValue', 'getsingle', array(
- 'return' => array("id"),
- 'value' => $paymentInstrumentValue,
- 'option_group_id' => "payment_instrument",
- ));
- $financialAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
- $paymentInstrument['id'],
- NULL,
- 'civicrm_option_value'
- );
- return $financialAccountId;
+ if (!isset(\Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue])) {
+ $paymentInstrumentID = civicrm_api3('OptionValue', 'getvalue', [
+ 'return' => 'id',
+ 'value' => $paymentInstrumentValue,
+ 'option_group_id' => "payment_instrument",
+ ]);
+ $accounts = civicrm_api3('EntityFinancialAccount', 'get', [
+ 'return' => 'financial_account_id',
+ 'entity_table' => 'civicrm_option_value',
+ 'entity_id' => $paymentInstrumentID,
+ 'options' => ['limit' => 1],
+ 'sequential' => 1,
+ ])['values'];
+ if (empty($accounts)) {
+ \Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue] = NULL;
+ }
+ else {
+ \Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue] = $accounts[0]['financial_account_id'];
+ }
+ }
+ return \Civi::$statics[__CLASS__]['instrument_financial_accounts'][$paymentInstrumentValue];
}
/**
@@ -177,40 +187,40 @@ public static function getInstrumentFinancialAccount($paymentInstrumentValue) {
* @return array
*/
public static function createDefaultFinancialAccounts($financialType) {
- $titles = array();
+ $titles = [];
$financialAccountTypeID = CRM_Core_OptionGroup::values('financial_account_type', FALSE, FALSE, FALSE, NULL, 'name');
$accountRelationship = CRM_Core_OptionGroup::values('account_relationship', FALSE, FALSE, FALSE, NULL, 'name');
- $relationships = array(
+ $relationships = [
array_search('Accounts Receivable Account is', $accountRelationship) => array_search('Asset', $financialAccountTypeID),
array_search('Expense Account is', $accountRelationship) => array_search('Expenses', $financialAccountTypeID),
array_search('Cost of Sales Account is', $accountRelationship) => array_search('Cost of Sales', $financialAccountTypeID),
array_search('Income Account is', $accountRelationship) => array_search('Revenue', $financialAccountTypeID),
- );
+ ];
$dao = CRM_Core_DAO::executeQuery('SELECT id, financial_account_type_id FROM civicrm_financial_account WHERE name LIKE %1',
- array(1 => array($financialType->name, 'String'))
+ [1 => [$financialType->name, 'String']]
);
$dao->fetch();
- $existingFinancialAccount = array();
+ $existingFinancialAccount = [];
if (!$dao->N) {
- $params = array(
+ $params = [
'name' => $financialType->name,
'contact_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', CRM_Core_Config::domainID(), 'contact_id'),
'financial_account_type_id' => array_search('Revenue', $financialAccountTypeID),
'description' => $financialType->description,
'account_type_code' => 'INC',
'is_active' => 1,
- );
+ ];
$financialAccount = CRM_Financial_BAO_FinancialAccount::add($params);
}
else {
$existingFinancialAccount[$dao->financial_account_type_id] = $dao->id;
}
- $params = array(
+ $params = [
'entity_table' => 'civicrm_financial_type',
'entity_id' => $financialType->id,
- );
+ ];
foreach ($relationships as $key => $value) {
if (!array_key_exists($value, $existingFinancialAccount)) {
if ($accountRelationship[$key] == 'Accounts Receivable Account is') {
@@ -247,7 +257,7 @@ public static function createDefaultFinancialAccounts($financialType) {
self::add($params);
}
if (!empty($existingFinancialAccount)) {
- $titles = array();
+ $titles = [];
}
return $titles;
}
@@ -264,9 +274,9 @@ public static function validateRelationship($financialTypeAccount) {
$financialAccountType = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $financialTypeAccount->financial_account_id, 'financial_account_type_id');
if (CRM_Utils_Array::value($financialTypeAccount->account_relationship, $financialAccountLinks) != $financialAccountType) {
$accountRelationships = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
- $params = array(
+ $params = [
1 => $accountRelationships[$financialTypeAccount->account_relationship],
- );
+ ];
throw new CRM_Core_Exception(ts("This financial account cannot have '%1' relationship.", $params));
}
}
diff --git a/CRM/Financial/BAO/Payment.php b/CRM/Financial/BAO/Payment.php
new file mode 100644
index 000000000000..e743d2d79685
--- /dev/null
+++ b/CRM/Financial/BAO/Payment.php
@@ -0,0 +1,501 @@
+ $params['contribution_id']]);
+ $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($contribution['contribution_status_id'], 'name');
+
+ $isPaymentCompletesContribution = self::isPaymentCompletesContribution($params['contribution_id'], $params['total_amount']);
+
+ // For legacy reasons Pending payments are completed through completetransaction.
+ // @todo completetransaction should transition components but financial transactions
+ // should be handled through Payment.create.
+ $isSkipRecordingPaymentHereForLegacyHandlingReasons = ($contributionStatus == 'Pending' && $isPaymentCompletesContribution);
+
+ if (!$isSkipRecordingPaymentHereForLegacyHandlingReasons && $params['total_amount'] > 0) {
+ $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
+
+ if (CRM_Utils_Array::value('line_item', $params) && !empty($trxn)) {
+ foreach ($params['line_item'] as $values) {
+ foreach ($values as $id => $amount) {
+ $p = ['id' => $id];
+ $check = CRM_Price_BAO_LineItem::retrieve($p, $defaults);
+ if (empty($check)) {
+ throw new API_Exception('Please specify a valid Line Item.');
+ }
+ // get financial item
+ $sql = "SELECT fi.id
+ FROM civicrm_financial_item fi
+ INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
+ WHERE li.contribution_id = %1 AND li.id = %2";
+ $sqlParams = [
+ 1 => [$params['contribution_id'], 'Integer'],
+ 2 => [$id, 'Integer'],
+ ];
+ $fid = CRM_Core_DAO::singleValueQuery($sql, $sqlParams);
+ // Record Entity Financial Trxn
+ $eftParams = [
+ 'entity_table' => 'civicrm_financial_item',
+ 'financial_trxn_id' => $trxn->id,
+ 'amount' => $amount,
+ 'entity_id' => $fid,
+ ];
+ civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
+ }
+ }
+ }
+ elseif (!empty($trxn)) {
+ CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution['total_amount']);
+ }
+ }
+ elseif ($params['total_amount'] < 0) {
+ $trxn = self::recordRefundPayment($params['contribution_id'], $params, FALSE);
+ }
+
+ if ($isPaymentCompletesContribution) {
+ civicrm_api3('Contribution', 'completetransaction', ['id' => $contribution['id']]);
+ // Get the trxn
+ $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
+ $ftParams = ['id' => $trxnId['financialTrxnId']];
+ $trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams, CRM_Core_DAO::$_nullArray);
+ }
+ elseif ($contributionStatus === 'Pending') {
+ civicrm_api3('Contribution', 'create',
+ [
+ 'id' => $contribution['id'],
+ 'contribution_status_id' => 'Partially paid',
+ ]
+ );
+ }
+
+ return $trxn;
+ }
+
+ /**
+ * Send an email confirming a payment that has been received.
+ *
+ * @param array $params
+ *
+ * @return array
+ */
+ public static function sendConfirmation($params) {
+
+ $entities = self::loadRelatedEntities($params['id']);
+ $sendTemplateParams = [
+ 'groupName' => 'msg_tpl_workflow_contribution',
+ 'valueName' => 'payment_or_refund_notification',
+ 'PDFFilename' => ts('notification') . '.pdf',
+ 'contactId' => $entities['contact']['id'],
+ 'toName' => $entities['contact']['display_name'],
+ 'toEmail' => $entities['contact']['email'],
+ 'tplParams' => self::getConfirmationTemplateParameters($entities),
+ ];
+ return CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
+ }
+
+ /**
+ * Load entities related to the current payment id.
+ *
+ * This gives us all the data we need to send an email confirmation but avoiding
+ * getting anything not tested for the confirmations. We retrieve the 'full' event as
+ * it has been traditionally assigned in full.
+ *
+ * @param int $id
+ *
+ * @return array
+ * - contact = ['id' => x, 'display_name' => y, 'email' => z]
+ * - event = [.... full event details......]
+ * - contribution = ['id' => x],
+ * - payment = [payment info + payment summary info]
+ */
+ protected static function loadRelatedEntities($id) {
+ $entities = [];
+ $contributionID = (int) civicrm_api3('EntityFinancialTrxn', 'getvalue', [
+ 'financial_trxn_id' => $id,
+ 'entity_table' => 'civicrm_contribution',
+ 'return' => 'entity_id',
+ ]);
+ $entities['contribution'] = ['id' => $contributionID];
+ $entities['payment'] = array_merge(civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $id]),
+ CRM_Contribute_BAO_Contribution::getPaymentInfo($contributionID)
+ );
+
+ $contactID = self::getPaymentContactID($contributionID);
+ list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
+ $entities['contact'] = ['id' => $contactID, 'display_name' => $displayName, 'email' => $email];
+ $contact = civicrm_api3('Contact', 'getsingle', ['id' => $contactID, 'return' => 'email_greeting']);
+ $entities['contact']['email_greeting'] = $contact['email_greeting_display'];
+
+ $participantRecords = civicrm_api3('ParticipantPayment', 'get', [
+ 'contribution_id' => $contributionID,
+ 'api.Participant.get' => ['return' => 'event_id'],
+ 'sequential' => 1,
+ ])['values'];
+ if (!empty($participantRecords)) {
+ $entities['event'] = civicrm_api3('Event', 'getsingle', ['id' => $participantRecords[0]['api.Participant.get']['values'][0]['event_id']]);
+ if (!empty($entities['event']['is_show_location'])) {
+ $locationParams = [
+ 'entity_id' => $entities['event']['id'],
+ 'entity_table' => 'civicrm_event',
+ ];
+ $entities['location'] = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
+ }
+ }
+
+ return $entities;
+ }
+
+ /**
+ * @param int $contributionID
+ *
+ * @return int
+ */
+ public static function getPaymentContactID($contributionID) {
+ $contribution = civicrm_api3('Contribution', 'getsingle', [
+ 'id' => $contributionID ,
+ 'return' => ['contact_id'],
+ ]);
+ return (int) $contribution['contact_id'];
+ }
+
+ /**
+ * @param array $entities
+ * Related entities as an array keyed by the various entities.
+ *
+ * @return array
+ * Values required for the notification
+ * - contact_id
+ * - template_variables
+ * - event (DAO of event if relevant)
+ */
+ public static function getConfirmationTemplateParameters($entities) {
+ $templateVariables = [
+ 'contactDisplayName' => $entities['contact']['display_name'],
+ 'emailGreeting' => $entities['contact']['email_greeting'],
+ 'totalAmount' => $entities['payment']['total'],
+ 'amountOwed' => $entities['payment']['balance'],
+ 'totalPaid' => $entities['payment']['paid'],
+ 'paymentAmount' => $entities['payment']['total_amount'],
+ 'checkNumber' => CRM_Utils_Array::value('check_number', $entities['payment']),
+ 'receive_date' => $entities['payment']['trxn_date'],
+ 'paidBy' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $entities['payment']['payment_instrument_id']),
+ 'isShowLocation' => (!empty($entities['event']) ? $entities['event']['is_show_location'] : FALSE),
+ 'location' => CRM_Utils_Array::value('location', $entities),
+ 'event' => CRM_Utils_Array::value('event', $entities),
+ 'component' => (!empty($entities['event']) ? 'event' : 'contribution'),
+ 'isRefund' => $entities['payment']['total_amount'] < 0,
+ 'isAmountzero' => $entities['payment']['total_amount'] === 0,
+ 'refundAmount' => ($entities['payment']['total_amount'] < 0 ? $entities['payment']['total_amount'] : NULL),
+ 'paymentsComplete' => ($entities['payment']['balance'] == 0),
+ ];
+
+ return self::filterUntestedTemplateVariables($templateVariables);
+ }
+
+ /**
+ * Filter out any untested variables.
+ *
+ * This just serves to highlight if any variables are added without a unit test also being added.
+ *
+ * (if hit then add a unit test for the param & add to this array).
+ *
+ * @param array $params
+ *
+ * @return array
+ */
+ public static function filterUntestedTemplateVariables($params) {
+ $testedTemplateVariables = [
+ 'contactDisplayName',
+ 'totalAmount',
+ 'amountOwed',
+ 'paymentAmount',
+ 'event',
+ 'component',
+ 'checkNumber',
+ 'receive_date',
+ 'paidBy',
+ 'isShowLocation',
+ 'location',
+ 'isRefund',
+ 'isAmountzero',
+ 'refundAmount',
+ 'totalPaid',
+ 'paymentsComplete',
+ 'emailGreeting',
+ ];
+ // These are assigned by the payment form - they still 'get through' from the
+ // form for now without being in here but we should ideally load
+ // and assign. Note we should update the tpl to use {if $billingName}
+ // and ditch contributeMode - although it might need to be deprecated rather than removed.
+ $todoParams = [
+ 'contributeMode',
+ 'billingName',
+ 'address',
+ 'credit_card_type',
+ 'credit_card_number',
+ 'credit_card_exp_date',
+ ];
+ $filteredParams = [];
+ foreach ($testedTemplateVariables as $templateVariable) {
+ // This will cause an a-notice if any are NOT set - by design. Ensuring
+ // they are set prevents leakage.
+ $filteredParams[$templateVariable] = $params[$templateVariable];
+ }
+ return $filteredParams;
+ }
+
+ /**
+ * @param $contributionId
+ * @param $trxnData
+ * @param $updateStatus
+ * - deprecate this param
+ *
+ * @todo - make this protected once recordAdditionalPayment no longer calls it.
+ *
+ * @return CRM_Financial_DAO_FinancialTrxn
+ */
+ public static function recordRefundPayment($contributionId, $trxnData, $updateStatus) {
+ list($contributionDAO, $params) = self::getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId);
+
+ $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
+
+ $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
+ $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
+ $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+
+ $trxnData['total_amount'] = $trxnData['net_amount'] = $trxnData['total_amount'];
+ $trxnData['from_financial_account_id'] = $arAccountId;
+ $trxnData['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
+ // record the entry
+ $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
+
+ // note : not using the self::add method,
+ // the reason because it performs 'status change' related code execution for financial records
+ // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
+ // are coded below i.e. just updating financial_item status to 'Paid'
+ if ($updateStatus) {
+ CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
+ }
+ // add financial item entry
+ $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionDAO->id);
+ if (!empty($lineItems)) {
+ foreach ($lineItems as $lineItemId => $lineItemValue) {
+ // don't record financial item for cancelled line-item
+ if ($lineItemValue['qty'] == 0) {
+ continue;
+ }
+ $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount / $contributionDAO->total_amount);
+ $addFinancialEntry = [
+ 'transaction_date' => $financialTrxn->trxn_date,
+ 'contact_id' => $contributionDAO->contact_id,
+ 'amount' => round($paid, 2),
+ 'currency' => $contributionDAO->currency,
+ 'status_id' => $paidStatus,
+ 'entity_id' => $lineItemId,
+ 'entity_table' => 'civicrm_line_item',
+ ];
+ $trxnIds = ['id' => $financialTrxn->id];
+ CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
+ }
+ }
+ return $financialTrxn;
+ }
+
+ /**
+ * @param int $contributionId
+ * @param array $trxnData
+ * @param int $participantId
+ *
+ * @return \CRM_Core_BAO_FinancialTrxn
+ */
+ public static function recordPayment($contributionId, $trxnData, $participantId) {
+ list($contributionDAO, $params) = self::getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId);
+
+ $trxnData['trxn_date'] = !empty($trxnData['trxn_date']) ? $trxnData['trxn_date'] : date('YmdHis');
+ $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
+
+ $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
+ $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
+ $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
+
+ $params['partial_payment_total'] = $contributionDAO->total_amount;
+ $params['partial_amount_to_pay'] = $trxnData['total_amount'];
+ $trxnData['net_amount'] = !empty($trxnData['net_amount']) ? $trxnData['net_amount'] : $trxnData['total_amount'];
+ $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $trxnData);
+ $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $trxnData);
+ $params['check_number'] = CRM_Utils_Array::value('check_number', $trxnData);
+
+ // record the entry
+ $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
+ $toFinancialAccount = $arAccountId;
+ $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
+ if (!empty($trxnId)) {
+ $trxnId = $trxnId['trxn_id'];
+ }
+ elseif (!empty($contributionDAO->payment_instrument_id)) {
+ $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
+ }
+ else {
+ $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
+ $queryParams = [1 => [$relationTypeId, 'Integer']];
+ $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
+ }
+
+ // update statuses
+ // criteria for updates contribution total_amount == financial_trxns of partial_payments
+ $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
+FROM civicrm_financial_trxn ft
+LEFT JOIN civicrm_entity_financial_trxn eft
+ ON (ft.id = eft.financial_trxn_id)
+WHERE eft.entity_table = 'civicrm_contribution'
+ AND eft.entity_id = {$contributionId}
+ AND ft.to_financial_account_id != {$toFinancialAccount}
+ AND ft.status_id = {$completedStatusId}
+";
+ $query = CRM_Core_DAO::executeQuery($sql);
+ $query->fetch();
+ $sumOfPayments = $query->sum_of_payments;
+
+ // update statuses
+ if ($contributionDAO->total_amount == $sumOfPayments) {
+ // update contribution status and
+ // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
+ $contributionDAO->contribution_status_id = $completedStatusId;
+ $contributionDAO->cancel_date = 'null';
+ $contributionDAO->cancel_reason = NULL;
+ $netAmount = !empty($trxnData['net_amount']) ? NULL : $trxnData['total_amount'];
+ $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
+ $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
+ $contributionDAO->save();
+
+ //Change status of financial record too
+ $financialTrxn->status_id = $completedStatusId;
+ $financialTrxn->save();
+
+ // note : not using the self::add method,
+ // the reason because it performs 'status change' related code execution for financial records
+ // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
+ // are coded below i.e. just updating financial_item status to 'Paid'
+
+ if (!$participantId) {
+ $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
+ }
+ if ($participantId) {
+ // update participant status
+ $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
+ $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
+ foreach ($ids as $val) {
+ $participantUpdate['id'] = $val;
+ $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
+ CRM_Event_BAO_Participant::add($participantUpdate);
+ }
+ }
+
+ // Remove this - completeOrder does it.
+ CRM_Contribute_BAO_Contribution::updateMembershipBasedOnCompletionOfContribution(
+ $contributionDAO,
+ $contributionId,
+ $trxnData['trxn_date']
+ );
+
+ // update financial item statuses
+ $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
+ $sqlFinancialItemUpdate = "
+UPDATE civicrm_financial_item fi
+ LEFT JOIN civicrm_entity_financial_trxn eft
+ ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
+SET status_id = {$paidStatus}
+WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
+";
+ CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
+ }
+ return $financialTrxn;
+ }
+
+ /**
+ * The recordFinancialTransactions function has capricious requirements for input parameters - load them.
+ *
+ * The function needs rework but for now we need to give it what it wants.
+ *
+ * @param int $contributionId
+ *
+ * @return array
+ */
+ protected static function getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId) {
+ $getInfoOf['id'] = $contributionId;
+ $defaults = [];
+ $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
+
+ // build params for recording financial trxn entry
+ $params['contribution'] = $contributionDAO;
+ $params = array_merge($defaults, $params);
+ $params['skipLineItem'] = TRUE;
+ return [$contributionDAO, $params];
+ }
+
+ /**
+ * Does this payment complete the contribution
+ *
+ * @param int $contributionID
+ * @param float $paymentAmount
+ *
+ * @return bool
+ */
+ protected static function isPaymentCompletesContribution($contributionID, $paymentAmount) {
+ $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID);
+ $cmp = bccomp($paymentAmount, $outstandingBalance, 5);
+ return ($cmp == 0 || $cmp == 1);
+ }
+
+}
diff --git a/CRM/Financial/BAO/PaymentProcessor.php b/CRM/Financial/BAO/PaymentProcessor.php
index 250d35a9a42f..fbf922c7c695 100644
--- a/CRM/Financial/BAO/PaymentProcessor.php
+++ b/CRM/Financial/BAO/PaymentProcessor.php
@@ -1,9 +1,9 @@
'civicrm_payment_processor',
'entity_id' => $processor->id,
'account_relationship' => $relationTypeId,
'financial_account_id' => $params['financial_account_id'],
- );
+ ];
CRM_Financial_BAO_FinancialTypeAccount::add($values);
}
@@ -116,7 +117,7 @@ public static function getCreditCards($paymentProcessorID = NULL) {
$cards = json_decode($processor->accepted_credit_cards, TRUE);
return $cards;
}
- return array();
+ return [];
}
/**
@@ -150,9 +151,8 @@ public static function retrieve(&$params, &$defaults) {
* @param bool $is_active
* Value we want to set the is_active field.
*
- * @return CRM_Financial_DAO_PaymentProcessor|null
- * 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) {
return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_PaymentProcessor', $id, 'is_active', $is_active);
@@ -167,8 +167,8 @@ public static function setIsActive($id, $is_active) {
*/
public static function &getDefault() {
if (self::$_defaultPaymentProcessor == NULL) {
- $params = array('is_default' => 1);
- $defaults = array();
+ $params = ['is_default' => 1];
+ $defaults = [];
self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
}
return self::$_defaultPaymentProcessor;
@@ -216,36 +216,8 @@ public static function del($paymentProcessorID) {
* associated array with payment processor related fields
*/
public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
- $capabilities = ($mode == 'test') ? array('TestMode') : array();
- $processors = self::getPaymentProcessors($capabilities, array($paymentProcessorID));
- $processor = $processors[$paymentProcessorID];
- $fields = array(
- 'id',
- 'name',
- 'payment_processor_type_id',
- 'user_name',
- 'password',
- 'signature',
- 'url_site',
- 'url_api',
- 'url_recur',
- 'url_button',
- 'subject',
- 'class_name',
- 'is_recur',
- 'billing_mode',
- 'is_test',
- 'payment_type',
- 'is_default',
- );
- // Just to prevent e-Notices elsewhere we set all fields.
- foreach ($fields as $name) {
- if (!isset($processor)) {
- $processor[$name] = NULL;
- }
- }
- $processor['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE,
- $processor['payment_processor_type_id'], 'name');
+ $capabilities = ($mode == 'test') ? ['TestMode'] : [];
+ $processors = self::getPaymentProcessors($capabilities, [$paymentProcessorID]);
return $processors[$paymentProcessorID];
}
@@ -258,16 +230,16 @@ public static function getPayment($paymentProcessorID, $mode = 'based_on_id') {
* Test payment processor ID.
*/
public static function getTestProcessorId($id) {
- $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', array(
+ $liveProcessorName = civicrm_api3('payment_processor', 'getvalue', [
'id' => $id,
'return' => 'name',
- ));
- return civicrm_api3('payment_processor', 'getvalue', array(
+ ]);
+ return civicrm_api3('payment_processor', 'getvalue', [
'return' => 'id',
'name' => $liveProcessorName,
'is_test' => 1,
'domain_id' => CRM_Core_Config::domainID(),
- ));
+ ]);
}
/**
@@ -301,7 +273,7 @@ public static function defaultComparison($processor1, $processor2) {
*/
public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $isCurrentDomainOnly = TRUE) {
- $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . CRM_Core_Config::domainID();
+ $cacheKey = 'CRM_Financial_BAO_Payment_Processor_' . $mode . '_' . $isCurrentDomainOnly . '_' . CRM_Core_Config::domainID();
if (!$reset) {
$processors = CRM_Utils_Cache::singleton()->get($cacheKey);
if (!empty($processors)) {
@@ -309,11 +281,11 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
}
}
- $retrievalParameters = array(
+ $retrievalParameters = [
'is_active' => TRUE,
- 'options' => array('sort' => 'is_default DESC, name', 'limit' => 0),
+ 'options' => ['sort' => 'is_default DESC, name', 'limit' => 0],
'api.payment_processor_type.getsingle' => 1,
- );
+ ];
if ($isCurrentDomainOnly) {
$retrievalParameters['domain_id'] = CRM_Core_Config::domainID();
}
@@ -326,7 +298,25 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
$processors = civicrm_api3('payment_processor', 'get', $retrievalParameters);
foreach ($processors['values'] as $processor) {
- $fieldsToProvide = array('user_name', 'password', 'signature', 'subject', 'is_recur');
+ $fieldsToProvide = [
+ 'id',
+ 'name',
+ 'payment_processor_type_id',
+ 'user_name',
+ 'password',
+ 'signature',
+ 'url_site',
+ 'url_api',
+ 'url_recur',
+ 'url_button',
+ 'subject',
+ 'class_name',
+ 'is_recur',
+ 'billing_mode',
+ 'is_test',
+ 'payment_type',
+ 'is_default',
+ ];
foreach ($fieldsToProvide as $field) {
// Prevent e-notices in processor classes when not configured.
if (!isset($processor[$field])) {
@@ -338,7 +328,7 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
}
// Add the pay-later pseudo-processor.
- $processors['values'][0] = array(
+ $processors['values'][0] = [
'object' => new CRM_Core_Payment_Manual(),
'id' => 0,
'payment_processor_type_id' => 0,
@@ -353,7 +343,7 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
// be a row in the payment processor table before we do that.
'is_recur' => FALSE,
'is_test' => FALSE,
- );
+ ];
CRM_Utils_Cache::singleton()->set($cacheKey, $processors['values']);
@@ -377,13 +367,13 @@ public static function getAllPaymentProcessors($mode = 'all', $reset = FALSE, $i
* @return array
* available processors
*/
- public static function getPaymentProcessors($capabilities = array(), $ids = FALSE) {
- $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : array();
+ public static function getPaymentProcessors($capabilities = [], $ids = FALSE) {
+ $testProcessors = in_array('TestMode', $capabilities) ? self::getAllPaymentProcessors('test') : [];
if (is_array($ids)) {
- $processors = self::getAllPaymentProcessors('all', TRUE, FALSE);
+ $processors = self::getAllPaymentProcessors('all', FALSE, FALSE);
}
else {
- $processors = self::getAllPaymentProcessors('all', TRUE);
+ $processors = self::getAllPaymentProcessors('all');
}
if (in_array('TestMode', $capabilities) && is_array($ids)) {
@@ -432,6 +422,7 @@ public static function getPaymentProcessors($capabilities = array(), $ids = FALS
* - supportsBackOffice
* - supportsLiveMode
* - supportsFutureRecurDate
+ * - supportsRecurring
* - supportsCancelRecurring
* - supportsRecurContributionsForPledges
*
@@ -443,9 +434,13 @@ public static function getPaymentProcessors($capabilities = array(), $ids = FALS
*
* @return bool
*/
- public static function hasPaymentProcessorSupporting($capabilities = array()) {
- $result = self::getPaymentProcessors($capabilities);
- return (!empty($result)) ? TRUE : FALSE;
+ public static function hasPaymentProcessorSupporting($capabilities = []) {
+ $capabilitiesString = implode('', $capabilities);
+ if (!isset(\Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString])) {
+ $result = self::getPaymentProcessors($capabilities);
+ \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString] = (!empty($result) && array_keys($result) !== [0]) ? TRUE : FALSE;
+ }
+ return \Civi::$statics[__CLASS__]['supported_capabilities'][$capabilitiesString];
}
/**
@@ -480,11 +475,11 @@ public static function hasPaymentProcessorSupporting($capabilities = array()) {
*/
public static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id') {
$result = NULL;
- if (!in_array($component, array(
+ if (!in_array($component, [
'membership',
'contribute',
'recur',
- ))
+ ])
) {
return $result;
}
@@ -508,6 +503,7 @@ public static function getProcessorForEntity($entityID, $component = 'contribute
WHERE con.id = %1";
}
elseif ($component == 'recur') {
+ // @deprecated - use getPaymentProcessorForRecurringContribution.
$sql = "
SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test
FROM civicrm_contribution_recur cr
@@ -517,7 +513,7 @@ public static function getProcessorForEntity($entityID, $component = 'contribute
// We are interested in a single record.
$sql .= ' LIMIT 1';
- $params = array(1 => array($entityID, 'Integer'));
+ $params = [1 => [$entityID, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if (!$dao->fetch()) {
@@ -536,17 +532,82 @@ public static function getProcessorForEntity($entityID, $component = 'contribute
}
elseif ($type == 'obj' && is_numeric($ppID)) {
try {
- $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', array('id' => $ppID));
+ $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', ['id' => $ppID]);
}
catch (API_Exception $e) {
// Unable to load the processor because this function uses an unreliable method to derive it.
// The function looks to load the payment processor ID from the contribution page, which
// can support multiple processors.
}
- $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, $paymentProcessor['payment_processor_type_id'], 'name');
+
+ $paymentProcessor['payment_processor_type'] = CRM_Core_PseudoConstant::getName('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $paymentProcessor['payment_processor_type_id']);
$result = Civi\Payment\System::singleton()->getByProcessor($paymentProcessor);
}
return $result;
}
+ /**
+ * Get the payment processor associated with a recurring contribution series.
+ *
+ * @param int $contributionRecurID
+ *
+ * @return \CRM_Core_Payment
+ */
+ public static function getPaymentProcessorForRecurringContribution($contributionRecurID) {
+ $paymentProcessorId = civicrm_api3('ContributionRecur', 'getvalue', [
+ 'id' => $contributionRecurID,
+ 'return' => 'payment_processor_id',
+ ]);
+ return Civi\Payment\System::singleton()->getById($paymentProcessorId);
+ }
+
+ /**
+ * Get the name of the payment processor
+ *
+ * @param $paymentProcessorId
+ *
+ * @return null|string
+ */
+ public static function getPaymentProcessorName($paymentProcessorId) {
+ try {
+ $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
+ 'return' => ['name'],
+ 'id' => $paymentProcessorId,
+ ]);
+ return $paymentProcessor['name'];
+ }
+ catch (Exception $e) {
+ return ts('Unknown') . ' (' . $paymentProcessorId . ')';
+ }
+ }
+
+ /**
+ * Generate and assign an arbitrary value to a field of a test object.
+ *
+ * @param string $fieldName
+ * @param array $fieldDef
+ * @param int $counter
+ * The globally-unique ID of the test object.
+ */
+ protected function assignTestValue($fieldName, &$fieldDef, $counter) {
+ if ($fieldName === 'class_name') {
+ $this->class_name = 'Payment_Dummy';
+ }
+ else {
+ parent::assignTestValue($fieldName, $fieldDef, $counter);
+ }
+ }
+
+ /**
+ * Get the default financial account id for payment processor accounts.
+ *
+ * Note that there is only a 'name' field & no label field. If people customise
+ * name then this won't work. This is new best-effort functionality so that's non-regressive.
+ *
+ * The fix for that is to add a label value to the financial account table.
+ */
+ public static function getDefaultFinancialAccountID() {
+ return CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_EntityFinancialAccount', 'financial_account_id', 'Payment Processor Account');
+ }
+
}
diff --git a/CRM/Financial/BAO/PaymentProcessorType.php b/CRM/Financial/BAO/PaymentProcessorType.php
index 2afcc0f8a65e..2a8f7ba0429a 100644
--- a/CRM/Financial/BAO/PaymentProcessorType.php
+++ b/CRM/Financial/BAO/PaymentProcessorType.php
@@ -1,9 +1,9 @@
1);
- $defaults = array();
+ $params = ['is_default' => 1];
+ $defaults = [];
self::$_defaultPaymentProcessorType = self::retrieve($params, $defaults);
}
return self::$_defaultPaymentProcessorType;
@@ -179,7 +179,7 @@ public static function del($paymentProcessorTypeId) {
FROM civicrm_payment_processor pp, civicrm_payment_processor_type ppt
WHERE pp.payment_processor_type_id = ppt.id AND ppt.id = %1";
- $params = array(1 => array($paymentProcessorTypeId, 'Integer'));
+ $params = [1 => [$paymentProcessorTypeId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
@@ -200,8 +200,8 @@ public static function del($paymentProcessorTypeId) {
*
* @return array
*/
- static private function getAllPaymentProcessorTypes($attr) {
- $ppt = array();
+ private static function getAllPaymentProcessorTypes($attr) {
+ $ppt = [];
$dao = new CRM_Financial_DAO_PaymentProcessorType();
$dao->find();
while ($dao->fetch()) {
diff --git a/CRM/Financial/DAO/Currency.php b/CRM/Financial/DAO/Currency.php
index 52cf12bedcf7..f20e3c203742 100644
--- a/CRM/Financial/DAO/Currency.php
+++ b/CRM/Financial/DAO/Currency.php
@@ -1,211 +1,198 @@
__table = 'civicrm_currency';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Currency ID') ,
- 'description' => 'Currency Id',
- 'required' => true,
+ 'title' => ts('Currency ID'),
+ 'description' => ts('Currency Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_currency.id',
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => 'Currency Name',
+ 'title' => ts('Currency'),
+ 'description' => ts('Currency Name'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_currency.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'symbol' => array(
+ ],
+ ],
+ 'symbol' => [
'name' => 'symbol',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency Symbol') ,
- 'description' => 'Currency Symbol',
+ 'title' => ts('Currency Symbol'),
+ 'description' => ts('Currency Symbol'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_currency.symbol',
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'numeric_code' => array(
+ ],
+ ],
+ 'numeric_code' => [
'name' => 'numeric_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency Numeric Code') ,
- 'description' => 'Numeric currency code',
+ 'title' => ts('Currency Numeric Code'),
+ 'description' => ts('Numeric currency code'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_currency.numeric_code',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- ) ,
- 'full_name' => array(
+ ],
+ 'full_name' => [
'name' => 'full_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Full Currency Name') ,
- 'description' => 'Full currency name',
+ 'title' => ts('Full Currency Name'),
+ 'description' => ts('Full currency name'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_currency.full_name',
'table_name' => 'civicrm_currency',
'entity' => 'Currency',
'bao' => 'CRM_Financial_DAO_Currency',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -213,10 +200,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'currency', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'currency', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -224,15 +212,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'currency', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'currency', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/EntityFinancialAccount.php b/CRM/Financial/DAO/EntityFinancialAccount.php
index 338a68afd38e..529a8d68a48d 100644
--- a/CRM/Financial/DAO/EntityFinancialAccount.php
+++ b/CRM/Financial/DAO/EntityFinancialAccount.php
@@ -1,226 +1,217 @@
__table = 'civicrm_entity_financial_account';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity Financial Account ID') ,
- 'description' => 'ID',
- 'required' => true,
+ 'title' => ts('Entity Financial Account ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.id',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'Links to an entity_table like civicrm_financial_type',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('Links to an entity_table like civicrm_financial_type'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_entity_financial_account.entity_table',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'description' => 'Links to an id in the entity_table, such as vid in civicrm_financial_type',
- 'required' => true,
+ 'title' => ts('Entity ID'),
+ 'description' => ts('Links to an id in the entity_table, such as vid in civicrm_financial_type'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.entity_id',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- ) ,
- 'account_relationship' => array(
+ ],
+ 'account_relationship' => [
'name' => 'account_relationship',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Account Relationship') ,
- 'description' => 'FK to a new civicrm_option_value (account_relationship)',
- 'required' => true,
+ 'title' => ts('Account Relationship'),
+ 'description' => ts('FK to a new civicrm_option_value (account_relationship)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.account_relationship',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'account_relationship',
'optionEditPath' => 'civicrm/admin/options/account_relationship',
- )
- ) ,
- 'financial_account_id' => array(
+ ]
+ ],
+ 'financial_account_id' => [
'name' => 'financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account') ,
- 'description' => 'FK to the financial_account_id',
- 'required' => true,
+ 'title' => ts('Financial Account'),
+ 'description' => ts('FK to the financial_account_id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_account.financial_account_id',
'table_name' => 'civicrm_entity_financial_account',
'entity' => 'EntityFinancialAccount',
'bao' => 'CRM_Financial_DAO_EntityFinancialAccount',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -228,10 +219,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_account', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -239,27 +231,33 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_account', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_entity_id_entity_table_account_relationship' => array(
+ $indices = [
+ 'index_entity_id_entity_table_account_relationship' => [
'name' => 'index_entity_id_entity_table_account_relationship',
- 'field' => array(
+ 'field' => [
0 => 'entity_id',
1 => 'entity_table',
2 => 'account_relationship',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_entity_financial_account::1::entity_id::entity_table::account_relationship',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/EntityFinancialTrxn.php b/CRM/Financial/DAO/EntityFinancialTrxn.php
index dc94113815e8..ba7d38c47116 100644
--- a/CRM/Financial/DAO/EntityFinancialTrxn.php
+++ b/CRM/Financial/DAO/EntityFinancialTrxn.php
@@ -1,215 +1,203 @@
__table = 'civicrm_entity_financial_trxn';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_trxn_id', 'civicrm_financial_trxn', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_trxn_id', 'civicrm_financial_trxn', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity Financial Transaction ID') ,
- 'description' => 'ID',
- 'required' => true,
+ 'title' => ts('Entity Financial Transaction ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_trxn.id',
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'May contain civicrm_financial_item, civicrm_contribution, civicrm_financial_trxn, civicrm_grant, etc',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('May contain civicrm_financial_item, civicrm_contribution, civicrm_financial_trxn, civicrm_grant, etc'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_entity_financial_trxn.entity_table',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'required' => true,
+ 'title' => ts('Entity ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_entity_financial_trxn.entity_id',
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- 'financial_trxn_id' => array(
+ ],
+ 'financial_trxn_id' => [
'name' => 'financial_trxn_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction Id') ,
+ 'title' => ts('Financial Transaction Id'),
+ 'where' => 'civicrm_entity_financial_trxn.financial_trxn_id',
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialTrxn',
- ) ,
- 'amount' => array(
+ ],
+ 'amount' => [
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount') ,
- 'description' => 'allocated amount of transaction to this entity',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Amount'),
+ 'description' => ts('allocated amount of transaction to this entity'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_entity_financial_trxn.amount',
'headerPattern' => '/amount/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_entity_financial_trxn',
'entity' => 'EntityFinancialTrxn',
'bao' => 'CRM_Financial_DAO_EntityFinancialTrxn',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -217,10 +205,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_trxn', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'entity_financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -228,32 +217,38 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_trxn', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'entity_financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_entity_financial_trxn_entity_table' => array(
+ $indices = [
+ 'UI_entity_financial_trxn_entity_table' => [
'name' => 'UI_entity_financial_trxn_entity_table',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_entity_financial_trxn::0::entity_table',
- ) ,
- 'UI_entity_financial_trxn_entity_id' => array(
+ ],
+ 'UI_entity_financial_trxn_entity_id' => [
'name' => 'UI_entity_financial_trxn_entity_id',
- 'field' => array(
+ 'field' => [
0 => 'entity_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_entity_financial_trxn::0::entity_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialAccount.php b/CRM/Financial/DAO/FinancialAccount.php
index ec43d41a2f01..99c784aa70e6 100644
--- a/CRM/Financial/DAO/FinancialAccount.php
+++ b/CRM/Financial/DAO/FinancialAccount.php
@@ -1,392 +1,402 @@
__table = 'civicrm_financial_account';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'parent_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'parent_id', 'civicrm_financial_account', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account ID') ,
- 'description' => 'ID',
- 'required' => true,
+ 'title' => ts('Financial Account ID'),
+ 'description' => ts('ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_account.id',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Account Name') ,
- 'description' => 'Financial Account Name.',
- 'required' => true,
+ 'title' => ts('Financial Account Name'),
+ 'description' => ts('Financial Account Name.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_account.name',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'financial_account_contact_id' => array(
+ ],
+ 'financial_account_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID that is responsible for the funds in this account',
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID that is responsible for the funds in this account'),
+ 'where' => 'civicrm_financial_account.contact_id',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'financial_account_type_id' => array(
+ ],
+ 'financial_account_type_id' => [
'name' => 'financial_account_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account Type') ,
- 'description' => 'pseudo FK into civicrm_option_value.',
- 'required' => true,
+ 'title' => ts('Financial Account Type'),
+ 'description' => ts('pseudo FK into civicrm_option_value.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_account.financial_account_type_id',
'default' => '3',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'financial_account_type',
'optionEditPath' => 'civicrm/admin/options/financial_account_type',
- )
- ) ,
- 'accounting_code' => array(
+ ]
+ ],
+ 'accounting_code' => [
'name' => 'accounting_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Accounting Code') ,
- 'description' => 'Optional value for mapping monies owed and received to accounting system codes.',
+ 'title' => ts('Accounting Code'),
+ 'description' => ts('Optional value for mapping monies owed and received to accounting system codes.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'export' => true,
'where' => 'civicrm_financial_account.accounting_code',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'account_type_code' => array(
+ ],
+ 'account_type_code' => [
'name' => 'account_type_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Account Type Code') ,
- 'description' => 'Optional value for mapping account types to accounting system account categories (QuickBooks Account Type Codes for example).',
+ 'title' => ts('Account Type Code'),
+ 'description' => ts('Optional value for mapping account types to accounting system account categories (QuickBooks Account Type Codes for example).'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'export' => true,
'where' => 'civicrm_financial_account.account_type_code',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Account Description') ,
- 'description' => 'Financial Type Description.',
+ 'title' => ts('Financial Account Description'),
+ 'description' => ts('Financial Type Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_account.description',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'parent_id' => array(
+ ],
+ 'parent_id' => [
'name' => 'parent_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account Parent') ,
- 'description' => 'Parent ID in account hierarchy',
+ 'title' => ts('Financial Account Parent'),
+ 'description' => ts('Parent ID in account hierarchy'),
+ 'where' => 'civicrm_financial_account.parent_id',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- ) ,
- 'is_header_account' => array(
+ ],
+ 'is_header_account' => [
'name' => 'is_header_account',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Header Financial Account?') ,
- 'description' => 'Is this a header account which does not allow transactions to be posted against it directly, but only to its sub-accounts?',
+ 'title' => ts('Header Financial Account?'),
+ 'description' => ts('Is this a header account which does not allow transactions to be posted against it directly, but only to its sub-accounts?'),
+ 'where' => 'civicrm_financial_account.is_header_account',
+ 'default' => '0',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_deductible' => array(
+ ],
+ 'is_deductible' => [
'name' => 'is_deductible',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Deductible Financial Account?') ,
- 'description' => 'Is this account tax-deductible?',
+ 'title' => ts('Deductible Financial Account?'),
+ 'description' => ts('Is this account tax-deductible?'),
+ 'where' => 'civicrm_financial_account.is_deductible',
'default' => '1',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_tax' => array(
+ ],
+ 'is_tax' => [
'name' => 'is_tax',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Tax Financial Account?') ,
- 'description' => 'Is this account for taxes?',
+ 'title' => ts('Tax Financial Account?'),
+ 'description' => ts('Is this account for taxes?'),
+ 'where' => 'civicrm_financial_account.is_tax',
+ 'default' => '0',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'tax_rate' => array(
+ ],
+ 'tax_rate' => [
'name' => 'tax_rate',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Account Tax Rate') ,
- 'description' => 'The percentage of the total_amount that is due for this tax.',
- 'precision' => array(
+ 'title' => ts('Financial Account Tax Rate'),
+ 'description' => ts('The percentage of the total_amount that is due for this tax.'),
+ 'precision' => [
10,
8
- ) ,
+ ],
+ 'where' => 'civicrm_financial_account.tax_rate',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Reserved Financial Account?') ,
- 'description' => 'Is this a predefined system object?',
+ 'title' => ts('Reserved Financial Account?'),
+ 'description' => ts('Is this a predefined system object?'),
+ 'where' => 'civicrm_financial_account.is_reserved',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Account is Active') ,
- 'description' => 'Is this property active?',
+ 'title' => ts('Financial Account is Active'),
+ 'description' => ts('Is this property active?'),
+ 'where' => 'civicrm_financial_account.is_active',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Default Financial Account') ,
- 'description' => 'Is this account the default one (or default tax one) for its financial_account_type?',
+ 'title' => ts('Default Financial Account'),
+ 'description' => ts('Is this account the default one (or default tax one) for its financial_account_type?'),
+ 'where' => 'civicrm_financial_account.is_default',
'table_name' => 'civicrm_financial_account',
'entity' => 'FinancialAccount',
'bao' => 'CRM_Financial_BAO_FinancialAccount',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -394,10 +404,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_account', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -405,25 +416,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_account', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_account', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name' => array(
+ $indices = [
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_financial_account::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialItem.php b/CRM/Financial/DAO/FinancialItem.php
index 82d71822af91..dcbc5b4d4f31 100644
--- a/CRM/Financial/DAO/FinancialItem.php
+++ b/CRM/Financial/DAO/FinancialItem.php
@@ -1,347 +1,346 @@
__table = 'civicrm_financial_item';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Item ID') ,
- 'required' => true,
+ 'title' => ts('Financial Item ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_item.id',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Financial Item Created Date') ,
- 'description' => 'Date and time the item was created',
- 'required' => true,
+ 'title' => ts('Financial Item Created Date'),
+ 'description' => ts('Date and time the item was created'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_item.created_date',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'transaction_date' => array(
+ ],
+ 'transaction_date' => [
'name' => 'transaction_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Financial Item Transaction Date') ,
- 'description' => 'Date and time of the source transaction',
- 'required' => true,
+ 'title' => ts('Financial Item Transaction Date'),
+ 'description' => ts('Date and time of the source transaction'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_item.transaction_date',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Item Contact ID') ,
- 'description' => 'FK to Contact ID of contact the item is from',
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Financial Item Contact ID'),
+ 'description' => ts('FK to Contact ID of contact the item is from'),
+ 'required' => TRUE,
'where' => 'civicrm_financial_item.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Item Description') ,
- 'description' => 'Human readable description of this item, to ease display without lookup of source item.',
+ 'title' => ts('Financial Item Description'),
+ 'description' => ts('Human readable description of this item, to ease display without lookup of source item.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_item.description',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'amount' => array(
+ ],
+ 'amount' => [
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount') ,
- 'description' => 'Total amount of this item',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Amount'),
+ 'description' => ts('Total amount of this item'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_financial_item.amount',
+ 'headerPattern' => '/unit?.?amoun/i',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
+ 'default' => '0',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Item Currency') ,
- 'description' => 'Currency for the amount',
+ 'title' => ts('Financial Item Currency'),
+ 'description' => ts('Currency for the amount'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'export' => true,
'where' => 'civicrm_financial_item.currency',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'financial_account_id' => array(
+ ]
+ ],
+ 'financial_account_id' => [
'name' => 'financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Account ID') ,
- 'description' => 'FK to civicrm_financial_account',
+ 'title' => ts('Financial Account ID'),
+ 'description' => ts('FK to civicrm_financial_account'),
+ 'where' => 'civicrm_financial_item.financial_account_id',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'status_id' => array(
+ ]
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Item Status ID') ,
- 'description' => 'Payment status: test, paid, part_paid, unpaid (if empty assume unpaid)',
- 'export' => true,
+ 'title' => ts('Financial Item Status ID'),
+ 'description' => ts('Payment status: test, paid, part_paid, unpaid (if empty assume unpaid)'),
'where' => 'civicrm_financial_item.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'financial_item_status',
'optionEditPath' => 'civicrm/admin/options/financial_item_status',
- )
- ) ,
- 'entity_table' => array(
+ ]
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'The table providing the source of this item such as civicrm_line_item',
+ 'title' => ts('Entity Table'),
+ 'description' => ts('The table providing the source of this item such as civicrm_line_item'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_financial_item.entity_table',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'description' => 'The specific source item that is responsible for the creation of this financial_item',
+ 'title' => ts('Entity ID'),
+ 'description' => ts('The specific source item that is responsible for the creation of this financial_item'),
+ 'where' => 'civicrm_financial_item.entity_id',
'table_name' => 'civicrm_financial_item',
'entity' => 'FinancialItem',
'bao' => 'CRM_Financial_BAO_FinancialItem',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -349,10 +348,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_item', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -360,41 +360,47 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_item', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'IX_created_date' => array(
+ $indices = [
+ 'IX_created_date' => [
'name' => 'IX_created_date',
- 'field' => array(
+ 'field' => [
0 => 'created_date',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_item::0::created_date',
- ) ,
- 'IX_transaction_date' => array(
+ ],
+ 'IX_transaction_date' => [
'name' => 'IX_transaction_date',
- 'field' => array(
+ 'field' => [
0 => 'transaction_date',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_item::0::transaction_date',
- ) ,
- 'index_entity_id_entity_table' => array(
+ ],
+ 'index_entity_id_entity_table' => [
'name' => 'index_entity_id_entity_table',
- 'field' => array(
+ 'field' => [
0 => 'entity_id',
1 => 'entity_table',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_item::0::entity_id::entity_table',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialTrxn.php b/CRM/Financial/DAO/FinancialTrxn.php
index 4aac190592b5..1d262b411dcb 100644
--- a/CRM/Financial/DAO/FinancialTrxn.php
+++ b/CRM/Financial/DAO/FinancialTrxn.php
@@ -1,489 +1,501 @@
__table = 'civicrm_financial_trxn';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'from_financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'to_financial_account_id', 'civicrm_financial_account', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_id', 'civicrm_payment_processor', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'from_financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'to_financial_account_id', 'civicrm_financial_account', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'payment_processor_id', 'civicrm_payment_processor', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction ID') ,
- 'required' => true,
+ 'title' => ts('Financial Transaction ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_trxn.id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'from_financial_account_id' => array(
+ ],
+ 'from_financial_account_id' => [
'name' => 'from_financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction From Account') ,
- 'description' => 'FK to financial_account table.',
+ 'title' => ts('Financial Transaction From Account'),
+ 'description' => ts('FK to financial_account table.'),
+ 'where' => 'civicrm_financial_trxn.from_financial_account_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'to_financial_account_id' => array(
+ ]
+ ],
+ 'to_financial_account_id' => [
'name' => 'to_financial_account_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction To Account') ,
- 'description' => 'FK to financial_financial_account table.',
+ 'title' => ts('Financial Transaction To Account'),
+ 'description' => ts('FK to financial_financial_account table.'),
+ 'where' => 'civicrm_financial_trxn.to_financial_account_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialAccount',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_account',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'trxn_date' => array(
+ ]
+ ],
+ 'trxn_date' => [
'name' => 'trxn_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Financial Transaction Date') ,
- 'description' => 'date transaction occurred',
+ 'title' => ts('Financial Transaction Date'),
+ 'description' => ts('date transaction occurred'),
+ 'where' => 'civicrm_financial_trxn.trxn_date',
'default' => 'NULL',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDateTime',
- ) ,
- ) ,
- 'total_amount' => array(
+ ],
+ ],
+ 'total_amount' => [
'name' => 'total_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Total Amount') ,
- 'description' => 'amount of transaction',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Financial Total Amount'),
+ 'description' => ts('amount of transaction'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_financial_trxn.total_amount',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'fee_amount' => array(
+ ],
+ 'fee_amount' => [
'name' => 'fee_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Fee Amount') ,
- 'description' => 'actual processor fee if known - may be 0.',
- 'precision' => array(
+ 'title' => ts('Financial Fee Amount'),
+ 'description' => ts('actual processor fee if known - may be 0.'),
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_financial_trxn.fee_amount',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'net_amount' => array(
+ ],
+ 'net_amount' => [
'name' => 'net_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Financial Net Amount') ,
- 'description' => 'actual funds transfer amount. total less fees. if processor does not report actual fee during transaction, this is set to total_amount.',
- 'precision' => array(
+ 'title' => ts('Financial Net Amount'),
+ 'description' => ts('actual funds transfer amount. total less fees. if processor does not report actual fee during transaction, this is set to total_amount.'),
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_financial_trxn.net_amount',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Financial Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_financial_trxn.currency',
'headerPattern' => '/cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/',
- 'export' => true,
+ 'export' => TRUE,
'default' => 'NULL',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'is_payment' => array(
+ ]
+ ],
+ 'is_payment' => [
'name' => 'is_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Payment?') ,
- 'description' => 'Is this entry either a payment or a reversal of a payment?',
- 'import' => true,
+ 'title' => ts('Is Payment?'),
+ 'description' => ts('Is this entry either a payment or a reversal of a payment?'),
+ 'import' => TRUE,
'where' => 'civicrm_financial_trxn.is_payment',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'trxn_id' => array(
+ ],
+ 'trxn_id' => [
'name' => 'trxn_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Transaction ID') ,
- 'description' => 'Transaction id supplied by external processor. This may not be unique.',
+ 'title' => ts('Transaction ID'),
+ 'description' => ts('Transaction id supplied by external processor. This may not be unique.'),
'maxlength' => 255,
'size' => 10,
+ 'where' => 'civicrm_financial_trxn.trxn_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'trxn_result_code' => array(
+ ],
+ ],
+ 'trxn_result_code' => [
'name' => 'trxn_result_code',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Transaction Result Code') ,
- 'description' => 'processor result code',
+ 'title' => ts('Transaction Result Code'),
+ 'description' => ts('processor result code'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_trxn.trxn_result_code',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- ) ,
- 'status_id' => array(
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Transaction Status Id') ,
- 'description' => 'pseudo FK to civicrm_option_value of contribution_status_id option_group',
- 'import' => true,
+ 'title' => ts('Financial Transaction Status Id'),
+ 'description' => ts('pseudo FK to civicrm_option_value of contribution_status_id option_group'),
+ 'import' => TRUE,
'where' => 'civicrm_financial_trxn.status_id',
'headerPattern' => '/status/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
- )
- ) ,
- 'payment_processor_id' => array(
+ ]
+ ],
+ 'payment_processor_id' => [
'name' => 'payment_processor_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor') ,
- 'description' => 'Payment Processor for this financial transaction',
+ 'title' => ts('Payment Processor'),
+ 'description' => ts('Payment Processor for this financial transaction'),
+ 'where' => 'civicrm_financial_trxn.payment_processor_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessor',
- ) ,
- 'financial_trxn_payment_instrument_id' => array(
+ ],
+ 'financial_trxn_payment_instrument_id' => [
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Method') ,
- 'description' => 'FK to payment_instrument option group values',
+ 'title' => ts('Payment Method'),
+ 'description' => ts('FK to payment_instrument option group values'),
+ 'where' => 'civicrm_financial_trxn.payment_instrument_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- 'financial_trxn_card_type_id' => array(
+ ]
+ ],
+ 'financial_trxn_card_type_id' => [
'name' => 'card_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Card Type ID') ,
- 'description' => 'FK to accept_creditcard option group values',
+ 'title' => ts('Card Type ID'),
+ 'description' => ts('FK to accept_creditcard option group values'),
+ 'where' => 'civicrm_financial_trxn.card_type_id',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'accept_creditcard',
'optionEditPath' => 'civicrm/admin/options/accept_creditcard',
- )
- ) ,
- 'financial_trxn_check_number' => array(
+ ]
+ ],
+ 'financial_trxn_check_number' => [
'name' => 'check_number',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Check Number') ,
- 'description' => 'Check number',
+ 'title' => ts('Check Number'),
+ 'description' => ts('Check number'),
'maxlength' => 255,
'size' => 6,
+ 'where' => 'civicrm_financial_trxn.check_number',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'financial_trxn_pan_truncation' => array(
+ ],
+ ],
+ 'financial_trxn_pan_truncation' => [
'name' => 'pan_truncation',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pan Truncation') ,
- 'description' => 'Last 4 digits of credit card',
+ 'title' => ts('Pan Truncation'),
+ 'description' => ts('Last 4 digits of credit card'),
'maxlength' => 4,
'size' => 4,
+ 'where' => 'civicrm_financial_trxn.pan_truncation',
'table_name' => 'civicrm_financial_trxn',
'entity' => 'FinancialTrxn',
'bao' => 'CRM_Financial_DAO_FinancialTrxn',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -491,10 +503,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_trxn', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -502,40 +515,46 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_trxn', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_trxn', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_ftrxn_trxn_id' => array(
+ $indices = [
+ 'UI_ftrxn_trxn_id' => [
'name' => 'UI_ftrxn_trxn_id',
- 'field' => array(
+ 'field' => [
0 => 'trxn_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_trxn::0::trxn_id',
- ) ,
- 'UI_ftrxn_payment_instrument_id' => array(
+ ],
+ 'UI_ftrxn_payment_instrument_id' => [
'name' => 'UI_ftrxn_payment_instrument_id',
- 'field' => array(
+ 'field' => [
0 => 'payment_instrument_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_trxn::0::payment_instrument_id',
- ) ,
- 'UI_ftrxn_check_number' => array(
+ ],
+ 'UI_ftrxn_check_number' => [
'name' => 'UI_ftrxn_check_number',
- 'field' => array(
+ 'field' => [
0 => 'check_number',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_financial_trxn::0::check_number',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/FinancialType.php b/CRM/Financial/DAO/FinancialType.php
index 3be6e3a6cfc9..90a916f0750d 100644
--- a/CRM/Financial/DAO/FinancialType.php
+++ b/CRM/Financial/DAO/FinancialType.php
@@ -1,211 +1,225 @@
__table = 'civicrm_financial_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type ID') ,
- 'description' => 'ID of original financial_type so you can search this table by the financial_type.id and then select the relevant version based on the timestamp',
- 'required' => true,
+ 'title' => ts('Financial Type ID'),
+ 'description' => ts('ID of original financial_type so you can search this table by the financial_type.id and then select the relevant version based on the timestamp'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_financial_type.id',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'financial_type' => array(
+ ],
+ 'financial_type' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Financial Type') ,
- 'description' => 'Financial Type Name.',
- 'required' => true,
+ 'title' => ts('Financial Type'),
+ 'description' => ts('Financial Type Name.'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_financial_type.name',
'headerPattern' => '/(finan(cial)?)?type/i',
'dataPattern' => '/donation|member|campaign/i',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'description' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Name"),
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Description') ,
- 'description' => 'Financial Type Description.',
+ 'title' => ts('Description'),
+ 'description' => ts('Financial Type Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_financial_type.description',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'is_deductible' => array(
+ 'html' => [
+ 'type' => 'TextArea',
+ 'label' => ts("Description"),
+ ],
+ ],
+ 'is_deductible' => [
'name' => 'is_deductible',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Tax Deductible?') ,
- 'description' => 'Is this financial type tax-deductible? If true, contributions of this type may be fully OR partially deductible - non-deductible amount is stored in the Contribution record.',
+ 'title' => ts('Is Tax Deductible?'),
+ 'description' => ts('Is this financial type tax-deductible? If true, contributions of this type may be fully OR partially deductible - non-deductible amount is stored in the Contribution record.'),
+ 'where' => 'civicrm_financial_type.is_deductible',
'default' => '1',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Tax-Deductible?"),
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Type is Reserved?') ,
- 'description' => 'Is this a predefined system object?',
+ 'title' => ts('Financial Type is Reserved?'),
+ 'description' => ts('Is this a predefined system object?'),
+ 'where' => 'civicrm_financial_type.is_reserved',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Reserved?"),
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Financial Type Is Active?') ,
- 'description' => 'Is this property active?',
+ 'title' => ts('Financial Type Is Active?'),
+ 'description' => ts('Is this property active?'),
+ 'where' => 'civicrm_financial_type.is_active',
'table_name' => 'civicrm_financial_type',
'entity' => 'FinancialType',
'bao' => 'CRM_Financial_BAO_FinancialType',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Enabled?"),
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -213,10 +227,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'financial_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -224,25 +239,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'financial_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_id' => array(
+ $indices = [
+ 'UI_id' => [
'name' => 'UI_id',
- 'field' => array(
+ 'field' => [
0 => 'id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_financial_type::1::id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/PaymentProcessor.php b/CRM/Financial/DAO/PaymentProcessor.php
index c585f1945d64..f3aed4735247 100644
--- a/CRM/Financial/DAO/PaymentProcessor.php
+++ b/CRM/Financial/DAO/PaymentProcessor.php
@@ -1,521 +1,563 @@
__table = 'civicrm_payment_processor';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_type_id', 'civicrm_payment_processor_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'payment_processor_type_id', 'civicrm_payment_processor_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor ID') ,
- 'description' => 'Payment Processor ID',
- 'required' => true,
+ 'title' => ts('Payment Processor ID'),
+ 'description' => ts('Payment Processor ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor.id',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor Domain') ,
- 'description' => 'Which Domain is this match entry for',
- 'required' => true,
+ 'title' => ts('Payment Processor Domain'),
+ 'description' => ts('Which Domain is this match entry for'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor.domain_id',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'name' => array(
+ ]
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor') ,
- 'description' => 'Payment Processor Name.',
+ 'title' => ts('Payment Processor'),
+ 'description' => ts('Payment Processor Name.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_payment_processor.name',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'title' => [
+ 'name' => 'title',
+ 'type' => CRM_Utils_Type::T_STRING,
+ 'title' => ts('Payment Processor Title'),
+ 'description' => ts('Payment Processor Descriptive Name.'),
+ 'maxlength' => 127,
+ 'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.title',
+ 'table_name' => 'civicrm_payment_processor',
+ 'entity' => 'PaymentProcessor',
+ 'bao' => 'CRM_Financial_BAO_PaymentProcessor',
+ 'localizable' => 1,
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'description' => array(
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Processor Description') ,
- 'description' => 'Payment Processor Description.',
+ 'title' => ts('Processor Description'),
+ 'description' => ts('Payment Processor Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.description',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'payment_processor_type_id' => array(
+ ],
+ 'payment_processor_type_id' => [
'name' => 'payment_processor_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor Type ID') ,
+ 'title' => ts('Payment Processor Type ID'),
+ 'where' => 'civicrm_payment_processor.payment_processor_type_id',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessorType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_payment_processor_type',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- 'is_active' => array(
+ ]
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor is Active?') ,
- 'description' => 'Is this processor active?',
+ 'title' => ts('Processor is Active?'),
+ 'description' => ts('Is this processor active?'),
+ 'where' => 'civicrm_payment_processor.is_active',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Is Default?') ,
- 'description' => 'Is this processor the default?',
+ 'title' => ts('Processor Is Default?'),
+ 'description' => ts('Is this processor the default?'),
+ 'where' => 'civicrm_payment_processor.is_default',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'is_test' => array(
+ ],
+ 'is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Test Processor?') ,
- 'description' => 'Is this processor for a test site?',
+ 'title' => ts('Is Test Processor?'),
+ 'description' => ts('Is this processor for a test site?'),
+ 'where' => 'civicrm_payment_processor.is_test',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'user_name' => array(
+ ],
+ 'user_name' => [
'name' => 'user_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('User Name') ,
+ 'title' => ts('User Name'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.user_name',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'password' => array(
+ ],
+ ],
+ 'password' => [
'name' => 'password',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Password') ,
+ 'title' => ts('Password'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.password',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Password',
- ) ,
- ) ,
- 'signature' => array(
+ ],
+ ],
+ 'signature' => [
'name' => 'signature',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Signature') ,
+ 'title' => ts('Signature'),
'rows' => 4,
'cols' => 40,
+ 'where' => 'civicrm_payment_processor.signature',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'url_site' => array(
+ ],
+ ],
+ 'url_site' => [
'name' => 'url_site',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Site URL') ,
+ 'title' => ts('Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_site',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'url_api' => array(
+ ],
+ ],
+ 'url_api' => [
'name' => 'url_api',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('API URL') ,
+ 'title' => ts('API URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_api',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'url_recur' => array(
+ ],
+ ],
+ 'url_recur' => [
'name' => 'url_recur',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Recurring Payments URL') ,
+ 'title' => ts('Recurring Payments URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_recur',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'url_button' => array(
+ ],
+ ],
+ 'url_button' => [
'name' => 'url_button',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Button URL') ,
+ 'title' => ts('Button URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.url_button',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'subject' => array(
+ ],
+ ],
+ 'subject' => [
'name' => 'subject',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Subject') ,
+ 'title' => ts('Subject'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.subject',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'class_name' => array(
+ ],
+ ],
+ 'class_name' => [
'name' => 'class_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Suffix for PHP class name implementation') ,
+ 'title' => ts('Suffix for PHP class name implementation'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor.class_name',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'billing_mode' => array(
+ ],
+ 'billing_mode' => [
'name' => 'billing_mode',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Processor Billing Mode') ,
- 'description' => 'Billing Mode (deprecated)',
- 'required' => true,
+ 'title' => ts('Processor Billing Mode'),
+ 'description' => ts('Billing Mode (deprecated)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor.billing_mode',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'is_recur' => array(
+ ],
+ 'is_recur' => [
'name' => 'is_recur',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Supports Recurring?') ,
- 'description' => 'Can process recurring contributions',
+ 'title' => ts('Processor Supports Recurring?'),
+ 'description' => ts('Can process recurring contributions'),
+ 'where' => 'civicrm_payment_processor.is_recur',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'payment_type' => array(
+ ],
+ 'payment_type' => [
'name' => 'payment_type',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Type') ,
- 'description' => 'Payment Type: Credit or Debit (deprecated)',
+ 'title' => ts('Payment Type'),
+ 'description' => ts('Payment Type: Credit or Debit (deprecated)'),
+ 'where' => 'civicrm_payment_processor.payment_type',
'default' => '1',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- 'payment_instrument_id' => array(
+ ],
+ 'payment_instrument_id' => [
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Method') ,
- 'description' => 'Payment Instrument ID',
+ 'title' => ts('Payment Method'),
+ 'description' => ts('Payment Instrument ID'),
+ 'where' => 'civicrm_payment_processor.payment_instrument_id',
'default' => '1',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- 'accepted_credit_cards' => array(
+ ]
+ ],
+ 'accepted_credit_cards' => [
'name' => 'accepted_credit_cards',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Accepted Credit Cards') ,
- 'description' => 'array of accepted credit card types',
+ 'title' => ts('Accepted Credit Cards'),
+ 'description' => ts('array of accepted credit card types'),
+ 'where' => 'civicrm_payment_processor.accepted_credit_cards',
'default' => 'NULL',
'table_name' => 'civicrm_payment_processor',
'entity' => 'PaymentProcessor',
'bao' => 'CRM_Financial_BAO_PaymentProcessor',
'localizable' => 0,
- ) ,
- );
+ 'serialize' => self::SERIALIZE_JSON,
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
- return self::$_tableName;
+ public static function getTableName() {
+ return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -523,10 +565,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -534,27 +577,33 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name_test_domain_id' => array(
+ $indices = [
+ 'UI_name_test_domain_id' => [
'name' => 'UI_name_test_domain_id',
- 'field' => array(
+ 'field' => [
0 => 'name',
1 => 'is_test',
2 => 'domain_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_payment_processor::1::name::is_test::domain_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/PaymentProcessorType.php b/CRM/Financial/DAO/PaymentProcessorType.php
index f98f34e9d41d..5bad18359df9 100644
--- a/CRM/Financial/DAO/PaymentProcessorType.php
+++ b/CRM/Financial/DAO/PaymentProcessorType.php
@@ -1,491 +1,507 @@
__table = 'civicrm_payment_processor_type';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor Type ID') ,
- 'description' => 'Payment Processor Type ID',
- 'required' => true,
+ 'title' => ts('Payment Processor Type ID'),
+ 'description' => ts('Payment Processor Type ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor_type.id',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor variable name to be used in code') ,
- 'description' => 'Payment Processor Name.',
+ 'title' => ts('Payment Processor variable name to be used in code'),
+ 'description' => ts('Payment Processor Name.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_payment_processor_type.name',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'title' => array(
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Payment Processor Title') ,
- 'description' => 'Payment Processor Name.',
+ 'title' => ts('Payment Processor Title'),
+ 'description' => ts('Payment Processor Name.'),
'maxlength' => 127,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.title',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'description' => array(
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Processor Type Description') ,
- 'description' => 'Payment Processor Description.',
+ 'title' => ts('Processor Type Description'),
+ 'description' => ts('Payment Processor Description.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.description',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type Is Active?') ,
- 'description' => 'Is this processor active?',
+ 'title' => ts('Processor Type Is Active?'),
+ 'description' => ts('Is this processor active?'),
+ 'where' => 'civicrm_payment_processor_type.is_active',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type is Default?') ,
- 'description' => 'Is this processor the default?',
+ 'title' => ts('Processor Type is Default?'),
+ 'description' => ts('Is this processor the default?'),
+ 'where' => 'civicrm_payment_processor_type.is_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'user_name_label' => array(
+ ],
+ 'user_name_label' => [
'name' => 'user_name_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for User Name if used') ,
+ 'title' => ts('Label for User Name if used'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.user_name_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'password_label' => array(
+ ],
+ 'password_label' => [
'name' => 'password_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for password') ,
+ 'title' => ts('Label for password'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.password_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'signature_label' => array(
+ ],
+ 'signature_label' => [
'name' => 'signature_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for Signature') ,
+ 'title' => ts('Label for Signature'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.signature_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'subject_label' => array(
+ ],
+ 'subject_label' => [
'name' => 'subject_label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label for Subject') ,
+ 'title' => ts('Label for Subject'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.subject_label',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'class_name' => array(
+ ],
+ 'class_name' => [
'name' => 'class_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Suffix for PHP class name implementation') ,
+ 'title' => ts('Suffix for PHP class name implementation'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.class_name',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_site_default' => array(
+ ],
+ 'url_site_default' => [
'name' => 'url_site_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Live Site URL') ,
+ 'title' => ts('Default Live Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_site_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_api_default' => array(
+ ],
+ 'url_api_default' => [
'name' => 'url_api_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default API Site URL') ,
+ 'title' => ts('Default API Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_api_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_recur_default' => array(
+ ],
+ 'url_recur_default' => [
'name' => 'url_recur_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Live Recurring Payments URL') ,
+ 'title' => ts('Default Live Recurring Payments URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_recur_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_button_default' => array(
+ ],
+ 'url_button_default' => [
'name' => 'url_button_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Live Button URL') ,
+ 'title' => ts('Default Live Button URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_button_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_site_test_default' => array(
+ ],
+ 'url_site_test_default' => [
'name' => 'url_site_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test Site URL') ,
+ 'title' => ts('Default Test Site URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_site_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_api_test_default' => array(
+ ],
+ 'url_api_test_default' => [
'name' => 'url_api_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test API URL') ,
+ 'title' => ts('Default Test API URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_api_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_recur_test_default' => array(
+ ],
+ 'url_recur_test_default' => [
'name' => 'url_recur_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test Recurring Payment URL') ,
+ 'title' => ts('Default Test Recurring Payment URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_recur_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'url_button_test_default' => array(
+ ],
+ 'url_button_test_default' => [
'name' => 'url_button_test_default',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Default Test Button URL') ,
+ 'title' => ts('Default Test Button URL'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_processor_type.url_button_test_default',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'billing_mode' => array(
+ ],
+ 'billing_mode' => [
'name' => 'billing_mode',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Billing Mode') ,
- 'description' => 'Billing Mode (deprecated)',
- 'required' => true,
+ 'title' => ts('Billing Mode'),
+ 'description' => ts('Billing Mode (deprecated)'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_processor_type.billing_mode',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::billingMode',
- )
- ) ,
- 'is_recur' => array(
+ ]
+ ],
+ 'is_recur' => [
'name' => 'is_recur',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Processor Type Supports Recurring?') ,
- 'description' => 'Can process recurring contributions',
+ 'title' => ts('Processor Type Supports Recurring?'),
+ 'description' => ts('Can process recurring contributions'),
+ 'where' => 'civicrm_payment_processor_type.is_recur',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'payment_type' => array(
+ ],
+ 'payment_type' => [
'name' => 'payment_type',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Processor Type Payment Type') ,
- 'description' => 'Payment Type: Credit or Debit (deprecated)',
+ 'title' => ts('Processor Type Payment Type'),
+ 'description' => ts('Payment Type: Credit or Debit (deprecated)'),
+ 'where' => 'civicrm_payment_processor_type.payment_type',
'default' => '1',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- ) ,
- 'payment_instrument_id' => array(
+ ],
+ 'payment_instrument_id' => [
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Method') ,
- 'description' => 'Payment Instrument ID',
+ 'title' => ts('Payment Method'),
+ 'description' => ts('Payment Instrument ID'),
+ 'where' => 'civicrm_payment_processor_type.payment_instrument_id',
'default' => '1',
'table_name' => 'civicrm_payment_processor_type',
'entity' => 'PaymentProcessorType',
'bao' => 'CRM_Financial_BAO_PaymentProcessorType',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -493,10 +509,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_processor_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -504,25 +521,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_processor_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name' => array(
+ $indices = [
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_payment_processor_type::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/DAO/PaymentToken.php b/CRM/Financial/DAO/PaymentToken.php
index d5fe14b10fcd..88206dd264f7 100644
--- a/CRM/Financial/DAO/PaymentToken.php
+++ b/CRM/Financial/DAO/PaymentToken.php
@@ -1,347 +1,356 @@
__table = 'civicrm_payment_token';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_id', 'civicrm_payment_processor', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'payment_processor_id', 'civicrm_payment_processor', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'created_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'payment_token_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'payment_token_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Token ID') ,
- 'description' => 'Payment Token ID',
- 'required' => true,
+ 'title' => ts('Payment Token ID'),
+ 'description' => ts('Payment Token ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_token.id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'contact_id' => array(
+ ],
+ 'contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID for the owner of the token',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID for the owner of the token'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_token.contact_id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'payment_processor_id' => array(
+ ],
+ 'payment_processor_id' => [
'name' => 'payment_processor_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Processor ID') ,
- 'required' => true,
+ 'title' => ts('Payment Processor ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_payment_token.payment_processor_id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessor',
- ) ,
- 'token' => array(
+ ],
+ 'token' => [
'name' => 'token',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Token') ,
- 'description' => 'Externally provided token string',
- 'required' => true,
+ 'title' => ts('Token'),
+ 'description' => ts('Externally provided token string'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.token',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'created_date' => array(
+ ],
+ 'created_date' => [
'name' => 'created_date',
'type' => CRM_Utils_Type::T_TIMESTAMP,
- 'title' => ts('Created Date') ,
- 'description' => 'Date created',
+ 'title' => ts('Created Date'),
+ 'description' => ts('Date created'),
+ 'where' => 'civicrm_payment_token.created_date',
'default' => 'CURRENT_TIMESTAMP',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'created_id' => array(
+ ],
+ 'created_id' => [
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Created ID') ,
- 'description' => 'Contact ID of token creator',
+ 'title' => ts('Created ID'),
+ 'description' => ts('Contact ID of token creator'),
+ 'where' => 'civicrm_payment_token.created_id',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'expiry_date' => array(
+ ],
+ 'expiry_date' => [
'name' => 'expiry_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Expiry Date') ,
- 'description' => 'Date this token expires',
+ 'title' => ts('Expiry Date'),
+ 'description' => ts('Date this token expires'),
+ 'where' => 'civicrm_payment_token.expiry_date',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'email' => array(
+ ],
+ 'email' => [
'name' => 'email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Email') ,
- 'description' => 'Email at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Email'),
+ 'description' => ts('Email at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.email',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'billing_first_name' => array(
+ ],
+ 'billing_first_name' => [
'name' => 'billing_first_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Billing First Name') ,
- 'description' => 'Billing first name at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Billing First Name'),
+ 'description' => ts('Billing first name at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.billing_first_name',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'billing_middle_name' => array(
+ ],
+ 'billing_middle_name' => [
'name' => 'billing_middle_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Billing Middle Name') ,
- 'description' => 'Billing middle name at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Billing Middle Name'),
+ 'description' => ts('Billing middle name at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.billing_middle_name',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'billing_last_name' => array(
+ ],
+ 'billing_last_name' => [
'name' => 'billing_last_name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Billing Last Name') ,
- 'description' => 'Billing last name at the time of token creation. Useful for fraud forensics',
+ 'title' => ts('Billing Last Name'),
+ 'description' => ts('Billing last name at the time of token creation. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.billing_last_name',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'masked_account_number' => array(
+ ],
+ 'masked_account_number' => [
'name' => 'masked_account_number',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Masked Account Number') ,
- 'description' => 'Holds the part of the card number or account details that may be retained or displayed',
+ 'title' => ts('Masked Account Number'),
+ 'description' => ts('Holds the part of the card number or account details that may be retained or displayed'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.masked_account_number',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- 'ip_address' => array(
+ ],
+ 'ip_address' => [
'name' => 'ip_address',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('IP Address') ,
- 'description' => 'IP used when creating the token. Useful for fraud forensics',
+ 'title' => ts('IP Address'),
+ 'description' => ts('IP used when creating the token. Useful for fraud forensics'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_payment_token.ip_address',
'table_name' => 'civicrm_payment_token',
'entity' => 'PaymentToken',
'bao' => 'CRM_Financial_DAO_PaymentToken',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -349,10 +358,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_token', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'payment_token', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -360,15 +370,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_token', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'payment_token', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Financial/Form/BatchTransaction.php b/CRM/Financial/Form/BatchTransaction.php
index e43e5573356f..584ed6a338cb 100644
--- a/CRM/Financial/Form/BatchTransaction.php
+++ b/CRM/Financial/Form/BatchTransaction.php
@@ -1,9 +1,9 @@
assign('entityID', self::$_entityID);
if (isset(self::$_entityID)) {
$this->_batchStatusId = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'status_id');
- $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name', 'condition' => " v.value={$this->_batchStatusId}"));
+ $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name', 'condition' => " v.value={$this->_batchStatusId}"]);
$this->_batchStatus = $batchStatuses[$this->_batchStatusId];
$this->assign('statusID', $this->_batchStatusId);
$this->assign('batchStatus', $this->_batchStatus);
$validStatus = FALSE;
- if (in_array($this->_batchStatus, array('Open', 'Reopened'))) {
+ if (in_array($this->_batchStatus, ['Open', 'Reopened'])) {
$validStatus = TRUE;
}
$this->assign('validStatus', $validStatus);
- $this->_values = civicrm_api3('Batch', 'getSingle', array('id' => self::$_entityID));
+ $this->_values = civicrm_api3('Batch', 'getSingle', ['id' => self::$_entityID]);
$batchTitle = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'title');
- CRM_Utils_System::setTitle(ts('Accounting Batch - %1', array(1 => $batchTitle)));
+ CRM_Utils_System::setTitle(ts('Accounting Batch - %1', [1 => $batchTitle]));
- $columnHeaders = array(
+ $columnHeaders = [
'created_by' => ts('Created By'),
'status' => ts('Status'),
'description' => ts('Description'),
@@ -81,7 +81,7 @@ public function preProcess() {
'total' => ts('Expected Total Amount'),
'assigned_total' => ts('Actual Total Amount'),
'opened_date' => ts('Opened'),
- );
+ ];
$this->assign('columnHeaders', $columnHeaders);
}
}
@@ -95,7 +95,7 @@ public function buildQuickForm() {
}
// do not build rest of form unless it is open/reopened batch
- if (!in_array($this->_batchStatus, array('Open', 'Reopened'))) {
+ if (!in_array($this->_batchStatus, ['Open', 'Reopened'])) {
return;
}
@@ -121,14 +121,14 @@ public function buildQuickForm() {
// multiselect for groups
if ($this->_group) {
$this->add('select', 'group', ts('Groups'), $this->_group, FALSE,
- array('id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
}
$contactTags = CRM_Core_BAO_Tag::getTags();
if ($contactTags) {
$this->add('select', 'contact_tags', ts('Tags'), $contactTags, FALSE,
- array('id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2')
+ ['id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2']
);
}
CRM_Contribute_BAO_Query::buildSearchForm($this);
@@ -137,37 +137,37 @@ public function buildQuickForm() {
$this->add('select',
'trans_remove',
ts('Task'),
- array('' => ts('- actions -')) + array('Remove' => ts('Remove from Batch')));
+ ['' => ts('- actions -')] + ['Remove' => ts('Remove from Batch')]);
$this->add('submit', 'rSubmit', ts('Go'),
- array(
+ [
'class' => 'crm-form-submit',
'id' => 'GoRemove',
- ));
+ ]);
self::$_entityID = CRM_Utils_Request::retrieve('bid', 'Positive');
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'submit',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
$this->addElement('checkbox', 'toggleSelect', NULL, NULL);
$this->add('select',
'trans_assign',
ts('Task'),
- array('' => ts('- actions -')) + array('Assign' => ts('Assign to Batch')));
+ ['' => ts('- actions -')] + ['Assign' => ts('Assign to Batch')]);
$this->add('submit', 'submit', ts('Go'),
- array(
+ [
'class' => 'crm-form-submit',
'id' => 'Go',
- ));
+ ]);
$this->applyFilter('__ALL__', 'trim');
$this->addElement('hidden', 'batch_id', self::$_entityID);
@@ -180,12 +180,12 @@ public function buildQuickForm() {
*/
public function setDefaultValues() {
// do not setdefault unless it is open/reopened batch
- if (!in_array($this->_batchStatus, array('Open', 'Reopened'))) {
+ if (!in_array($this->_batchStatus, ['Open', 'Reopened'])) {
return;
}
if (isset(self::$_entityID)) {
$paymentInstrumentID = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'payment_instrument_id');
- $defaults['payment_instrument_id'] = $paymentInstrumentID;
+ $defaults['contribution_payment_instrument_id'] = $paymentInstrumentID;
$this->assign('paymentInstrumentID', $paymentInstrumentID);
}
return $defaults;
@@ -198,20 +198,20 @@ public function setDefaultValues() {
*/
public function &links() {
if (!(self::$_links)) {
- self::$_links = array(
- 'view' => array(
+ self::$_links = [
+ 'view' => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&id=%%contid%%&cid=%%cid%%&action=view&context=contribution&selectedChild=contribute',
'title' => ts('View Contribution'),
- ),
- 'assign' => array(
+ ],
+ 'assign' => [
'name' => ts('Assign'),
'ref' => 'disable-action',
'title' => ts('Assign Transaction'),
'extra' => 'onclick = "assignRemove( %%id%%,\'' . 'assign' . '\' );"',
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
diff --git a/CRM/Financial/Form/Export.php b/CRM/Financial/Form/Export.php
index 46034b1708e4..966a179324d6 100644
--- a/CRM/Financial/Form/Export.php
+++ b/CRM/Financial/Form/Export.php
@@ -1,9 +1,9 @@
_batchIds = $this->get('batchIds');
}
- if (!empty($_GET['export_format']) && in_array($_GET['export_format'], array('IIF', 'CSV'))) {
+ if (!empty($_GET['export_format']) && in_array($_GET['export_format'], ['IIF', 'CSV'])) {
$this->_exportFormat = $_GET['export_format'];
}
}
@@ -89,8 +98,7 @@ public function preProcess() {
$this->_batchIds = $this->_id;
}
- $allBatchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
- $this->_exportStatusId = CRM_Utils_Array::key('Exported', $allBatchStatus);
+ $this->_exportStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_DAO_Batch', 'status_id', 'Exported');
// check if batch status is valid, do not allow exported batches to export again
$batchStatus = CRM_Batch_BAO_Batch::getBatchStatuses($this->_batchIds);
@@ -121,26 +129,26 @@ public function buildQuickForm() {
}
}
- $optionTypes = array(
+ $optionTypes = [
'IIF' => ts('Export to IIF'),
'CSV' => ts('Export to CSV'),
- );
+ ];
$this->addRadio('export_format', NULL, $optionTypes, NULL, ' ', TRUE);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'next',
'name' => ts('Export Batch'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
}
@@ -154,7 +162,7 @@ public function postProcess() {
}
if ($this->_id) {
- $batchIds = array($this->_id);
+ $batchIds = [$this->_id];
}
elseif (!empty($this->_batchIds)) {
$batchIds = explode(',', $this->_batchIds);
@@ -175,7 +183,7 @@ public function postProcess() {
CRM_Batch_BAO_Batch::create($batchParams);
}
- CRM_Batch_BAO_Batch::exportFinancialBatch($batchIds, $this->_exportFormat);
+ CRM_Batch_BAO_Batch::exportFinancialBatch($batchIds, $this->_exportFormat, $this->_downloadFile);
}
}
diff --git a/CRM/Financial/Form/FinancialAccount.php b/CRM/Financial/Form/FinancialAccount.php
index eff3122f638d..6b38724a81c4 100644
--- a/CRM/Financial/Form/FinancialAccount.php
+++ b/CRM/Financial/Form/FinancialAccount.php
@@ -1,9 +1,9 @@
_id) {
- $params = array(
+ $params = [
'id' => $this->_id,
- );
+ ];
$financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, CRM_Core_DAO::$_nullArray);
$financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
if ($financialAccount->financial_account_type_id == $financialAccountTypeId
@@ -84,15 +83,15 @@ public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialAccount');
$this->add('text', 'name', ts('Name'), $attributes['name'], TRUE);
$this->addRule('name', ts('A financial type with this name already exists. Please select another name.'),
- 'objectExists', array('CRM_Financial_DAO_FinancialAccount', $this->_id));
+ 'objectExists', ['CRM_Financial_DAO_FinancialAccount', $this->_id]);
$this->add('text', 'description', ts('Description'), $attributes['description']);
$this->add('text', 'accounting_code', ts('Accounting Code'), $attributes['accounting_code']);
$elementAccounting = $this->add('text', 'account_type_code', ts('Account Type Code'), $attributes['account_type_code']);
- $this->addEntityRef('contact_id', ts('Owner'), array(
- 'api' => array('params' => array('contact_type' => 'Organization')),
+ $this->addEntityRef('contact_id', ts('Owner'), [
+ 'api' => ['params' => ['contact_type' => 'Organization']],
'create' => TRUE,
- ));
+ ]);
$this->add('text', 'tax_rate', ts('Tax Rate'), $attributes['tax_rate']);
$this->add('checkbox', 'is_deductible', ts('Tax-Deductible?'));
$elementActive = $this->add('checkbox', 'is_active', ts('Enabled?'));
@@ -107,7 +106,7 @@ public function buildQuickForm() {
$financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
if (!empty($financialAccountType)) {
$element = $this->add('select', 'financial_account_type_id', ts('Financial Account Type'),
- array('' => '- select -') + $financialAccountType, TRUE, array('class' => 'crm-select2 huge'));
+ ['' => '- select -'] + $financialAccountType, TRUE, ['class' => 'crm-select2 huge']);
if ($this->_isARFlag) {
$element->freeze();
$elementAccounting->freeze();
@@ -121,9 +120,9 @@ public function buildQuickForm() {
if ($this->_action == CRM_Core_Action::UPDATE &&
CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $this->_id, 'is_reserved')
) {
- $this->freeze(array('name', 'description', 'is_active'));
+ $this->freeze(['name', 'description', 'is_active']);
}
- $this->addFormRule(array('CRM_Financial_Form_FinancialAccount', 'formRule'), $this);
+ $this->addFormRule(['CRM_Financial_Form_FinancialAccount', 'formRule'], $this);
}
/**
@@ -138,7 +137,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errorMsg = array();
+ $errorMsg = [];
$financialAccountTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' "));
if (isset($values['is_tax'])) {
if ($values['financial_account_type_id'] != $financialAccountTypeId) {
@@ -156,10 +155,10 @@ public static function formRule($values, $files, $self) {
if ($self->_action & CRM_Core_Action::UPDATE) {
if (!(isset($values['is_tax']))) {
$relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
- $params = array(
+ $params = [
'financial_account_id' => $self->_id,
'account_relationship' => $relationshipId,
- );
+ ];
$result = CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
if ($result) {
$errorMsg['is_tax'] = ts('Is Tax? must be set for this financial account');
@@ -200,9 +199,16 @@ public function postProcess() {
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
}
-
+ foreach ([
+ 'is_active',
+ 'is_deductible',
+ 'is_tax',
+ 'is_default',
+ ] as $field) {
+ $params[$field] = CRM_Utils_Array::value($field, $params, FALSE);
+ }
$financialAccount = CRM_Financial_BAO_FinancialAccount::add($params);
- CRM_Core_Session::setStatus(ts('The Financial Account \'%1\' has been saved.', array(1 => $financialAccount->name)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The Financial Account \'%1\' has been saved.', [1 => $financialAccount->name]), ts('Saved'), 'success');
}
}
diff --git a/CRM/Financial/Form/FinancialBatch.php b/CRM/Financial/Form/FinancialBatch.php
index 7ae2fc505a86..283db9a3a241 100644
--- a/CRM/Financial/Form/FinancialBatch.php
+++ b/CRM/Financial/Form/FinancialBatch.php
@@ -1,9 +1,9 @@
set("context", $context);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
parent::preProcess();
$session = CRM_Core_Session::singleton();
if ($this->_id) {
- $permissions = array(
- CRM_Core_Action::UPDATE => array(
- 'permission' => array(
+ $permissions = [
+ CRM_Core_Action::UPDATE => [
+ 'permission' => [
'edit own manual batches',
'edit all manual batches',
- ),
+ ],
'actionName' => 'edit',
- ),
- CRM_Core_Action::DELETE => array(
- 'permission' => array(
+ ],
+ CRM_Core_Action::DELETE => [
+ 'permission' => [
'delete own manual batches',
'delete all manual batches',
- ),
+ ],
'actionName' => 'delete',
- ),
- );
+ ],
+ ];
$createdID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $this->_id, 'created_id');
if (!empty($permissions[$this->_action])) {
@@ -95,32 +95,32 @@ public function buildQuickForm() {
$this->applyFilter('__ALL__', 'trim');
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'next',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
+ $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_BAO_Batch', 'status_id');
// unset exported status
- $exportedStatusId = CRM_Utils_Array::key('Exported', $batchStatus);
+ $exportedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Exported');
unset($batchStatus[$exportedStatusId]);
- $this->add('select', 'status_id', ts('Batch Status'), array('' => ts('- select -')) + $batchStatus, TRUE);
- $this->freeze(array('status_id'));
+ $this->add('select', 'status_id', ts('Batch Status'), ['' => ts('- select -')] + $batchStatus, TRUE);
+ $this->freeze(['status_id']);
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Batch_DAO_Batch');
@@ -130,14 +130,14 @@ public function buildQuickForm() {
$this->add('textarea', 'description', ts('Description'), $attributes['description']);
$this->add('select', 'payment_instrument_id', ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
FALSE
);
$this->add('text', 'total', ts('Total Amount'), $attributes['total']);
$this->add('text', 'item_count', ts('Number of Transactions'), $attributes['item_count']);
- $this->addFormRule(array('CRM_Financial_Form_FinancialBatch', 'formRule'), $this);
+ $this->addFormRule(['CRM_Financial_Form_FinancialBatch', 'formRule'], $this);
}
/**
@@ -170,7 +170,7 @@ public function setDefaultValues() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($values['contact_name']) && !is_numeric($values['created_id'])) {
$errors['contact_name'] = ts('Please select a valid contact.');
}
@@ -196,7 +196,7 @@ public static function formRule($values, $files, $self) {
public function postProcess() {
$session = CRM_Core_Session::singleton();
$params = $this->exportValues();
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id');
+ $closedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed');
if ($this->_id) {
$params['id'] = $this->_id;
}
@@ -209,9 +209,8 @@ public function postProcess() {
}
if ($this->_action & CRM_Core_Action::ADD) {
- $batchMode = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'mode_id', array('labelColumn' => 'name'));
- $params['mode_id'] = CRM_Utils_Array::key('Manual Batch', $batchMode);
- $params['status_id'] = CRM_Utils_Array::key('Open', $batchStatus);
+ $params['mode_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'mode_id', 'Manual Batch');
+ $params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Open');
$params['created_date'] = date('YmdHis');
if (empty($params['created_id'])) {
$params['created_id'] = $session->get('userID');
@@ -221,30 +220,30 @@ public function postProcess() {
}
elseif ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
$details = "{$params['title']} batch has been edited by this contact.";
- if (CRM_Utils_Array::value($params['status_id'], $batchStatus) == 'Closed') {
+ if ($params['status_id'] === $closedStatusId) {
$details = "{$params['title']} batch has been closed by this contact.";
}
$activityTypeName = 'Edit Batch';
}
+ // FIXME: What happens if we get to here and no activityType is defined?
+
$batch = CRM_Batch_BAO_Batch::create($params);
//set batch id
$this->_id = $batch->id;
- $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
-
// create activity.
- $activityParams = array(
- 'activity_type_id' => array_search($activityTypeName, $activityTypes),
+ $activityParams = [
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeName),
'subject' => $batch->title . "- Batch",
- 'status_id' => 2,
- 'priority_id' => 2,
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed'),
+ 'priority_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_DAO_Activity', 'priority_id', 'Normal'),
'activity_date_time' => date('YmdHis'),
'source_contact_id' => $session->get('userID'),
'source_contact_qid' => $session->get('userID'),
'details' => $details,
- );
+ ];
CRM_Activity_BAO_Activity::create($activityParams);
@@ -252,7 +251,7 @@ public function postProcess() {
$context = $this->get("context");
if ($batch->title) {
- CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", array(1 => $batch->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("'%1' batch has been saved.", [1 => $batch->title]), ts('Saved'), 'success');
}
if ($buttonName == $this->getButtonName('next', 'new') & $this->_action == CRM_Core_Action::UPDATE) {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
@@ -262,7 +261,7 @@ public function postProcess() {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/financial/batch',
"reset=1&action=add"));
}
- elseif (CRM_Utils_Array::value($batch->status_id, $batchStatus) == 'Closed') {
+ elseif ($batch->status_id === $closedStatusId) {
$session->replaceUserContext(CRM_Utils_System::url('civicrm', 'reset=1'));
}
elseif (($buttonName == $this->getButtonName('next') & $this->_action == CRM_Core_Action::UPDATE) ||
@@ -291,11 +290,11 @@ public function postProcess() {
public function checkPermissions($action, $permissions, $createdID, $userContactID, $actionName) {
if ((CRM_Core_Permission::check($permissions[0]) || CRM_Core_Permission::check($permissions[1]))) {
if (CRM_Core_Permission::check($permissions[0]) && $userContactID != $createdID && !CRM_Core_Permission::check($permissions[1])) {
- CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), array(1 => $actionName));
+ CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
}
}
else {
- CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), array(1 => $actionName));
+ CRM_Core_Error::statusBounce(ts('You dont have permission to %1 this batch'), [1 => $actionName]);
}
}
diff --git a/CRM/Financial/Form/FinancialType.php b/CRM/Financial/Form/FinancialType.php
index caa7f7eaae32..f64304a648dd 100644
--- a/CRM/Financial/Form/FinancialType.php
+++ b/CRM/Financial/Form/FinancialType.php
@@ -1,9 +1,9 @@
_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
parent::preProcess();
+ $this->setPageTitle(ts('Financial Type'));
+ if ($this->_id) {
+ $this->_title = CRM_Core_PseudoConstant::getLabel(
+ 'CRM_Financial_BAO_FinancialType',
+ 'financial_type',
+ $this->_id
+ );
+ $this->assign('aid', $this->_id);
+ }
+ }
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'name' => [
+ 'name' => 'name',
+ 'required' => TRUE,
+ ],
+ 'description' => ['name' => 'description'],
+ 'is_deductible' => [
+ 'name' => 'is_deductible',
+ 'description' => ts('Are contributions of this type tax-deductible?'),
+ ],
+ 'is_reserved' => ['name' => 'is_reserved'],
+ 'is_active' => ['name' => 'is_active'],
+ ];
+ }
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'FinancialType';
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('WARNING: You cannot delete a financial type if it is currently used by any Contributions, Contribution Pages or Membership Types. Consider disabling this option instead.') . ts('Deleting a financial type cannot be undone.') . ts('Do you want to continue?');
}
/**
* Build the form object.
*/
public function buildQuickForm() {
- parent::buildQuickForm();
- $this->setPageTitle(ts('Financial Type'));
-
- $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- if ($this->_id) {
- $this->_title = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_id, 'name');
- }
+ self::buildQuickEntityForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
- $this->applyFilter('__ALL__', 'trim');
- $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'name'), TRUE);
-
- $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'description'));
-
- $this->add('checkbox', 'is_deductible', ts('Tax-Deductible?'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'is_deductible'));
- $this->add('checkbox', 'is_active', ts('Enabled?'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'is_active'));
- $this->add('checkbox', 'is_reserved', ts('Reserved?'), CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialType', 'is_reserved'));
- if ($this->_action == CRM_Core_Action::UPDATE) {
- $this->assign('aid', $this->_id);
- }
- if ($this->_action == CRM_Core_Action::UPDATE && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_id, 'is_reserved', 'vid')) {
- $this->freeze(array('is_active'));
+ if ($this->_action == CRM_Core_Action::UPDATE && CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $this->_id, 'is_reserved')) {
+ $this->freeze(['is_active']);
}
-
$this->addRule('name', ts('A financial type with this name already exists. Please select another name.'), 'objectExists',
- array('CRM_Financial_DAO_FinancialType', $this->_id)
+ ['CRM_Financial_DAO_FinancialType', $this->_id]
);
}
@@ -95,35 +138,46 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected financial type has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $params = $ids = array();
// store the submitted values in an array
$params = $this->exportValues();
-
- if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['financialType'] = $this->_id;
+ if ($this->_id) {
+ $params['id'] = $this->_id;
}
-
- $financialType = CRM_Financial_BAO_FinancialType::add($params, $ids);
+ foreach ([
+ 'is_active',
+ 'is_reserved',
+ 'is_deductible',
+ ] as $field) {
+ $params[$field] = CRM_Utils_Array::value($field, $params, FALSE);
+ }
+ $financialType = civicrm_api3('FinancialType', 'create', $params);
if ($this->_action & CRM_Core_Action::UPDATE) {
$url = CRM_Utils_System::url('civicrm/admin/financial/financialType', 'reset=1&action=browse');
- CRM_Core_Session::setStatus(ts('The financial type "%1" has been updated.', array(1 => $financialType->name)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The financial type "%1" has been updated.', [1 => $params['name']]), ts('Saved'), 'success');
}
else {
- $url = CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', 'reset=1&action=browse&aid=' . $financialType->id);
- $statusArray = array(
- 1 => $financialType->name,
- 2 => $financialType->name,
- 3 => CRM_Utils_Array::value(0, $financialType->titles),
- 4 => CRM_Utils_Array::value(1, $financialType->titles),
- 5 => CRM_Utils_Array::value(2, $financialType->titles),
- );
- if (empty($financialType->titles)) {
- $text = ts('Your Financial "%1" Type has been created and assigned to an existing financial account with the same title. You should review the assigned account and determine whether additional account relationships are needed.', $statusArray);
+ $url = CRM_Utils_System::url('civicrm/admin/financial/financialType/accounts', 'reset=1&action=browse&aid=' . $financialType['id']);
+
+ $statusArray = [
+ 1 => $params['name'],
+ ];
+ $financialAccounts = civicrm_api3('EntityFinancialAccount', 'get', [
+ 'return' => ["financial_account_id.name"],
+ 'entity_table' => "civicrm_financial_type",
+ 'entity_id' => $financialType['id'],
+ 'options' => ['sort' => "id"],
+ 'account_relationship' => ['!=' => "Income Account is"],
+ ]);
+ if (!empty($financialAccounts['values'])) {
+ foreach ($financialAccounts['values'] as $financialAccount) {
+ $statusArray[] = $financialAccount['financial_account_id.name'];
+ }
+ $text = ts('Your Financial "%1" Type has been created, along with a corresponding income account "%1". That income account, along with standard financial accounts "%2", "%3" and "%4" have been linked to the financial type. You may edit or replace those relationships here.', $statusArray);
}
else {
- $text = ts('Your Financial "%1" Type has been created, along with a corresponding income account "%2". That income account, along with standard financial accounts "%3", "%4" and "%5" have been linked to the financial type. You may edit or replace those relationships here.', $statusArray);
+ $text = ts('Your Financial "%1" Type has been created and assigned to an existing financial account with the same title. You should review the assigned account and determine whether additional account relationships are needed.', $statusArray);
}
- CRM_Core_Session::setStatus($text, ts('Saved'), 'success', array('expires' => 0));
+ CRM_Core_Session::setStatus($text, ts('Saved'), 'success', ['expires' => 0]);
}
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Financial/Form/FinancialTypeAccount.php b/CRM/Financial/Form/FinancialTypeAccount.php
index 2055f5007975..e0940a738af1 100644
--- a/CRM/Financial/Form/FinancialTypeAccount.php
+++ b/CRM/Financial/Form/FinancialTypeAccount.php
@@ -1,9 +1,9 @@
ts('Financial Type Accounts'),
'url' => $url,
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -125,7 +125,7 @@ public function buildQuickForm() {
}
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Financial_BAO_FinancialTypeAccount::retrieve($params, $defaults);
$this->setDefaults($defaults);
$financialAccountTitle = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $defaults['financial_account_id'], 'name');
@@ -147,7 +147,7 @@ public function buildQuickForm() {
$element = $this->add('select',
'account_relationship',
ts('Financial Account Relationship'),
- array('select' => ts('- Select Financial Account Relationship -')) + $AccountTypeRelationship,
+ ['select' => ts('- Select Financial Account Relationship -')] + $AccountTypeRelationship,
TRUE
);
}
@@ -162,12 +162,12 @@ public function buildQuickForm() {
$financialAccountType = CRM_Utils_Array::value($this->_submitValues['account_relationship'], $financialAccountType);
$result = CRM_Contribute_PseudoConstant::financialAccount(NULL, $financialAccountType);
- $financialAccountSelect = array('' => ts('- select -')) + $result;
+ $financialAccountSelect = ['' => ts('- select -')] + $result;
}
else {
- $financialAccountSelect = array(
+ $financialAccountSelect = [
'select' => ts('- select -'),
- ) + CRM_Contribute_PseudoConstant::financialAccount();
+ ] + CRM_Contribute_PseudoConstant::financialAccount();
}
}
if ($this->_action == CRM_Core_Action::UPDATE) {
@@ -175,7 +175,7 @@ public function buildQuickForm() {
$financialAccountType = $financialAccountType[$this->_defaultValues['account_relationship']];
$result = CRM_Contribute_PseudoConstant::financialAccount(NULL, $financialAccountType);
- $financialAccountSelect = array('' => ts('- select -')) + $result;
+ $financialAccountSelect = ['' => ts('- select -')] + $result;
}
$this->add('select',
@@ -185,24 +185,23 @@ public function buildQuickForm() {
TRUE
);
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'next',
- 'name' => ts('Save and New'),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
- $this->addFormRule(array('CRM_Financial_Form_FinancialTypeAccount', 'formRule'), $this);
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'next',
+ 'name' => ts('Save and New'),
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+ $this->addFormRule(['CRM_Financial_Form_FinancialTypeAccount', 'formRule'], $this);
}
/**
@@ -217,7 +216,7 @@ public function buildQuickForm() {
* list of errors to be posted back to the form
*/
public static function formRule($values, $files, $self) {
- $errorMsg = array();
+ $errorMsg = [];
$errorFlag = FALSE;
if ($self->_action == CRM_Core_Action::DELETE) {
$relationValues = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship');
@@ -238,12 +237,12 @@ public static function formRule($values, $files, $self) {
$errorMsg['financial_account_id'] = 'Financial Account is a required field.';
}
if (!empty($values['account_relationship']) && !empty($values['financial_account_id'])) {
- $params = array(
+ $params = [
'account_relationship' => $values['account_relationship'],
'entity_id' => $self->_aid,
'entity_table' => 'civicrm_financial_type',
- );
- $defaults = array();
+ ];
+ $defaults = [];
if ($self->_action == CRM_Core_Action::ADD) {
$relationshipId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
$isTax = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialAccount', $values['financial_account_id'], 'is_tax');
@@ -286,7 +285,7 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected financial type account has been deleted.'));
}
else {
- $params = $ids = array();
+ $params = $ids = [];
// store the submitted values in an array
$params = $this->exportValues();
diff --git a/CRM/Financial/Form/FrontEndPaymentFormTrait.php b/CRM/Financial/Form/FrontEndPaymentFormTrait.php
new file mode 100644
index 000000000000..7380cdd857be
--- /dev/null
+++ b/CRM/Financial/Form/FrontEndPaymentFormTrait.php
@@ -0,0 +1,82 @@
+ $value) {
+ foreach ($value as $k => $v) {
+ if (isset($v['tax_rate']) && $v['tax_rate'] != '') {
+ // These only need assigning once, but code is more readable with them here
+ $this->assign('getTaxDetails', TRUE);
+ $this->assign('taxTerm', CRM_Invoicing_Utils::getTaxTerm());
+ // Cast to float to display without trailing zero decimals
+ $tplLineItems[$key][$k]['tax_rate'] = (float) $v['tax_rate'];
+ }
+ }
+ }
+ }
+
+ /**
+ * Assign line items to the template.
+ *
+ * @param $tplLineItems
+ */
+ protected function assignLineItemsToTemplate($tplLineItems) {
+ // @todo this should be a hook that invoicing code hooks into rather than a call to it.
+ $this->alterLineItemsForTemplate($tplLineItems);
+ $this->assign('lineItem', $tplLineItems);
+ }
+
+}
diff --git a/CRM/Financial/Form/Payment.php b/CRM/Financial/Form/Payment.php
index ba9412b4d789..9deb8ea26554 100644
--- a/CRM/Financial/Form/Payment.php
+++ b/CRM/Financial/Form/Payment.php
@@ -1,9 +1,9 @@
_formName = CRM_Utils_Request::retrieve('formName', 'String', $this);
+
$this->_values['custom_pre_id'] = CRM_Utils_Request::retrieve('pre_profile_id', 'Integer', $this);
$this->_paymentProcessorID = CRM_Utils_Request::retrieve('processor_id', 'Integer', CRM_Core_DAO::$_nullObject,
@@ -72,19 +79,19 @@ public function preProcess() {
CRM_Core_Payment_ProcessorForm::preProcess($this);
- self::addCreditCardJs($this->_paymentProcessorID);
-
- $this->assign('paymentProcessorID', $this->_paymentProcessorID);
- $this->assign('currency', $this->currency);
-
$this->assign('suppressForm', TRUE);
$this->controller->_generateQFKey = FALSE;
}
/**
+ * Get currency
+ *
+ * @param array $submittedValues
+ * Required for consistency with other form methods.
+ *
* @return string
*/
- public function getCurrency() {
+ public function getCurrency($submittedValues = []) {
return $this->currency;
}
@@ -112,7 +119,19 @@ public function setDefaultValues() {
*/
public static function addCreditCardJs($paymentProcessorID = NULL, $region = 'billing-block') {
$creditCards = CRM_Financial_BAO_PaymentProcessor::getCreditCards($paymentProcessorID);
- $creditCardTypes = CRM_Core_Payment_Form::getCreditCardCSSNames($creditCards);
+ if (empty($creditCards)) {
+ $creditCards = CRM_Contribute_PseudoConstant::creditCard();
+ }
+ $creditCardTypes = [];
+ foreach ($creditCards as $name => $label) {
+ $creditCardTypes[$name] = [
+ 'label' => $label,
+ 'name' => $name,
+ 'css_key' => self::getCssLabelFriendlyName($name),
+ 'pattern' => self::getCardPattern($name),
+ ];
+ }
+
CRM_Core_Resources::singleton()
// CRM-20516: add BillingBlock script on billing-block region
// to support this feature in payment form snippet too.
@@ -122,4 +141,49 @@ public static function addCreditCardJs($paymentProcessorID = NULL, $region = 'bi
->addScript('CRM.config.creditCardTypes = ' . json_encode($creditCardTypes) . ';', '-9999', $region);
}
+ /**
+ * Get css friendly labels for credit cards.
+ *
+ * We add the icons based on these css names which are lower cased
+ * and only AlphaNumeric (+ _).
+ *
+ * @param $key
+ *
+ * @return string
+ */
+ protected static function getCssLabelFriendlyName($key) {
+ $key = str_replace(' ', '', $key);
+ $key = preg_replace('/[^a-zA-Z0-9]/', '_', $key);
+ $key = strtolower($key);
+
+ return $key;
+ }
+
+ /**
+ * Get the pattern that can be used to determine the card type.
+ *
+ * We do a strotolower comparison as we don't know what case people might have if they
+ * are using a non-std one like dinersclub.
+ *
+ * @param $key
+ *
+ * Based on http://davidwalsh.name/validate-credit-cards
+ * See also https://en.wikipedia.org/wiki/Credit_card_numbers
+ *
+ * @return string
+ */
+ protected static function getCardPattern($key) {
+ $cardMappings = [
+ 'mastercard' => '(5[1-5][0-9]{2}|2[3-6][0-9]{2}|22[3-9][0-9]|222[1-9]|27[0-1][0-9]|2720)[0-9]{12}',
+ 'visa' => '4(?:[0-9]{12}|[0-9]{15})',
+ 'amex' => '3[47][0-9]{13}',
+ 'dinersclub' => '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
+ 'carteblanche' => '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
+ 'discover' => '6011[0-9]{12}',
+ 'jcb' => '(?:3[0-9]{15}|(2131|1800)[0-9]{11})',
+ 'unionpay' => '62(?:[0-9]{14}|[0-9]{17})',
+ ];
+ return isset($cardMappings[strtolower($key)]) ? $cardMappings[strtolower($key)] : '';
+ }
+
}
diff --git a/CRM/Financial/Form/PaymentEdit.php b/CRM/Financial/Form/PaymentEdit.php
index 72e97e7eb280..105b98641c14 100644
--- a/CRM/Financial/Form/PaymentEdit.php
+++ b/CRM/Financial/Form/PaymentEdit.php
@@ -1,9 +1,9 @@
assign('id', $this->_id);
$this->_contributionID = CRM_Utils_Request::retrieve('contribution_id', 'Positive', $this);
- $this->_values = civicrm_api3('FinancialTrxn', 'getsingle', array('id' => $this->_id));
+ $this->_values = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $this->_id]);
if (!empty($this->_values['payment_processor_id'])) {
- CRM_Core_Error::statusBounce(ts('You cannot update this payment'));
+ CRM_Core_Error::statusBounce(ts('You cannot update this payment as it is tied to a payment processor'));
}
}
@@ -81,7 +82,13 @@ public function preProcess() {
* @return array
*/
public function setDefaultValues() {
- return $this->_values;
+ $defaults = $this->_values;
+ // Format money fields - localize for display
+ $moneyFields = ['total_amount', 'fee_amount', 'net_amount'];
+ foreach ($moneyFields as $field) {
+ $defaults[$field] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($this->_values[$field]);
+ }
+ return $defaults;
}
/**
@@ -94,10 +101,10 @@ public function buildQuickForm() {
$this->assign('paymentFields', $paymentFields);
foreach ($paymentFields as $name => $paymentField) {
if (!empty($paymentField['add_field'])) {
- $attributes = array(
+ $attributes = [
'entity' => 'FinancialTrxn',
'name' => $name,
- );
+ ];
$this->addField($name, $attributes, $paymentField['is_required']);
}
else {
@@ -111,19 +118,19 @@ public function buildQuickForm() {
}
$this->assign('currency', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $this->_values['currency'], 'symbol', 'name'));
- $this->addFormRule(array(__CLASS__, 'formRule'), $this);
+ $this->addFormRule([__CLASS__, 'formRule'], $this);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'submit',
'name' => ts('Update'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -139,7 +146,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
// if Credit Card is chosen and pan_truncation is not NULL ensure that it's value is numeric else throw validation error
if (CRM_Core_PseudoConstant::getName('CRM_Financial_DAO_FinancialTrxn', 'payment_instrument_id', $fields['payment_instrument_id']) == 'Credit Card' &&
@@ -156,12 +163,12 @@ public static function formRule($fields, $files, $self) {
* Process the form submission.
*/
public function postProcess() {
- $params = array(
+ $params = [
'id' => $this->_id,
'payment_instrument_id' => $this->_submitValues['payment_instrument_id'],
'trxn_id' => CRM_Utils_Array::value('trxn_id', $this->_submitValues),
'trxn_date' => CRM_Utils_Array::value('trxn_date', $this->_submitValues, date('YmdHis')),
- );
+ ];
$paymentInstrumentName = CRM_Core_PseudoConstant::getName('CRM_Financial_DAO_FinancialTrxn', 'payment_instrument_id', $params['payment_instrument_id']);
if ($paymentInstrumentName == 'Credit Card') {
@@ -199,18 +206,18 @@ protected function submit($submittedValues) {
$previousFinanciaTrxn['contribution_id'] = $newFinancialTrxn['contribution_id'] = $this->_contributionID;
$newFinancialTrxn['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($submittedValues['payment_instrument_id']);
- foreach (array('total_amount', 'fee_amount', 'net_amount', 'currency', 'is_payment', 'status_id') as $fieldName) {
+ foreach (['total_amount', 'fee_amount', 'net_amount', 'currency', 'is_payment', 'status_id'] as $fieldName) {
$newFinancialTrxn[$fieldName] = $this->_values[$fieldName];
}
- foreach (array($previousFinanciaTrxn, $newFinancialTrxn) as $financialTrxnParams) {
- civicrm_api3('FinancialTrxn', 'create', $financialTrxnParams);
- $trxnParams = array(
+ foreach ([$previousFinanciaTrxn, $newFinancialTrxn] as $financialTrxnParams) {
+ $financialTrxn = civicrm_api3('FinancialTrxn', 'create', $financialTrxnParams);
+ $trxnParams = [
'total_amount' => $financialTrxnParams['total_amount'],
'contribution_id' => $this->_contributionID,
- );
+ ];
$contributionTotalAmount = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionID, 'total_amount');
- CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $submittedValues['id'], $contributionTotalAmount);
+ CRM_Contribute_BAO_Contribution::assignProportionalLineItems($trxnParams, $financialTrxn['id'], $contributionTotalAmount);
}
}
else {
@@ -229,7 +236,7 @@ protected function submit($submittedValues) {
public function testSubmit($params) {
$this->_id = $params['id'];
$this->_contributionID = $params['contribution_id'];
- $this->_values = civicrm_api3('FinancialTrxn', 'getsingle', array('id' => $params['id']));
+ $this->_values = civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $params['id']]);
$this->submit($params);
}
@@ -246,7 +253,7 @@ public static function updateRelatedContribution($params, $contributionID) {
$contributionDAO->id = $contributionID;
$contributionDAO->find(TRUE);
- foreach (array('trxn_id', 'check_number') as $fieldName) {
+ foreach (['trxn_id', 'check_number'] as $fieldName) {
if (!empty($params[$fieldName])) {
if (!empty($contributionDAO->$fieldName)) {
$values = explode(',', $contributionDAO->$fieldName);
@@ -267,49 +274,49 @@ public static function updateRelatedContribution($params, $contributionID) {
* Get payment fields
*/
public function getPaymentFields() {
- $paymentFields = array(
- 'payment_instrument_id' => array(
+ $paymentFields = [
+ 'payment_instrument_id' => [
'is_required' => TRUE,
'add_field' => TRUE,
- ),
- 'check_number' => array(
+ ],
+ 'check_number' => [
'is_required' => FALSE,
'add_field' => TRUE,
- ),
+ ],
// @TODO we need to show card type icon in place of select field
- 'card_type_id' => array(
+ 'card_type_id' => [
'is_required' => FALSE,
'add_field' => TRUE,
- ),
- 'pan_truncation' => array(
+ ],
+ 'pan_truncation' => [
'is_required' => FALSE,
'add_field' => TRUE,
- ),
- 'trxn_id' => array(
+ ],
+ 'trxn_id' => [
'add_field' => TRUE,
'is_required' => FALSE,
- ),
- 'trxn_date' => array(
+ ],
+ 'trxn_date' => [
'htmlType' => 'datepicker',
'name' => 'trxn_date',
'title' => ts('Transaction Date'),
'is_required' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'date' => 'yyyy-mm-dd',
'time' => 24,
- ),
- ),
- 'total_amount' => array(
+ ],
+ ],
+ 'total_amount' => [
'htmlType' => 'text',
'name' => 'total_amount',
'title' => ts('Total Amount'),
'is_required' => TRUE,
- 'attributes' => array(
+ 'attributes' => [
'readonly' => TRUE,
'size' => 6,
- ),
- ),
- );
+ ],
+ ],
+ ];
return $paymentFields;
}
diff --git a/CRM/Financial/Form/SalesTaxTrait.php b/CRM/Financial/Form/SalesTaxTrait.php
new file mode 100644
index 000000000000..bf0b89818e02
--- /dev/null
+++ b/CRM/Financial/Form/SalesTaxTrait.php
@@ -0,0 +1,89 @@
+assign('taxTerm', $this->getSalesTaxTerm());
+ }
+
+ /**
+ * Assign sales tax rates to the template.
+ */
+ public function assignSalesTaxRates() {
+ $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
+ }
+
+ /**
+ * Return the string to be assigned to the template for sales tax - e.g GST, VAT.
+ *
+ * @return string
+ */
+ public function getSalesTaxTerm() {
+ $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
+ $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
+ if (!$invoicing) {
+ return '';
+ }
+ return CRM_Utils_Array::value('tax_term', $invoiceSettings);
+ }
+
+ /**
+ * Assign information to the template required for sales tax purposes.
+ */
+ public function assignSalesTaxMetadataToTemplate() {
+ $this->assignSalesTaxRates();
+ $this->assignSalesTaxTermToTemplate();
+ }
+
+ /**
+ * Get sales tax rates.
+ *
+ * @return array
+ */
+ public function getTaxRatesForFinancialTypes() {
+ return CRM_Core_PseudoConstant::getTaxRates();
+ }
+
+ /**
+ * @param int $financialTypeID
+ *
+ * @return string
+ */
+ public function getTaxRateForFinancialType($financialTypeID) {
+ return CRM_Utils_Array::value($financialTypeID, $this->getTaxRatesForFinancialTypes());
+ }
+
+}
diff --git a/CRM/Financial/Form/Search.php b/CRM/Financial/Form/Search.php
index 742c886d3b0c..30de0e886610 100644
--- a/CRM/Financial/Form/Search.php
+++ b/CRM/Financial/Form/Search.php
@@ -1,9 +1,9 @@
_batchStatus) {
@@ -63,17 +63,17 @@ public function buildQuickForm() {
$attributes['total']['class'] = $attributes['item_count']['class'] = 'number';
$this->add('text', 'title', ts('Batch Name'), $attributes['title']);
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
+ $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
$this->add(
'select',
'status_id',
ts('Batch Status'),
- array(
+ [
'' => ts('- any -'),
array_search('Open', $batchStatus) => ts('Open'),
array_search('Closed', $batchStatus) => ts('Closed'),
array_search('Exported', $batchStatus) => ts('Exported'),
- ),
+ ],
FALSE
);
@@ -81,7 +81,7 @@ public function buildQuickForm() {
'select',
'payment_instrument_id',
ts('Payment Method'),
- array('' => ts('- any -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ ['' => ts('- any -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
FALSE
);
@@ -90,14 +90,14 @@ public function buildQuickForm() {
$this->add('text', 'item_count', ts('Number of Items'), $attributes['item_count']);
$this->add('text', 'sort_name', ts('Created By'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name'));
- $this->assign('elements', array('status_id', 'title', 'sort_name', 'payment_instrument_id', 'item_count', 'total'));
- $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
- $batchAction = array(
+ $this->assign('elements', ['status_id', 'title', 'sort_name', 'payment_instrument_id', 'item_count', 'total']);
+ $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
+ $batchAction = [
'reopen' => ts('Re-open'),
'close' => ts('Close'),
'export' => ts('Export'),
'delete' => ts('Delete'),
- );
+ ];
foreach ($batchAction as $action => $ignore) {
if (!CRM_Batch_BAO_Batch::checkBatchPermission($action)) {
@@ -107,28 +107,28 @@ public function buildQuickForm() {
$this->add('select',
'batch_update',
ts('Task'),
- array('' => ts('- actions -')) + $batchAction);
+ ['' => ts('- actions -')] + $batchAction);
$this->add('submit', 'submit', ts('Go'),
- array(
+ [
'class' => 'crm-form-submit',
'id' => 'Go',
- ));
+ ]);
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- )
+ ],
+ ]
);
parent::buildQuickForm();
}
public function postProcess() {
- $batchIds = array();
+ $batchIds = [];
foreach ($_POST as $key => $value) {
if (substr($key, 0, 6) == "check_") {
$batch = explode("_", $key);
diff --git a/CRM/Financial/Page/AJAX.php b/CRM/Financial/Page/AJAX.php
index 0a5b4ae6e813..27b4b347ca28 100644
--- a/CRM/Financial/Page/AJAX.php
+++ b/CRM/Financial/Page/AJAX.php
@@ -1,9 +1,9 @@
ts('- select -'),
'value' => 'select',
- ),
- );
+ ],
+ ];
if (!empty($result)) {
foreach ($result as $id => $name) {
- $selectedArray = array();
+ $selectedArray = [];
if ($id == $defaultId) {
$selectedArray['selected'] = 'Selected';
}
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
- ) + $selectedArray;
+ ] + $selectedArray;
}
}
CRM_Utils_JSON::output($elements);
@@ -100,36 +100,36 @@ public static function jqFinancialRelation($config) {
$params['orderColumn'] = 'label';
$result = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount', 'account_relationship', $params);
- $elements = array(
- array(
+ $elements = [
+ [
'name' => ts('- Select Financial Account Relationship -'),
'value' => 'select',
- ),
- );
+ ],
+ ];
$countResult = count($financialAccountType[$financialAccountTypeId]);
if (!empty($result)) {
foreach ($result as $id => $name) {
if (in_array($id, $financialAccountType[$financialAccountTypeId]) && $_GET['_value'] != 'select') {
if ($countResult != 1) {
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
- );
+ ];
}
else {
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
'selected' => 'Selected',
- );
+ ];
}
}
elseif ($_GET['_value'] == 'select') {
- $elements[] = array(
+ $elements[] = [
'name' => $name,
'value' => $id,
- );
+ ];
}
}
}
@@ -164,17 +164,17 @@ public static function assignRemove() {
}
$entityID = CRM_Utils_Request::retrieve('entityID', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'POST');
- $methods = array(
+ $methods = [
'assign' => 'create',
'remove' => 'del',
'reopen' => 'create',
'close' => 'create',
'delete' => 'deleteBatch',
- );
+ ];
if ($op == 'close') {
$totals = CRM_Batch_BAO_Batch::batchTotals($records);
}
- $response = array('status' => 'record-updated-fail');
+ $response = ['status' => 'record-updated-fail'];
// first munge and clean the recordBAO and get rid of any non alpha numeric characters
$recordBAO = CRM_Utils_String::munge($recordBAO);
$recordClass = explode('_', $recordBAO);
@@ -182,7 +182,7 @@ public static function assignRemove() {
// at least 3 levels deep
if ($recordClass[0] == 'CRM' && count($recordClass) >= 3) {
foreach ($records as $recordID) {
- $params = array();
+ $params = [];
switch ($op) {
case 'assign':
case 'remove':
@@ -190,14 +190,14 @@ public static function assignRemove() {
$batchPID = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $entityID, 'payment_instrument_id');
$paymentInstrument = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchPID);
if ($op == 'remove' || ($recordPID == $batchPID && $op == 'assign') || !isset($batchPID)) {
- $params = array(
+ $params = [
'entity_id' => $recordID,
'entity_table' => 'civicrm_financial_trxn',
'batch_id' => $entityID,
- );
+ ];
}
else {
- $response = array('status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", array(1 => $paymentInstrument)));
+ $response = ['status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", [1 => $paymentInstrument])];
}
break;
@@ -206,7 +206,7 @@ public static function assignRemove() {
$params = $totals[$recordID];
case 'reopen':
$status = $op == 'close' ? 'Closed' : 'Reopened';
- $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name'));
+ $batchStatus = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name']);
$params['status_id'] = CRM_Utils_Array::key($status, $batchStatus);
$session = CRM_Core_Session::singleton();
$params['modified_date'] = date('YmdHis');
@@ -230,10 +230,10 @@ public static function assignRemove() {
if ($batchStatus[$updated->status_id] == "Reopened") {
$redirectStatus = array_search("Open", $batchStatus);
}
- $response = array(
+ $response = [
'status' => 'record-updated-success',
'status_id' => $redirectStatus,
- );
+ ];
}
}
}
@@ -248,7 +248,7 @@ public static function assignRemove() {
* @return string|wtf??
*/
public static function getFinancialTransactionsList() {
- $sortMapper = array(
+ $sortMapper = [
0 => '',
1 => '',
2 => 'sort_name',
@@ -259,7 +259,7 @@ public static function getFinancialTransactionsList() {
7 => 'payment_method',
8 => 'status',
9 => 'name',
- );
+ ];
$sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
$return = isset($_REQUEST['return']) ? CRM_Utils_Type::escape($_REQUEST['return'], 'Boolean') : FALSE;
@@ -267,7 +267,7 @@ public static function getFinancialTransactionsList() {
$rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
$sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
$sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
- $context = isset($_REQUEST['context']) ? CRM_Utils_Type::escape($_REQUEST['context'], 'String') : NULL;
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
$entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL;
$notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL;
$statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL;
@@ -278,7 +278,7 @@ public static function getFinancialTransactionsList() {
$params['sortBy'] = $sort . ' ' . $sortOrder;
}
- $returnvalues = array(
+ $returnvalues = [
'civicrm_financial_trxn.payment_instrument_id as payment_method',
'civicrm_contribution.contact_id as contact_id',
'civicrm_contribution.id as contributionID',
@@ -293,9 +293,11 @@ public static function getFinancialTransactionsList() {
'civicrm_financial_trxn.currency as currency',
'civicrm_financial_trxn.status_id as status',
'civicrm_financial_trxn.check_number as check_number',
- );
+ 'civicrm_financial_trxn.card_type_id',
+ 'civicrm_financial_trxn.pan_truncation',
+ ];
- $columnHeader = array(
+ $columnHeader = [
'contact_type' => '',
'sort_name' => ts('Contact Name'),
'amount' => ts('Amount'),
@@ -305,7 +307,7 @@ public static function getFinancialTransactionsList() {
'payment_method' => ts('Payment Method'),
'status' => ts('Status'),
'name' => ts('Type'),
- );
+ ];
if ($sort && $sortOrder) {
$params['sortBy'] = $sort . ' ' . $sortOrder;
@@ -347,13 +349,13 @@ public static function getFinancialTransactionsList() {
$params['total'] = count($assignedTransactionsCount);
}
}
- $financialitems = array();
+ $financialitems = [];
if ($statusID) {
- $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', array('labelColumn' => 'name', 'condition' => " v.value={$statusID}"));
+ $batchStatuses = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'status_id', ['labelColumn' => 'name', 'condition' => " v.value={$statusID}"]);
$batchStatus = $batchStatuses[$statusID];
}
while ($financialItem->fetch()) {
- $row[$financialItem->id] = array();
+ $row[$financialItem->id] = [];
foreach ($columnHeader as $columnKey => $columnValue) {
if ($financialItem->contact_sub_type && $columnKey == 'contact_type') {
$row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type;
@@ -384,18 +386,18 @@ public static function getFinancialTransactionsList() {
$row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $financialItem->$columnKey);
}
}
- if (isset($batchStatus) && in_array($batchStatus, array('Open', 'Reopened'))) {
+ if (isset($batchStatus) && in_array($batchStatus, ['Open', 'Reopened'])) {
if (isset($notPresent)) {
$js = "enableActions('x')";
$row[$financialItem->id]['check'] = "";
$row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
CRM_Financial_Form_BatchTransaction::links(),
NULL,
- array(
+ [
'id' => $financialItem->id,
'contid' => $financialItem->contributionID,
'cid' => $financialItem->contact_id,
- ),
+ ],
ts('more'),
FALSE,
'financialItem.batch.row',
@@ -409,11 +411,11 @@ public static function getFinancialTransactionsList() {
$row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
CRM_Financial_Page_BatchTransaction::links(),
NULL,
- array(
+ [
'id' => $financialItem->id,
'contid' => $financialItem->contributionID,
'cid' => $financialItem->contact_id,
- ),
+ ],
ts('more'),
FALSE,
'financialItem.batch.row',
@@ -430,11 +432,11 @@ public static function getFinancialTransactionsList() {
$row[$financialItem->id]['action'] = CRM_Core_Action::formLink(
$links,
NULL,
- array(
+ [
'id' => $financialItem->id,
'contid' => $financialItem->contributionID,
'cid' => $financialItem->contact_id,
- ),
+ ],
ts('more'),
FALSE,
'financialItem.batch.row',
@@ -449,7 +451,7 @@ public static function getFinancialTransactionsList() {
}
$iFilteredTotal = $iTotal = $params['total'];
- $selectorElements = array(
+ $selectorElements = [
'check',
'contact_type',
'sort_name',
@@ -461,7 +463,7 @@ public static function getFinancialTransactionsList() {
'status',
'name',
'action',
- );
+ ];
if ($return) {
return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
@@ -487,11 +489,11 @@ public static function bulkAssignRemove() {
foreach ($cIDs as $key => $value) {
$recordPID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $value, 'payment_instrument_id');
if ($action == 'Remove' || ($recordPID == $batchPID && $action == 'Assign') || !isset($batchPID)) {
- $params = array(
+ $params = [
'entity_id' => $value,
'entity_table' => 'civicrm_financial_trxn',
'batch_id' => $entityID,
- );
+ ];
if ($action == 'Assign') {
$updated = CRM_Batch_BAO_EntityBatch::create($params);
}
@@ -501,17 +503,17 @@ public static function bulkAssignRemove() {
}
}
if ($updated) {
- $status = array('status' => 'record-updated-success');
+ $status = ['status' => 'record-updated-success'];
}
else {
- $status = array('status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", array(1 => $paymentInstrument)));
+ $status = ['status' => ts("This batch is configured to include only transactions using %1 payment method. If you want to include other transactions, please edit the batch first and modify the Payment Method.", [1 => $paymentInstrument])];
}
CRM_Utils_JSON::output($status);
}
public static function getBatchSummary() {
$batchID = CRM_Utils_Type::escape($_REQUEST['batchID'], 'String');
- $params = array('id' => $batchID);
+ $params = ['id' => $batchID];
$batchSummary = self::makeBatchSummary($batchID, $params);
@@ -528,8 +530,8 @@ public static function getBatchSummary() {
*/
public static function makeBatchSummary($batchID, $params) {
$batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value);
- $batchTotals = CRM_Batch_BAO_Batch::batchTotals(array($batchID));
- $batchSummary = array(
+ $batchTotals = CRM_Batch_BAO_Batch::batchTotals([$batchID]);
+ $batchSummary = [
'created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id),
'status' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'status_id', $batchInfo->status_id),
'description' => $batchInfo->description,
@@ -539,7 +541,7 @@ public static function makeBatchSummary($batchID, $params) {
'total' => CRM_Utils_Money::format($batchInfo->total),
'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']),
'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date),
- );
+ ];
return $batchSummary;
}
diff --git a/CRM/Financial/Page/Batch.php b/CRM/Financial/Page/Batch.php
index 58126d73d6fb..36340646abc5 100644
--- a/CRM/Financial/Page/Batch.php
+++ b/CRM/Financial/Page/Batch.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ 'view' => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&id=%%contid%%&cid=%%cid%%&action=view&context=contribution&selectedChild=contribute',
'title' => ts('View Contribution'),
- ),
- 'remove' => array(
+ ],
+ 'remove' => [
'name' => ts('Remove'),
'title' => ts('Remove Transaction'),
'extra' => 'onclick = "assignRemove( %%id%%,\'' . 'remove' . '\' );"',
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -91,7 +91,8 @@ public function &links() {
*/
public function run() {
// get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
+ // default to 'browse'
+ $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
// assign vars to templates
$this->assign('action', $action);
@@ -102,13 +103,13 @@ public function run() {
$statusID = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', self::$_entityID, 'status_id');
}
$breadCrumb
- = array(
- array(
+ = [
+ [
'title' => ts('Accounting Batches'),
'url' => CRM_Utils_System::url('civicrm/financial/financialbatches',
"reset=1&batchStatus=$statusID"),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
$this->edit($action, self::$_entityID);
diff --git a/CRM/Financial/Page/FinancialAccount.php b/CRM/Financial/Page/FinancialAccount.php
index 0d4718b6e288..74c38c429c95 100644
--- a/CRM/Financial/Page/FinancialAccount.php
+++ b/CRM/Financial/Page/FinancialAccount.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/financial/financialAccount',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Financial Type'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Financial Type'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Financial Type'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/financial/financialAccount',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Financial Type'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -95,14 +95,14 @@ public function &links() {
*/
public function browse() {
// get all custom groups sorted by weight
- $contributionType = array();
+ $contributionType = [];
$dao = new CRM_Financial_DAO_FinancialAccount();
$dao->orderBy('financial_account_type_id, name');
$dao->find();
$financialAccountType = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialAccount', 'financial_account_type_id');
while ($dao->fetch()) {
- $contributionType[$dao->id] = array();
+ $contributionType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $contributionType[$dao->id]);
$contributionType[$dao->id]['financial_account_type_id'] = $financialAccountType[$dao->financial_account_type_id];
// form all action links
@@ -122,7 +122,7 @@ public function browse() {
}
$contributionType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'financialAccount.manage.action',
diff --git a/CRM/Financial/Page/FinancialBatch.php b/CRM/Financial/Page/FinancialBatch.php
index 6ce5833a5fc2..0c25a0a72b99 100644
--- a/CRM/Financial/Page/FinancialBatch.php
+++ b/CRM/Financial/Page/FinancialBatch.php
@@ -1,9 +1,9 @@
set("context", $context);
$id = $this->getIdAndAction();
@@ -92,7 +92,6 @@ public function run() {
return CRM_Core_Page::run();
}
-
/**
* Get name of edit form.
*
diff --git a/CRM/Financial/Page/FinancialType.php b/CRM/Financial/Page/FinancialType.php
index 53d31b84b674..6bb3b325ff79 100644
--- a/CRM/Financial/Page/FinancialType.php
+++ b/CRM/Financial/Page/FinancialType.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::BROWSE => [
'name' => ts('Accounts'),
'url' => 'civicrm/admin/financial/financialType/accounts',
'qs' => 'reset=1&action=browse&aid=%%id%%',
'title' => ts('Accounts'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/financial/financialType',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Financial Type'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Financial Type'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Financial Type'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/financial/financialType',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Financial Type'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -107,17 +107,17 @@ public function browse() {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
// get all financial types sorted by weight
- $financialType = array();
+ $financialType = [];
$dao = new CRM_Financial_DAO_FinancialType();
$dao->orderBy('name');
$dao->find();
while ($dao->fetch()) {
- $financialType[$dao->id] = array();
+ $financialType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
- $defaults = $financialAccountId = array();
+ $defaults = $financialAccountId = [];
$financialAccounts = CRM_Contribute_PseudoConstant::financialAccount();
- $financialAccountIds = array();
+ $financialAccountIds = [];
$params['entity_id'] = $dao->id;
$params['entity_table'] = 'civicrm_financial_type';
@@ -153,7 +153,7 @@ public function browse() {
}
$financialType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'financialType.manage.action',
diff --git a/CRM/Financial/Page/FinancialTypeAccount.php b/CRM/Financial/Page/FinancialTypeAccount.php
index 5f20b5f2b22b..c4f019b6645c 100644
--- a/CRM/Financial/Page/FinancialTypeAccount.php
+++ b/CRM/Financial/Page/FinancialTypeAccount.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/financial/financialType/accounts',
'qs' => 'action=update&id=%%id%%&aid=%%aid%%&reset=1',
'title' => ts('Edit Financial Type Account'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/financial/financialType/accounts',
'qs' => 'action=delete&id=%%id%%&aid=%%aid%%',
'title' => ts('Delete Financial Type Account'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -94,7 +94,8 @@ public function &links() {
*/
public function run() {
// get the requested action
- $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); // default to 'browse'
+ // default to 'browse'
+ $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
// assign vars to templates
$this->assign('action', $action);
@@ -118,8 +119,8 @@ public function run() {
*/
public function browse() {
// get all Financial Type Account data sorted by weight
- $financialType = array();
- $params = array();
+ $financialType = [];
+ $params = [];
$dao = new CRM_Financial_DAO_EntityFinancialAccount();
$params['entity_id'] = $this->_aid;
$params['entity_table'] = 'civicrm_financial_type';
@@ -132,11 +133,11 @@ public function browse() {
$dao->copyValues($params);
$dao->find();
while ($dao->fetch()) {
- $financialType[$dao->id] = array();
+ $financialType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $financialType[$dao->id]);
- $params = array('id' => $dao->financial_account_id);
- $defaults = array();
+ $params = ['id' => $dao->financial_account_id];
+ $defaults = [];
$financialAccount = CRM_Financial_BAO_FinancialAccount::retrieve($params, $defaults);
if (!empty($financialAccount)) {
$financialType[$dao->id]['financial_account'] = $financialAccount->name;
@@ -165,10 +166,10 @@ public function browse() {
unset($links[CRM_Core_Action::DELETE]);
}
$financialType[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action,
- array(
+ [
'id' => $dao->id,
'aid' => $dao->entity_id,
- ),
+ ],
ts('more'),
FALSE,
'financialTypeAccount.manage.action',
diff --git a/CRM/Friend/BAO/Friend.php b/CRM/Friend/BAO/Friend.php
index b79126f6ace9..b817cae90911 100644
--- a/CRM/Friend/BAO/Friend.php
+++ b/CRM/Friend/BAO/Friend.php
@@ -1,9 +1,9 @@
copyValues($params);
-
$friend->find(TRUE);
-
CRM_Core_DAO::storeValues($friend, $values);
-
return $values;
}
@@ -88,38 +91,41 @@ public static function retrieve(&$params, &$values) {
* Takes an associative array and creates a friend object.
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * (reference) an assoc array of name/value pairs.
*
- * @return void
+ * @throws \CRM_Core_Exception
*/
public static function create(&$params) {
$transaction = new CRM_Core_Transaction();
- $mailParams = array();
- //create contact corresponding to each friend
+ $mailParams = [];
+ $contactParams = [];
+
+ // create contact corresponding to each friend
foreach ($params['friend'] as $key => $details) {
if ($details["first_name"]) {
- $contactParams[$key] = array(
+ $contactParams[$key] = [
'first_name' => $details["first_name"],
'last_name' => $details["last_name"],
'contact_source' => ts('Tell a Friend') . ": {$params['title']}",
'email-Primary' => $details["email"],
- );
+ ];
$displayName = $details["first_name"] . " " . $details["last_name"];
$mailParams['email'][$displayName] = $details["email"];
}
}
- $frndParams = array();
- $frndParams['entity_id'] = $params['entity_id'];
- $frndParams['entity_table'] = $params['entity_table'];
- self::getValues($frndParams);
+ $friendParams = [
+ 'entity_id' => $params['entity_id'],
+ 'entity_table' => $params['entity_table'],
+ ];
+ self::getValues($friendParams);
$activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'Tell a Friend', 'value', 'name');
- //create activity
- $activityParams = array(
+ // create activity
+ $activityParams = [
'source_contact_id' => $params['source_contact_id'],
'source_record_id' => NULL,
'activity_type_id' => $activityTypeId,
@@ -127,33 +133,32 @@ public static function create(&$params) {
'activity_date_time' => date("YmdHis"),
'subject' => ts('Tell a Friend') . ": {$params['title']}",
'details' => $params['suggested_message'],
- 'status_id' => 2,
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
'is_test' => $params['is_test'],
'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
- );
+ ];
- //activity creation
+ // activity creation
$activity = CRM_Activity_BAO_Activity::create($activityParams);
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
- //friend contacts creation
+ // friend contacts creation
foreach ($contactParams as $key => $value) {
-
- //create contact only if it does not exits in db
+ // create contact only if it does not exits in db
$value['email'] = $value['email-Primary'];
- $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($value, 'Individual', 'Supervised', array(), FALSE);
+ $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($value, 'Individual', 'Supervised', [], FALSE);
if (!$contactID) {
$contactID = self::add($value);
}
// attempt to save activity targets
- $targetParams = array(
+ $targetParams = [
'activity_id' => $activity->id,
'contact_id' => $contactID,
'record_type_id' => $targetID,
- );
+ ];
// See if it already exists
$activityContact = new CRM_Activity_DAO_ActivityContact();
@@ -167,28 +172,27 @@ public static function create(&$params) {
$transaction->commit();
- //process sending of mails
+ // Process sending of mails
$mailParams['title'] = CRM_Utils_Array::value('title', $params);
- $mailParams['general_link'] = CRM_Utils_Array::value('general_link', $frndParams);
+ $mailParams['general_link'] = CRM_Utils_Array::value('general_link', $friendParams);
$mailParams['message'] = CRM_Utils_Array::value('suggested_message', $params);
- // get domain
- $domainDetails = CRM_Core_BAO_Domain::getNameAndEmail();
- list($username, $mailParams['domain']) = explode('@', $domainDetails[1]);
+ // Default "from email address" is default domain address.
+ list($_, $mailParams['email_from']) = CRM_Core_BAO_Domain::getNameAndEmail();
+ list($username, $mailParams['domain']) = explode('@', $mailParams['email_from']);
- $default = array();
- $findProperties = array('id' => $params['entity_id']);
+ $default = [];
+ $findProperties = ['id' => $params['entity_id']];
if ($params['entity_table'] == 'civicrm_contribution_page') {
-
- $returnProperties = array('receipt_from_email', 'is_email_receipt');
+ $returnProperties = ['receipt_from_email', 'is_email_receipt'];
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage',
$findProperties,
$default,
$returnProperties
);
- //if is_email_receipt is set then take receipt_from_email
- //as from_email
+
+ // if is_email_receipt is set then take receipt_from_email as from_email
if (!empty($default['is_email_receipt']) && !empty($default['receipt_from_email'])) {
$mailParams['email_from'] = $default['receipt_from_email'];
}
@@ -197,18 +201,14 @@ public static function create(&$params) {
$mailParams['module'] = 'contribute';
}
elseif ($params['entity_table'] == 'civicrm_event') {
-
- $returnProperties = array('confirm_from_email', 'is_email_confirm');
+ $returnProperties = ['confirm_from_email', 'is_email_confirm'];
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event',
$findProperties,
$default,
$returnProperties
);
- $mailParams['email_from'] = $domainDetails['1'];
-
- //if is_email_confirm is set then take confirm_from_email
- //as from_email
+ // if is_email_confirm is set then take confirm_from_email as from_email
if (!empty($default['is_email_confirm']) && !empty($default['confirm_from_email'])) {
$mailParams['email_from'] = $default['confirm_from_email'];
}
@@ -217,34 +217,36 @@ public static function create(&$params) {
$mailParams['module'] = 'event';
}
elseif ($params['entity_table'] == 'civicrm_pcp') {
- $mailParams['email_from'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $params['source_contact_id'],
- 'email', 'contact_id'
- );
+ if (Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ $mailParams['email_from'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $params['source_contact_id'],
+ 'email', 'contact_id'
+ );
+ }
$urlPath = 'civicrm/pcp/info';
$mailParams['module'] = 'contribute';
}
$mailParams['page_url'] = CRM_Utils_System::url($urlPath, "reset=1&id={$params['entity_id']}", TRUE, NULL, FALSE, TRUE);
- //send mail
+ // Send the email
self::sendMail($params['source_contact_id'], $mailParams);
}
/**
* Build the form object.
*
- * @param CRM_Core_Form $form
+ * @param CRM_Friend_Form $form
* Form object.
*
* @return void
*/
public static function buildFriendForm($form) {
- $form->addElement('checkbox', 'tf_is_active', ts('Tell a Friend enabled?'), NULL, array('onclick' => "friendBlock(this)"));
+ $form->addElement('checkbox', 'tf_is_active', ts('Tell a Friend enabled?'), NULL, ['onclick' => "friendBlock(this)"]);
// name
$form->add('text', 'tf_title', ts('Title'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'title'), TRUE);
// intro-text and thank-you text
- $form->add('wysiwyg', 'intro', ts('Introduction'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'intro') + array('class' => 'collapsed'));
+ $form->add('wysiwyg', 'intro', ts('Introduction'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'intro') + ['class' => 'collapsed']);
$form->add('textarea', 'suggested_message', ts('Suggested Message'),
CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'suggested_message'), FALSE
@@ -254,7 +256,7 @@ public static function buildFriendForm($form) {
$form->add('text', 'tf_thankyou_title', ts('Thank-you Title'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'thankyou_title'), TRUE);
- $form->add('wysiwyg', 'tf_thankyou_text', ts('Thank-you Message'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'thankyou_text') + array('class' => 'collapsed'));
+ $form->add('wysiwyg', 'tf_thankyou_text', ts('Thank-you Message'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'thankyou_text') + ['class' => 'collapsed']);
if ($form->_friendId) {
// CRM-14200 the i18n dialogs need this for translation
@@ -263,12 +265,12 @@ public static function buildFriendForm($form) {
}
/**
- * The function sets the deafult values of the form.
+ * The function sets the default values of the form.
*
* @param array $defaults
* (reference) the default values.
*
- * @return booelan
+ * @return bool
* whether anything was found
*/
public static function getValues(&$defaults) {
@@ -283,7 +285,7 @@ public static function getValues(&$defaults) {
}
/**
- * Process that send tell a friend e-mails
+ * Process that sends tell a friend e-mails
*
* @param int $contactID
* @param array $values
@@ -297,33 +299,41 @@ public static function sendMail($contactID, &$values) {
$fromName = $email;
}
- // use contact email, CRM-4963
+ if (Civi::settings()->get('allow_mail_from_logged_in_contact')) {
+ // use contact email, CRM-4963
+ if (empty($values['email_from'])) {
+ $values['email_from'] = $email;
+ }
+ }
+
+ // If we have no "email_from" when we get to here, explicitly set it to the default domain email.
if (empty($values['email_from'])) {
- $values['email_from'] = $email;
+ list($domainFromName, $domainEmail) = CRM_Core_BAO_Domain::getNameAndEmail();
+ $values['email_from'] = $domainEmail;
+ $values['domain'] = $domainFromName;
}
+ $templateParams = [
+ 'groupName' => 'msg_tpl_workflow_friend',
+ 'valueName' => 'friend',
+ 'contactId' => $contactID,
+ 'tplParams' => [
+ $values['module'] => $values['module'],
+ 'senderContactName' => $fromName,
+ 'title' => $values['title'],
+ 'generalLink' => $values['general_link'],
+ 'pageURL' => $values['page_url'],
+ 'senderMessage' => $values['message'],
+ ],
+ 'from' => "$fromName (via {$values['domain']}) <{$values['email_from']}>",
+ 'replyTo' => $email,
+ ];
+
foreach ($values['email'] as $displayName => $emailTo) {
if ($emailTo) {
- // FIXME: factor the below out of the foreach loop
- CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
- 'groupName' => 'msg_tpl_workflow_friend',
- 'valueName' => 'friend',
- 'contactId' => $contactID,
- 'tplParams' => array(
- $values['module'] => $values['module'],
- 'senderContactName' => $fromName,
- 'title' => $values['title'],
- 'generalLink' => $values['general_link'],
- 'pageURL' => $values['page_url'],
- 'senderMessage' => $values['message'],
- ),
- 'from' => "$fromName (via {$values['domain']}) <{$values['email_from']}>",
- 'toName' => $displayName,
- 'toEmail' => $emailTo,
- 'replyTo' => $email,
- )
- );
+ $templateParams['toName'] = $displayName;
+ $templateParams['toEmail'] = $emailTo;
+ CRM_Core_BAO_MessageTemplate::sendTemplate($templateParams);
}
}
}
@@ -336,16 +346,14 @@ public static function sendMail($contactID, &$values) {
* pairs
*
* @param array $params
- * (reference ) an assoc array of name/value pairs.
+ * (reference) an assoc array of name/value pairs.
*
- * @return CRM_Friend_BAO_Friend
+ * @return CRM_Friend_DAO_Friend
*/
public static function addTellAFriend(&$params) {
$friendDAO = new CRM_Friend_DAO_Friend();
-
$friendDAO->copyValues($params);
$friendDAO->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
-
$friendDAO->save();
return $friendDAO;
diff --git a/CRM/Friend/DAO/Friend.php b/CRM/Friend/DAO/Friend.php
index 186a78673fec..2d568215f02d 100644
--- a/CRM/Friend/DAO/Friend.php
+++ b/CRM/Friend/DAO/Friend.php
@@ -1,310 +1,309 @@
__table = 'civicrm_tell_friend';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Friend ID') ,
- 'description' => 'Friend ID',
- 'required' => true,
+ 'title' => ts('Friend ID'),
+ 'description' => ts('Friend ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_tell_friend.id',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'Name of table where item being referenced is stored.',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('Name of table where item being referenced is stored.'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_tell_friend.entity_table',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity ID') ,
- 'description' => 'Foreign key to the referenced item.',
- 'required' => true,
+ 'title' => ts('Entity ID'),
+ 'description' => ts('Foreign key to the referenced item.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_tell_friend.entity_id',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- ) ,
- 'title' => array(
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Title') ,
+ 'title' => ts('Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_tell_friend.title',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'intro' => array(
+ ],
+ ],
+ 'intro' => [
'name' => 'intro',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Intro') ,
- 'description' => 'Introductory message to contributor or participant displayed on the Tell a Friend form.',
+ 'title' => ts('Intro'),
+ 'description' => ts('Introductory message to contributor or participant displayed on the Tell a Friend form.'),
+ 'where' => 'civicrm_tell_friend.intro',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'suggested_message' => array(
+ ],
+ ],
+ 'suggested_message' => [
'name' => 'suggested_message',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Suggested Message') ,
- 'description' => 'Suggested message to friends, provided as default on the Tell A Friend form.',
+ 'title' => ts('Suggested Message'),
+ 'description' => ts('Suggested message to friends, provided as default on the Tell A Friend form.'),
+ 'where' => 'civicrm_tell_friend.suggested_message',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'general_link' => array(
+ ],
+ ],
+ 'general_link' => [
'name' => 'general_link',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('General Link') ,
- 'description' => 'URL for general info about the organization - included in the email sent to friends.',
+ 'title' => ts('General Link'),
+ 'description' => ts('URL for general info about the organization - included in the email sent to friends.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_tell_friend.general_link',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'thankyou_title' => array(
+ ],
+ ],
+ 'thankyou_title' => [
'name' => 'thankyou_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Thank You Title') ,
- 'description' => 'Text for Tell a Friend thank you page header and HTML title.',
+ 'title' => ts('Thank You Title'),
+ 'description' => ts('Text for Tell a Friend thank you page header and HTML title.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_tell_friend.thankyou_title',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'thankyou_text' => array(
+ ],
+ ],
+ 'thankyou_text' => [
'name' => 'thankyou_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Thank You Text') ,
- 'description' => 'Thank you message displayed on success page.',
+ 'title' => ts('Thank You Text'),
+ 'description' => ts('Thank you message displayed on success page.'),
+ 'where' => 'civicrm_tell_friend.thankyou_text',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
+ 'title' => ts('Enabled?'),
+ 'where' => 'civicrm_tell_friend.is_active',
'table_name' => 'civicrm_tell_friend',
'entity' => 'Friend',
'bao' => 'CRM_Friend_BAO_Friend',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -312,10 +311,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'tell_friend', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'tell_friend', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -323,15 +323,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'tell_friend', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'tell_friend', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Friend/Form.php b/CRM/Friend/Form.php
index ecd589234ac8..70cd21086dc5 100644
--- a/CRM/Friend/Form.php
+++ b/CRM/Friend/Form.php
@@ -1,9 +1,9 @@
$this->_entityId);
+ ])) {
+ $values = [];
+ $params = ['id' => $this->_entityId];
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage',
- $params, $values, array('title', 'campaign_id', 'is_share')
+ $params, $values, ['title', 'campaign_id', 'is_share']
);
$this->_title = CRM_Utils_Array::value('title', $values);
$this->_campaignId = CRM_Utils_Array::value('campaign_id', $values);
@@ -88,6 +95,7 @@ public function preProcess() {
if ($pcomponent == 'event') {
$this->_entityTable = 'civicrm_event';
$isShare = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_entityId, 'is_share');
+ $this->_title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_entityId, 'title');
}
else {
$isShare = CRM_Utils_Array::value('is_share', $values);
@@ -98,10 +106,10 @@ public function preProcess() {
elseif ($pcomponent == 'pcp') {
$this->_pcpBlockId = CRM_Utils_Request::retrieve('blockId', 'Positive', $this, TRUE);
- $values = array();
- $params = array('id' => $this->_pcpBlockId);
+ $values = [];
+ $params = ['id' => $this->_pcpBlockId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock',
- $params, $values, array('is_tellfriend_enabled', 'tellfriend_limit')
+ $params, $values, ['is_tellfriend_enabled', 'tellfriend_limit']
);
if (empty($values['is_tellfriend_enabled'])) {
@@ -117,7 +125,7 @@ public function preProcess() {
FROM civicrm_pcp pcp
INNER JOIN civicrm_contribution_page contrib ON ( pcp.page_id = contrib.id AND pcp.page_type = "contribute" )
WHERE pcp.id = %1';
- $pcp = CRM_Core_DAO::executeQuery($sql, array(1 => array($this->_entityId, 'Positive')));
+ $pcp = CRM_Core_DAO::executeQuery($sql, [1 => [$this->_entityId, 'Positive']]);
while ($pcp->fetch()) {
$this->_title = $pcp->title;
$this->_campaignId = $pcp->campaign_id;
@@ -152,7 +160,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults['entity_id'] = $this->_entityId;
$defaults['entity_table'] = $this->_entityTable;
@@ -197,7 +205,7 @@ public function buildQuickForm() {
$email->freeze();
$this->add('wysiwyg', 'suggested_message', ts('Your Message'), CRM_Core_DAO::getAttribute('CRM_Friend_DAO_Friend', 'suggested_message'));
- $friend = array();
+ $friend = [];
$mailLimit = self::NUM_OPTION;
if ($this->_entityTable == 'civicrm_pcp') {
$mailLimit = $this->_mailLimit;
@@ -210,21 +218,20 @@ public function buildQuickForm() {
$this->addRule("friend[$i][email]", ts('The format of this email address is not valid.'), 'email');
}
- $this->addButtons(array(
- array(
- 'type' => 'submit',
- 'name' => ts('Send Your Message'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
- $this->addFormRule(array('CRM_Friend_Form', 'formRule'));
+ $this->addButtons([
+ [
+ 'type' => 'submit',
+ 'name' => ts('Send Your Message'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
+
+ $this->addFormRule(['CRM_Friend_Form', 'formRule']);
}
/**
@@ -237,7 +244,7 @@ public function buildQuickForm() {
*/
public static function formRule($fields) {
- $errors = array();
+ $errors = [];
$valid = FALSE;
foreach ($fields['friend'] as $key => $val) {
@@ -285,7 +292,7 @@ public function postProcess() {
CRM_Friend_BAO_Friend::create($formValues);
$this->assign('status', 'thankyou');
- $defaults = array();
+ $defaults = [];
$defaults['entity_id'] = $this->_entityId;
$defaults['entity_table'] = $this->_entityTable;
diff --git a/CRM/Friend/Form/Contribute.php b/CRM/Friend/Form/Contribute.php
index e59f94074f82..f4bb3971944b 100644
--- a/CRM/Friend/Form/Contribute.php
+++ b/CRM/Friend/Form/Contribute.php
@@ -1,9 +1,9 @@
_id)) {
$defaults['entity_table'] = 'civicrm_contribution_page';
diff --git a/CRM/Friend/Form/Event.php b/CRM/Friend/Form/Event.php
index 86f2a1d9a562..bf5b6cb51828 100644
--- a/CRM/Friend/Form/Event.php
+++ b/CRM/Friend/Form/Event.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'friend');
}
/**
@@ -57,7 +58,7 @@ public function preProcess() {
* @return void
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
$defaults['entity_table'] = 'civicrm_event';
diff --git a/CRM/Grant/BAO/Grant.php b/CRM/Grant/BAO/Grant.php
index 7a669d599e6b..4db6f2a3c23f 100644
--- a/CRM/Grant/BAO/Grant.php
+++ b/CRM/Grant/BAO/Grant.php
@@ -1,9 +1,9 @@
$name) {
- $stats[$id] = array(
+ $stats[$id] = [
'label' => $name,
'total' => 0,
- );
+ ];
}
while ($dao->fetch()) {
- $stats[$dao->status_id] = array(
+ $stats[$dao->status_id] = [
'label' => $status[$dao->status_id],
'total' => $dao->status_total,
- );
+ ];
$summary['total_grants'] += $dao->status_total;
}
@@ -96,10 +90,10 @@ public static function getGrantSummary($admin = FALSE) {
*/
public static function getGrantStatusOptGroup() {
- $params = array();
+ $params = [];
$params['name'] = CRM_Grant_BAO_Grant::$statusGroupName;
- $defaults = array();
+ $defaults = [];
$og = CRM_Core_BAO_OptionGroup::retrieve($params, $defaults);
if (!$og) {
@@ -150,23 +144,23 @@ public static function add(&$params, &$ids) {
}
// first clean up all the money fields
- $moneyFields = array(
+ $moneyFields = [
'amount_total',
'amount_granted',
'amount_requested',
- );
+ ];
foreach ($moneyFields as $field) {
if (isset($params[$field])) {
$params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
}
}
// convert dates to mysql format
- $dates = array(
+ $dates = [
'application_received_date',
'decision_date',
'money_transfer_date',
'grant_due_date',
- );
+ ];
foreach ($dates as $d) {
if (isset($params[$d])) {
@@ -197,7 +191,7 @@ public static function add(&$params, &$ids) {
}
$title = CRM_Contact_BAO_Contact::displayName($grant->contact_id) . ' - ' . ts('Grant') . ': ' . $grantTypes[$grant->grant_type_id];
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviGrant', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/grant',
"action=update&reset=1&id={$grant->id}&cid={$grant->contact_id}&context=home"
@@ -256,23 +250,23 @@ public static function create(&$params, &$ids) {
$id = CRM_Utils_Array::value('contact_id', $params);
}
if (!empty($params['note']) || CRM_Utils_Array::value('id', CRM_Utils_Array::value('note', $ids))) {
- $noteParams = array(
+ $noteParams = [
'entity_table' => 'civicrm_grant',
'note' => $params['note'] = $params['note'] ? $params['note'] : "null",
'entity_id' => $grant->id,
'contact_id' => $id,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Note::add($noteParams, (array) CRM_Utils_Array::value('note', $ids));
}
// Log the information on successful add/edit of Grant
- $logParams = array(
+ $logParams = [
'entity_table' => 'civicrm_grant',
'entity_id' => $grant->id,
'modified_id' => $id,
'modified_date' => date('Ymd'),
- );
+ ];
CRM_Core_BAO_Log::add($logParams);
@@ -325,10 +319,10 @@ public static function del($id) {
$grant->find();
// delete the recently created Grant
- $grantRecent = array(
+ $grantRecent = [
'id' => $id,
'type' => 'Grant',
- );
+ ];
CRM_Utils_Recent::del($grantRecent);
if ($grant->fetch()) {
@@ -346,54 +340,19 @@ public static function del($id) {
* array of exportable Fields
*/
public static function &exportableFields() {
- if (!self::$_exportableFields) {
- if (!self::$_exportableFields) {
- self::$_exportableFields = array();
- }
-
- $grantFields = array(
- 'grant_status' => array(
- 'title' => ts('Grant Status'),
- 'name' => 'grant_status',
- 'data_type' => CRM_Utils_Type::T_STRING,
- ),
- 'grant_type' => array(
- 'title' => ts('Grant Type'),
- 'name' => 'grant_type',
- 'data_type' => CRM_Utils_Type::T_STRING,
- ),
- 'grant_money_transfer_date' => array(
- 'title' => ts('Grant Money Transfer Date'),
- 'name' => 'grant_money_transfer_date',
- 'data_type' => CRM_Utils_Type::T_DATE,
- ),
- 'grant_amount_requested' => array(
- 'title' => ts('Grant Amount Requested'),
- 'name' => 'grant_amount_requested',
- 'data_type' => CRM_Utils_Type::T_FLOAT,
- ),
- 'grant_application_received_date' => array(
- 'title' => ts('Grant Application Received Date'),
- 'name' => 'grant_application_received_date',
- 'data_type' => CRM_Utils_Type::T_DATE,
- ),
- );
-
- $fields = CRM_Grant_DAO_Grant::export();
- $grantNote = array(
- 'grant_note' => array(
- 'title' => ts('Grant Note'),
- 'name' => 'grant_note',
- 'data_type' => CRM_Utils_Type::T_TEXT,
- ),
- );
- $fields = array_merge($fields, $grantFields, $grantNote,
- CRM_Core_BAO_CustomField::getFieldsForImport('Grant')
- );
- self::$_exportableFields = $fields;
- }
+ $fields = CRM_Grant_DAO_Grant::export();
+ $grantNote = [
+ 'grant_note' => [
+ 'title' => ts('Grant Note'),
+ 'name' => 'grant_note',
+ 'data_type' => CRM_Utils_Type::T_TEXT,
+ ],
+ ];
+ $fields = array_merge($fields, $grantNote,
+ CRM_Core_BAO_CustomField::getFieldsForImport('Grant')
+ );
- return self::$_exportableFields;
+ return $fields;
}
/**
diff --git a/CRM/Grant/BAO/Query.php b/CRM/Grant/BAO/Query.php
index d10acbe418d6..b76fcfd5118e 100644
--- a/CRM/Grant/BAO/Query.php
+++ b/CRM/Grant/BAO/Query.php
@@ -1,9 +1,9 @@
_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;
@@ -159,7 +158,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'grant_due_date_high':
$query->dateQueryBuilder($values, 'civicrm_grant',
'grant_due_date',
- 'grant_due_date', 'Grant Due Date'
+ 'grant_due_date', ts('Grant Due Date')
);
return;
@@ -173,7 +172,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'grant_decision_date_high':
$query->dateQueryBuilder($values, 'civicrm_grant',
'grant_decision_date',
- 'decision_date', 'Grant Decision Date'
+ 'decision_date', ts('Grant Decision Date')
);
return;
@@ -190,17 +189,17 @@ public static function whereClauseSingle(&$values, &$query) {
if (strstr($name, 'type')) {
$name = 'grant_type_id';
- $label = 'Grant Type(s)';
+ $label = ts('Grant Type(s)');
}
else {
$name = 'status_id';
- $label = 'Grant Status(s)';
+ $label = ts('Grant Status(s)');
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_grant.$name", $op, $value, "Integer");
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;
@@ -208,15 +207,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;
@@ -279,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,
@@ -291,61 +290,68 @@ 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.
+ */
+ 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->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->addElement('checkbox', 'grant_due_date_notset', ts('Date is not set'), NULL);
+ $form->addElement('checkbox', 'grant_decision_date_notset', ts('Date is not set'), NULL);
- $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', '', 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_money_transfer_date_notset', '', 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', '', 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', '', 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);
}
diff --git a/CRM/Grant/Controller/Search.php b/CRM/Grant/Controller/Search.php
index c04784ab45b0..847ac448a7d3 100644
--- a/CRM/Grant/Controller/Search.php
+++ b/CRM/Grant/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_grant';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'grant_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'grant_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Grant ID') ,
- 'description' => 'Unique Grant id',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Grant ID'),
+ 'description' => ts('Unique Grant id'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_grant.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- ) ,
- 'grant_contact_id' => array(
+ ],
+ 'grant_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'Contact ID of contact record given grant belongs to.',
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('Contact ID of contact record given grant belongs to.'),
+ 'required' => TRUE,
'where' => 'civicrm_grant.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'application_received_date' => array(
+ ],
+ ],
+ 'grant_application_received_date' => [
'name' => 'application_received_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Application received date') ,
- 'description' => 'Date on which grant application was received by donor.',
- 'export' => true,
+ 'title' => ts('Application received date'),
+ 'description' => ts('Date on which grant application was received by donor.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.application_received_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- ) ,
- 'decision_date' => array(
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_decision_date' => [
'name' => 'decision_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Decision date') ,
- 'description' => 'Date on which grant decision was made.',
- 'import' => true,
+ 'title' => ts('Decision date'),
+ 'description' => ts('Date on which grant decision was made.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.decision_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'grant_money_transfer_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_money_transfer_date' => [
'name' => 'money_transfer_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Grant Money transfer date') ,
- 'description' => 'Date on which grant money transfer was made.',
- 'import' => true,
+ 'title' => ts('Grant Money transfer date'),
+ 'description' => ts('Date on which grant money transfer was made.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.money_transfer_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'grant_due_date' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_due_date' => [
'name' => 'grant_due_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Grant Due Date') ,
- 'description' => 'Date on which grant report is due.',
+ 'title' => ts('Grant Report Due Date'),
+ 'description' => ts('Date on which grant report is due.'),
+ 'import' => TRUE,
+ 'where' => 'civicrm_grant.grant_due_date',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'grant_report_received' => array(
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'grant_report_received' => [
'name' => 'grant_report_received',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Grant report received') ,
- 'description' => 'Yes/No field stating whether grant report was received by donor.',
- 'import' => true,
+ 'title' => ts('Grant report received'),
+ 'description' => ts('Yes/No field stating whether grant report was received by donor.'),
+ 'import' => TRUE,
'where' => 'civicrm_grant.grant_report_received',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'grant_type_id' => array(
+ ],
+ ],
+ 'grant_type_id' => [
'name' => 'grant_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Grant Type') ,
- 'description' => 'Type of grant. Implicit FK to civicrm_option_value in grant_type option_group.',
- 'required' => true,
- 'export' => true,
+ 'title' => ts('Grant Type'),
+ 'description' => ts('Type of grant. Implicit FK to civicrm_option_value in grant_type option_group.'),
+ 'required' => TRUE,
'where' => 'civicrm_grant.grant_type_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'grant_type',
'optionEditPath' => 'civicrm/admin/options/grant_type',
- )
- ) ,
- 'amount_total' => array(
+ ]
+ ],
+ 'amount_total' => [
'name' => 'amount_total',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Total Amount') ,
- 'description' => 'Requested grant amount, in default currency.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Total Amount'),
+ 'description' => ts('Requested grant amount, in default currency.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_grant.amount_total',
- 'headerPattern' => '',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'amount_requested' => array(
+ ],
+ ],
+ 'amount_requested' => [
'name' => 'amount_requested',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount Requested') ,
- 'description' => 'Requested grant amount, in original currency (optional).',
- 'precision' => array(
+ 'title' => ts('Amount Requested'),
+ 'description' => ts('Requested grant amount, in original currency (optional).'),
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_grant.amount_requested',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'amount_granted' => array(
+ ],
+ ],
+ 'amount_granted' => [
'name' => 'amount_granted',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Amount granted') ,
- 'description' => 'Granted amount, in default currency.',
- 'precision' => array(
+ 'title' => ts('Amount granted'),
+ 'description' => ts('Granted amount, in default currency.'),
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_grant.amount_granted',
- 'headerPattern' => '',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Grant Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
- 'required' => true,
+ 'title' => ts('Grant Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
+ 'required' => TRUE,
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_grant.currency',
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'rationale' => array(
+ ]
+ ],
+ 'rationale' => [
'name' => 'rationale',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Grant Rationale') ,
- 'description' => 'Grant rationale.',
+ 'title' => ts('Grant Rationale'),
+ 'description' => ts('Grant rationale.'),
'rows' => 4,
'cols' => 60,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_grant.rationale',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'grant_status_id' => array(
+ ],
+ ],
+ 'grant_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Grant Status') ,
- 'description' => 'Id of Grant status.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Grant Status'),
+ 'description' => ts('Id of Grant status.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_grant.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'grant_status',
'optionEditPath' => 'civicrm/admin/options/grant_status',
- )
- ) ,
- 'financial_type_id' => array(
+ ]
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type.'),
+ 'where' => 'civicrm_grant.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_grant',
'entity' => 'Grant',
'bao' => 'CRM_Grant_BAO_Grant',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -492,10 +486,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'grant', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'grant', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -503,32 +498,38 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'grant', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'grant', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_grant_type_id' => array(
+ $indices = [
+ 'index_grant_type_id' => [
'name' => 'index_grant_type_id',
- 'field' => array(
+ 'field' => [
0 => 'grant_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_grant::0::grant_type_id',
- ) ,
- 'index_status_id' => array(
+ ],
+ 'index_status_id' => [
'name' => 'index_status_id',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_grant::0::status_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Grant/Form/Grant.php b/CRM/Grant/Form/Grant.php
index fd477e6848ac..36d7afa24fe8 100644
--- a/CRM/Grant/Form/Grant.php
+++ b/CRM/Grant/Form/Grant.php
@@ -1,9 +1,9 @@
_id) {
$this->_grantType = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $this->_id, 'grant_type_id');
}
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('action', $this->_action);
$this->assign('context', $this->_context);
@@ -141,22 +141,6 @@ public function setDefaultValues() {
if (isset($defaults['amount_granted'])) {
$defaults['amount_granted'] = CRM_Utils_Money::format($defaults['amount_granted'], NULL, '%a');
}
-
- $dates = array(
- 'application_received_date',
- 'decision_date',
- 'money_transfer_date',
- 'grant_due_date',
- );
-
- foreach ($dates as $key) {
- if (!empty($defaults[$key])) {
- list($defaults[$key]) = CRM_Utils_Date::setDateDefaults($defaults[$key]);
- }
- }
- }
- else {
- list($defaults['application_received_date']) = CRM_Utils_Date::setDateDefaults();
}
return $defaults;
@@ -170,36 +154,35 @@ public function setDefaultValues() {
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Delete'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
return;
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Grant_DAO_Grant');
- $this->addSelect('grant_type_id', array('onChange' => "CRM.buildCustomData( 'Grant', this.value );"), TRUE);
+ $this->addSelect('grant_type_id', ['onChange' => "CRM.buildCustomData( 'Grant', this.value );"], TRUE);
//need to assign custom data type and subtype to the template
$this->assign('customDataType', 'Grant');
$this->assign('customDataSubType', $this->_grantType);
$this->assign('entityID', $this->_id);
- $this->addSelect('status_id', array(), TRUE);
+ $this->addSelect('status_id', [], TRUE);
- $this->addDate('application_received_date', ts('Application Received'), FALSE, array('formatType' => 'custom'));
- $this->addDate('decision_date', ts('Grant Decision'), FALSE, array('formatType' => 'custom'));
- $this->addDate('money_transfer_date', ts('Money Transferred'), FALSE, array('formatType' => 'custom'));
- $this->addDate('grant_due_date', ts('Grant Report Due'), FALSE, array('formatType' => 'custom'));
+ $this->add('datepicker', 'application_received_date', ts('Application Received'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'decision_date', ts('Grant Decision'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'money_transfer_date', ts('Money Transferred'), [], FALSE, ['time' => FALSE]);
+ $this->add('datepicker', 'grant_due_date', ts('Grant Report Due'), [], FALSE, ['time' => FALSE]);
$this->addElement('checkbox', 'grant_report_received', ts('Grant Report Received?'), NULL);
$this->add('textarea', 'rationale', ts('Rationale'), $attributes['rationale']);
@@ -223,27 +206,26 @@ public function buildQuickForm() {
// make this form an upload since we dont know if the custom data injected dynamically
// is of type file etc $uploadNames = $this->get( 'uploadNames' );
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'upload',
- 'name' => ts('Save and New'),
- 'js' => array('onclick' => "return verify( );"),
- 'subName' => 'new',
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'upload',
+ 'name' => ts('Save and New'),
+ 'js' => ['onclick' => "return verify( );"],
+ 'subName' => 'new',
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
if ($this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Applicant'), array('create' => TRUE), TRUE);
+ $this->addEntityRef('contact_id', ts('Applicant'), ['create' => TRUE], TRUE);
}
}
@@ -276,7 +258,7 @@ public function postProcess() {
}
$params['contact_id'] = $this->_contactID;
- $ids['note'] = array();
+ $ids['note'] = [];
if ($this->_noteId) {
$ids['note']['id'] = $this->_noteId;
}
diff --git a/CRM/Grant/Form/GrantView.php b/CRM/Grant/Form/GrantView.php
index a0e872b7688f..1f55a08c89e0 100644
--- a/CRM/Grant/Form/GrantView.php
+++ b/CRM/Grant/Form/GrantView.php
@@ -1,9 +1,9 @@
_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $context);
- $values = array();
+ $values = [];
$params['id'] = $this->_id;
CRM_Grant_BAO_Grant::retrieve($params, $values);
$grantType = CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_type_id');
$grantStatus = CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'status_id');
$this->assign('grantType', $grantType[$values['grant_type_id']]);
$this->assign('grantStatus', $grantStatus[$values['status_id']]);
- $grantTokens = array(
+ $grantTokens = [
'amount_total',
'amount_requested',
'amount_granted',
@@ -67,7 +67,7 @@ public function preProcess() {
'decision_date',
'money_transfer_date',
'grant_due_date',
- );
+ ];
foreach ($grantTokens as $token) {
$this->assign($token, CRM_Utils_Array::value($token, $values));
@@ -93,7 +93,7 @@ public function preProcess() {
$title = CRM_Contact_BAO_Contact::displayName($values['contact_id']) . ' - ' . ts('Grant') . ': ' . CRM_Utils_Money::format($values['amount_total']) . ' (' . $grantType[$values['grant_type_id']] . ')';
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviGrant', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/grant',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -131,15 +131,14 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'cancel',
- 'name' => ts('Done'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Done'),
+ 'spacing' => ' ',
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Search.php b/CRM/Grant/Form/Search.php
index 3a1400ad7565..9cb7c8e397cc 100644
--- a/CRM/Grant/Form/Search.php
+++ b/CRM/Grant/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
-
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
-
- // get user submitted values
- // get it from controller only if form has been submitted, else preProcess has set this
- if (!empty($_POST)) {
- $this->_formValues = $this->controller->exportValues($this->_name);
- }
- else {
- $this->_formValues = $this->get('formValues');
- }
-
- if (empty($this->_formValues)) {
- if (isset($this->_ssID)) {
- $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
- }
- }
+ $this->loadStandardSearchOptionsFromUrl();
+ $this->loadFormValues();
if ($this->_force) {
$this->postProcess();
@@ -154,9 +138,6 @@ public function preProcess() {
/**
* Build the form object.
- *
- *
- * @return void
*/
public function buildQuickForm() {
parent::buildQuickForm();
@@ -170,9 +151,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Grant_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Grant_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -319,4 +298,13 @@ public function getTitle() {
return ts('Find Grants');
}
+ /**
+ * Get metadata for fields being assigned by metadata.
+ *
+ * @return array
+ */
+ protected function getEntityMetadata() {
+ return CRM_Grant_BAO_Query::getSearchFieldMetadata();
+ }
+
}
diff --git a/CRM/Grant/Form/Task.php b/CRM/Grant/Form/Task.php
index c7700b34b94e..e868f4d64665 100644
--- a/CRM/Grant/Form/Task.php
+++ b/CRM/Grant/Form/Task.php
@@ -1,9 +1,9 @@
_grantIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_grantIds = [];
$values = $form->controller->exportValues('Search');
$form->_task = $values['task'];
- $grantTasks = CRM_Grant_Task::tasks();
- $form->assign('taskName', $grantTasks[$form->_task]);
+ $tasks = CRM_Grant_Task::tasks();
+ if (!array_key_exists($form->_task, $tasks)) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
+ }
+ $form->assign('taskName', $tasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -124,7 +105,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_grantIds = $form->_componentIds = $ids;
//set the context for redirection for any task actions
- $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
+ $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
@@ -139,7 +120,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_grantIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_grantIds,
'civicrm_grant'
);
}
@@ -156,18 +137,17 @@ public function setContactIDs() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Task/Delete.php b/CRM/Grant/Form/Task/Delete.php
index 6c6eb1cd6709..925da7565f62 100644
--- a/CRM/Grant/Form/Task/Delete.php
+++ b/CRM/Grant/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count grants deleted.', 'count' => $deleted));
+ $msg = ts('%count grant deleted.', ['plural' => '%count grants deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Grant/Form/Task/Print.php b/CRM/Grant/Form/Task/Print.php
index dc4c429abb5d..9f962f129489 100644
--- a/CRM/Grant/Form/Task/Print.php
+++ b/CRM/Grant/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Grant List'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Grant List'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Grant/Form/Task/Result.php b/CRM/Grant/Form/Task/Result.php
index 099beb47f142..eb6086e47b00 100644
--- a/CRM/Grant/Form/Task/Result.php
+++ b/CRM/Grant/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Task/SearchTaskHookSample.php b/CRM/Grant/Form/Task/SearchTaskHookSample.php
index 86708453827d..a09dfa62132a 100644
--- a/CRM/Grant/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Grant/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_grantIds);
@@ -62,12 +62,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'decision_date' => $dao->decision_date,
'amount_requested' => $dao->amount_total,
'amount_granted' => $dao->amount_granted,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -78,14 +78,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
- 'type' => 'done',
- 'name' => ts('Done'),
- 'isDefault' => TRUE,
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'done',
+ 'name' => ts('Done'),
+ 'isDefault' => TRUE,
+ ],
+ ]);
}
}
diff --git a/CRM/Grant/Form/Task/Update.php b/CRM/Grant/Form/Task/Update.php
index 552e7dc15fed..c1d9b4ad3784 100644
--- a/CRM/Grant/Form/Task/Update.php
+++ b/CRM/Grant/Form/Task/Update.php
@@ -1,9 +1,9 @@
addElement('select', 'status_id', ts('Grant Status'), array('' => '') + $grantStatus);
+ $this->addElement('select', 'status_id', ts('Grant Status'), ['' => ''] + $grantStatus);
$this->addElement('text', 'amount_granted', ts('Amount Granted'));
$this->addRule('amount_granted', ts('Please enter a valid amount.'), 'money');
- $this->addDate('decision_date', ts('Grant Decision'), FALSE, array('formatType' => 'custom'));
+ $this->add('datepicker', 'decision_date', ts('Grant Decision'), [], FALSE, ['time' => FALSE]);
- $this->assign('elements', array('status_id', 'amount_granted', 'decision_date'));
+ $this->assign('elements', ['status_id', 'amount_granted', 'decision_date']);
$this->assign('totalSelectedGrants', count($this->_grantIds));
$this->addDefaultButtons(ts('Update Grants'), 'done');
@@ -105,7 +105,7 @@ public function postProcess() {
}
}
- $status = ts('Updated Grant(s): %1 (Total Selected: %2)', array(1 => $updatedGrants, 2 => count($this->_grantIds)));
+ $status = ts('Updated Grant(s): %1 (Total Selected: %2)', [1 => $updatedGrants, 2 => count($this->_grantIds)]);
CRM_Core_Session::setStatus($status, '', 'info');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 'force=1&qfKey=' . $qfKey));
}
diff --git a/CRM/Grant/Info.php b/CRM/Grant/Info.php
index 5addd46e102c..7ae2788d9107 100644
--- a/CRM/Grant/Info.php
+++ b/CRM/Grant/Info.php
@@ -1,9 +1,9 @@
'CiviGrant',
'translatedName' => ts('CiviGrant'),
'title' => 'CiviCRM Grant Management Engine',
'path' => 'CRM_Grant_',
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
-
/**
* @inheritDoc
* @param bool $getAllUnconditionally
@@ -67,20 +67,20 @@ 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'),
- ),
- 'delete in CiviGrant' => array(
+ ],
+ 'delete in CiviGrant' => [
ts('delete in CiviGrant'),
ts('Delete grants'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -114,11 +114,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';
}
/**
@@ -126,10 +134,10 @@ public function registerTab() {
* @return array
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Grants'),
'weight' => 50,
- );
+ ];
}
/**
@@ -148,14 +156,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/Grant/Page/DashBoard.php b/CRM/Grant/Page/DashBoard.php
index 0a6bb61fe885..b039a8f9954e 100644
--- a/CRM/Grant/Page/DashBoard.php
+++ b/CRM/Grant/Page/DashBoard.php
@@ -1,9 +1,9 @@
_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -151,7 +151,7 @@ public function run() {
}
public function setContext() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this);
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Grant/Selector/Search.php b/CRM/Grant/Selector/Search.php
index 49e957623c19..19ff51cd4fa6 100644
--- a/CRM/Grant/Selector/Search.php
+++ b/CRM/Grant/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=grant' . $extraParams,
'title' => ts('View Grant'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Grant'),
- ),
- );
+ ],
+ ];
if ($cid) {
- $delLink = array(
- CRM_Core_Action::DELETE => array(
+ $delLink = [
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&selectedChild=grant' . $extraParams,
'title' => ts('Delete Grant'),
- ),
- );
+ ],
+ ];
self::$_links = self::$_links + $delLink;
}
}
@@ -279,10 +279,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
+ $rows = [];
//CRM-4418 check for view, edit, delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit grants')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -292,7 +292,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
@@ -306,11 +306,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['action'] = CRM_Core_Action::formLink(self::links($this->_key),
$mask,
- array(
+ [
'id' => $result->grant_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'grant.selector.row',
@@ -348,54 +348,54 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Status'),
'sort' => 'grant_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Type'),
'sort' => 'grant_type_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Requested'),
'sort' => 'grant_amount_total',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Granted'),
'sort' => 'grant_amount_granted',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Application Received'),
'sort' => 'grant_application_received_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Report Received'),
'sort' => 'grant_report_received',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Money Transferred'),
'sort' => 'money_transfer_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact Type')),
- array(
+ $pre = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
diff --git a/CRM/Grant/StateMachine/Search.php b/CRM/Grant/StateMachine/Search.php
index 2b387d63b0c5..6e5890336684 100644
--- a/CRM/Grant/StateMachine/Search.php
+++ b/CRM/Grant/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Grant_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -82,7 +82,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Grant/Task.php b/CRM/Grant/Task.php
index 290f52ab78f2..467853f627a6 100644
--- a/CRM/Grant/Task.php
+++ b/CRM/Grant/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete grants'),
'class' => 'CRM_Grant_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Grant_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export grants'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
+ ],
+ self::UPDATE_GRANTS => [
'title' => ts('Update grants'),
'class' => 'CRM_Grant_Form_Task_Update',
'result' => FALSE,
- ),
- );
+ ],
+ ];
if (!CRM_Core_Permission::check('delete in CiviGrant')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
- CRM_Utils_Hook::searchTasks('grant', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit grants')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviGrant')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -154,14 +135,12 @@ public static function &permissionedTaskTitles($permission) {
*/
public static function getTask($value) {
self::tasks();
- if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
- // make the print task by default
- $value = 2;
+
+ if (!CRM_Utils_Array::value($value, self::$_tasks)) {
+ // make it the print task by default
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Group/Controller.php b/CRM/Group/Controller.php
index b97e1030393e..8e3f05464afc 100644
--- a/CRM/Group/Controller.php
+++ b/CRM/Group/Controller.php
@@ -1,9 +1,9 @@
entityFields = [
+ 'title' => [
+ 'name' => 'title',
+ 'required' => TRUE,
+ ],
+ 'description' => ['name' => 'description'],
+ ];
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = '';
+ }
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'Group';
+ }
+
/**
* Set up variables to build the form.
*/
@@ -106,7 +137,12 @@ public function preProcess() {
if ($this->_action == CRM_Core_Action::DELETE) {
if (isset($this->_id)) {
$this->assign('title', $this->_title);
- $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
+ try {
+ $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
+ }
+ catch (CRM_Core_Exception $e) {
+ // If the group is borked the query might fail but delete should be possible.
+ }
CRM_Utils_System::setTitle(ts('Confirm Group Delete'));
}
if ($this->_groupValues['is_reserved'] == 1 && !CRM_Core_Permission::check('administer reserved groups')) {
@@ -160,7 +196,6 @@ public function preProcess() {
*/
public function setDefaultValues() {
$defaults = array();
-
if (isset($this->_id)) {
$defaults = $this->_groupValues;
if (!empty($defaults['group_type'])) {
@@ -177,6 +212,9 @@ public function setDefaultValues() {
CRM_Contact_BAO_GroupOrganization::retrieve($this->_id, $defaults);
}
}
+ else {
+ $defaults['is_active'] = 1;
+ }
if (!((CRM_Core_Permission::check('access CiviMail')) ||
(CRM_Mailing_Info::workflowEnabled() &&
@@ -206,19 +244,8 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
- if ($this->_action == CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Delete Group'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ self::buildQuickEntityForm();
+ if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
@@ -227,15 +254,6 @@ public function buildQuickForm() {
$this->preventAjaxSubmit();
}
- $this->applyFilter('__ALL__', 'trim');
- $this->add('text', 'title', ts('Name') . ' ',
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'), TRUE
- );
-
- $this->add('textarea', 'description', ts('Description') . ' ',
- CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'description')
- );
-
$groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
if (isset($this->_id) && !empty($this->_groupValues['saved_search_id'])) {
@@ -261,23 +279,11 @@ public function buildQuickForm() {
if (!CRM_Core_Permission::check('administer reserved groups')) {
$this->freeze('is_reserved');
}
+ $this->addElement('checkbox', 'is_active', ts('Is active?'));
//build custom data
CRM_Custom_Form_CustomData::buildQuickForm($this);
- $this->addButtons(array(
- array(
- 'type' => 'upload',
- 'name' => ($this->_action == CRM_Core_Action::ADD) ? ts('Continue') : ts('Save'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
-
$doParentCheck = FALSE;
if (CRM_Core_Permission::isMultisiteEnabled()) {
$doParentCheck = ($this->_id && CRM_Core_BAO_Domain::isDomainGroup($this->_id)) ? FALSE : TRUE;
@@ -356,7 +362,7 @@ public static function formRule($fields, $fileParams, $options) {
* Process the form when submitted.
*/
public function postProcess() {
- CRM_Utils_System::flushCache('CRM_Core_DAO_Group');
+ CRM_Utils_System::flushCache();
$updateNestingCache = FALSE;
if ($this->_action & CRM_Core_Action::DELETE) {
@@ -367,9 +373,6 @@ public function postProcess() {
else {
// store the submitted values in an array
$params = $this->controller->exportValues($this->_name);
-
- $params['is_active'] = CRM_Utils_Array::value('is_active', $this->_groupValues, 1);
-
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
}
@@ -378,8 +381,13 @@ public function postProcess() {
$params['group_organization'] = $this->_groupOrganizationID;
}
- $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
+ // CRM-21431 If all group_type are unchecked, the change will not be saved otherwise.
+ if (!isset($params['group_type'])) {
+ $params['group_type'] = array();
+ }
+ $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
+ $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
$this->_id,
'Group'
@@ -448,7 +456,7 @@ public static function buildParentGroups(&$form) {
$potentialParentGroupIds = array_keys($groupNames);
}
- $parentGroupSelectValues = array('' => '- ' . ts('select group') . ' -');
+ $parentGroupSelectValues = array();
foreach ($potentialParentGroupIds as $potentialParentGroupId) {
if (array_key_exists($potentialParentGroupId, $groupNames)) {
$parentGroupSelectValues[$potentialParentGroupId] = $groupNames[$potentialParentGroupId];
@@ -462,7 +470,7 @@ public static function buildParentGroups(&$form) {
else {
$required = FALSE;
}
- $form->add('select', 'parents', ts('Add Parent'), $parentGroupSelectValues, $required, array('class' => 'crm-select2'));
+ $form->add('select', 'parents', ts('Add Parent'), $parentGroupSelectValues, $required, array('class' => 'crm-select2', 'multiple' => TRUE));
}
return $parentGroups;
diff --git a/CRM/Group/Form/Search.php b/CRM/Group/Form/Search.php
index 6922d218dfb6..8de0d8beaa58 100644
--- a/CRM/Group/Form/Search.php
+++ b/CRM/Group/Form/Search.php
@@ -1,9 +1,9 @@
add('select', 'visibility', ts('Visibility'),
- array('' => ts('- any visibility -')) + CRM_Core_SelectValues::ufVisibility(TRUE)
+ ['' => ts('- any visibility -')] + CRM_Core_SelectValues::ufVisibility(TRUE)
);
- $groupStatuses = array(ts('Enabled') => 1, ts('Disabled') => 2);
+ $groupStatuses = [ts('Enabled') => 1, ts('Disabled') => 2];
$this->addCheckBox('group_status',
ts('Status'),
$groupStatuses,
NULL, NULL, NULL, NULL, ' '
);
- $this->addButtons(array(
- array(
+ $componentModes = CRM_Contact_Form_Search::getModeSelect();
+ if (count($componentModes) > 1) {
+ $this->add('select',
+ 'component_mode',
+ ts('View Results As'),
+ $componentModes,
+ FALSE,
+ ['class' => 'crm-select2']
+ );
+ }
+
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
parent::buildQuickForm();
$this->assign('suppressForm', TRUE);
@@ -97,7 +108,7 @@ public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array('title', 'created_by', 'group_type', 'visibility', 'active_status', 'inactive_status');
+ $fields = ['title', 'created_by', 'group_type', 'visibility', 'active_status', 'inactive_status', 'component_mode'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
diff --git a/CRM/Group/Page/AJAX.php b/CRM/Group/Page/AJAX.php
index 9210ddbead21..5ccad88a887f 100644
--- a/CRM/Group/Page/AJAX.php
+++ b/CRM/Group/Page/AJAX.php
@@ -1,9 +1,9 @@
'String',
'created_by' => 'String',
'group_type' => 'String',
'visibility' => 'String',
+ 'component_mode' => 'String',
'status' => 'Integer',
'parentsOnly' => 'Integer',
'showOrgInfo' => 'Boolean',
// Ignore 'parent_id' as that case is handled above
- );
+ ];
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParams, $optionalParams);
diff --git a/CRM/Group/Page/Group.php b/CRM/Group/Page/Group.php
index c371fe56bc76..a4409c2e4905 100644
--- a/CRM/Group/Page/Group.php
+++ b/CRM/Group/Page/Group.php
@@ -1,9 +1,9 @@
_pages = array(
+ $this->_pages = [
'CRM_Group_Form_Edit' => NULL,
'CRM_Contact_Form_Search_Basic' => NULL,
'CRM_Contact_Form_Task_AddToGroup' => NULL,
'CRM_Contact_Form_Task_Result' => NULL,
- );
+ ];
$this->addSequentialPages($this->_pages, $action);
}
diff --git a/CRM/Import/DataSource.php b/CRM/Import/DataSource.php
index 9091e3f647a1..a9d837d59693 100644
--- a/CRM/Import/DataSource.php
+++ b/CRM/Import/DataSource.php
@@ -1,9 +1,9 @@
ts('Comma-Separated Values (CSV)'));
+ return ['title' => ts('Comma-Separated Values (CSV)')];
}
/**
@@ -74,10 +74,10 @@ public function buildQuickForm(&$form) {
$form->assign('uploadSize', $uploadSize);
$form->add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
$form->setMaxFileSize($uploadFileSize);
- $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(
- 1 => $uploadSize,
- 2 => $uploadFileSize,
- )), 'maxfilesize', $uploadFileSize);
+ $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', [
+ 1 => $uploadSize,
+ 2 => $uploadFileSize,
+ ]), 'maxfilesize', $uploadFileSize);
$form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
$form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
@@ -131,7 +131,7 @@ private static function _CsvToTable(
$table = NULL,
$fieldSeparator = ','
) {
- $result = array();
+ $result = [];
$fd = fopen($file, 'r');
if (!$fd) {
CRM_Core_Error::fatal("Could not read $file");
@@ -192,7 +192,7 @@ private static function _CsvToTable(
}
}
else {
- $columns = array();
+ $columns = [];
foreach ($firstrow as $i => $_) {
$columns[] = "col_$i";
}
@@ -239,7 +239,7 @@ private static function _CsvToTable(
function($string) {
return trim($string, chr(0xC2) . chr(0xA0));
}, $row);
- $row = array_map(array('CRM_Core_DAO', 'escapeString'), $row);
+ $row = array_map(['CRM_Core_DAO', 'escapeString'], $row);
$sql .= "('" . implode("', '", $row) . "')";
$count++;
diff --git a/CRM/Import/DataSource/SQL.php b/CRM/Import/DataSource/SQL.php
index 5223d2e8032c..0017b5c55af3 100644
--- a/CRM/Import/DataSource/SQL.php
+++ b/CRM/Import/DataSource/SQL.php
@@ -1,9 +1,9 @@
ts('SQL Query'),
- 'permissions' => array('import SQL datasource'),
- );
+ 'permissions' => ['import SQL datasource'],
+ ];
}
/**
@@ -68,7 +68,7 @@ public function preProcess(&$form) {
public function buildQuickForm(&$form) {
$form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_SQL');
$form->add('textarea', 'sqlQuery', ts('Specify SQL Query'), 'rows=10 cols=45', TRUE);
- $form->addFormRule(array('CRM_Import_DataSource_SQL', 'formRule'), $form);
+ $form->addFormRule(['CRM_Import_DataSource_SQL', 'formRule'], $form);
}
/**
@@ -79,13 +79,13 @@ public function buildQuickForm(&$form) {
* @return array|bool
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
// Makeshift query validation (case-insensitive regex matching on word boundaries)
- $forbidden = array('ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'information_schema');
+ $forbidden = ['ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'information_schema'];
foreach ($forbidden as $pattern) {
if (preg_match("/\\b$pattern\\b/i", $fields['sqlQuery'])) {
- $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', array(1 => $pattern));
+ $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', [1 => $pattern]);
}
}
diff --git a/CRM/Import/Form/DataSource.php b/CRM/Import/Form/DataSource.php
index 6a7ba2ab9322..ae577f0c519c 100644
--- a/CRM/Import/Form/DataSource.php
+++ b/CRM/Import/Form/DataSource.php
@@ -1,9 +1,9 @@
add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
$this->setMaxFileSize($uploadFileSize);
- $this->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(
+ $this->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', [
1 => $uploadSize,
2 => $uploadFileSize,
- )), 'maxfilesize', $uploadFileSize);
+ ]), 'maxfilesize', $uploadFileSize);
$this->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
$this->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
$this->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
- $this->add('text', 'fieldSeparator', ts('Import Field Separator'), array('size' => 2), TRUE);
- $this->setDefaults(array('fieldSeparator' => $config->fieldSeparator));
+ $this->add('text', 'fieldSeparator', ts('Import Field Separator'), ['size' => 2], TRUE);
+ $this->setDefaults(['fieldSeparator' => $config->fieldSeparator]);
$mappingArray = CRM_Core_BAO_Mapping::getCreateMappingValues('Import ' . static::IMPORT_ENTITY);
$this->assign('savedMapping', $mappingArray);
- $this->add('select', 'savedMapping', ts('Mapping Option'), array('' => ts('- select -')) + $mappingArray);
+ $this->add('select', 'savedMapping', ts('Mapping Option'), ['' => ts('- select -')] + $mappingArray);
if ($loadedMapping = $this->get('loadedMapping')) {
$this->assign('loadedMapping', $loadedMapping);
- $this->setDefaults(array('savedMapping' => $loadedMapping));
+ $this->setDefaults(['savedMapping' => $loadedMapping]);
}
//build date formats
CRM_Core_Form_Date::buildAllowedDateFormats($this);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
/**
@@ -112,7 +111,7 @@ public function buildQuickForm() {
*/
protected function addContactTypeSelector() {
//contact types option
- $contactOptions = array();
+ $contactOptions = [];
if (CRM_Contact_BAO_ContactType::isActive('Individual')) {
$contactOptions[] = $this->createElement('radio',
NULL, NULL, ts('Individual'), CRM_Import_Parser::CONTACT_INDIVIDUAL
@@ -133,9 +132,9 @@ protected function addContactTypeSelector() {
ts('Contact Type')
);
- $this->setDefaults(array(
+ $this->setDefaults([
'contactType' => CRM_Import_Parser::CONTACT_INDIVIDUAL,
- ));
+ ]);
}
/**
@@ -168,7 +167,7 @@ protected function submitFileForMapping($parserClassName, $entity = NULL) {
$separator = $this->controller->exportValue($this->_name, 'fieldSeparator');
- $mapper = array();
+ $mapper = [];
$parser = new $parserClassName($mapper);
if ($entity) {
diff --git a/CRM/Import/Form/MapField.php b/CRM/Import/Form/MapField.php
index 08ca4fbd34e2..c6a82f7877a9 100644
--- a/CRM/Import/Form/MapField.php
+++ b/CRM/Import/Form/MapField.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'back',
'name' => ts('Previous'),
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Import Now'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
+ }
+
+ /**
+ * Set status url for ajax.
+ */
+ public function setStatusUrl() {
+ $statusID = $this->get('statusID');
+ if (!$statusID) {
+ $statusID = md5(uniqid(rand(), TRUE));
+ $this->set('statusID', $statusID);
+ }
+ $statusUrl = CRM_Utils_System::url('civicrm/ajax/status', "id={$statusID}", FALSE, NULL, FALSE);
+ $this->assign('statusUrl', $statusUrl);
}
}
diff --git a/CRM/Import/Form/Summary.php b/CRM/Import/Form/Summary.php
index 32639f8cb8a4..f24de6ebb9cf 100644
--- a/CRM/Import/Form/Summary.php
+++ b/CRM/Import/Form/Summary.php
@@ -1,9 +1,9 @@
ts('Done'),
'isDefault' => TRUE,
),
- )
- );
+ ));
}
/**
diff --git a/CRM/Import/Parser.php b/CRM/Import/Parser.php
index c4169c2c5d37..cf01fdd05482 100644
--- a/CRM/Import/Parser.php
+++ b/CRM/Import/Parser.php
@@ -1,9 +1,9 @@
_maxLinesToProcess = 0;
- $this->_maxErrorCount = self::MAX_ERRORS;
}
/**
@@ -279,7 +284,7 @@ public function setActiveFieldValues($elements, &$erroneousField) {
* (reference) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -292,11 +297,66 @@ public function &getActiveFieldParams() {
return $params;
}
+ /**
+ * Add progress bar to the import process. Calculates time remaining, status etc.
+ *
+ * @param $statusID
+ * status id of the import process saved in $config->uploadDir.
+ * @param bool $startImport
+ * True when progress bar is to be initiated.
+ * @param $startTimestamp
+ * Initial timstamp when the import was started.
+ * @param $prevTimestamp
+ * Previous timestamp when this function was last called.
+ * @param $totalRowCount
+ * Total number of rows in the import file.
+ *
+ * @return NULL|$currTimestamp
+ */
+ public function progressImport($statusID, $startImport = TRUE, $startTimestamp = NULL, $prevTimestamp = NULL, $totalRowCount = NULL) {
+ $config = CRM_Core_Config::singleton();
+ $statusFile = "{$config->uploadDir}status_{$statusID}.txt";
+
+ if ($startImport) {
+ $status = "
' . ts('More information on tokens...') . '';
}
}
return empty($errors) ? TRUE : $errors;
@@ -196,7 +194,7 @@ public static function dataRule($params, $files, $options) {
* mixed true or array of errors
*/
public static function formRule($params, $files, $options) {
- $errors = array();
+ $errors = [];
if (empty($params['body_text']) && empty($params['body_html'])) {
$errors['body_text'] = ts("Please provide either HTML or TEXT format for the Body.");
$errors['body_html'] = ts("Please provide either HTML or TEXT format for the Body.");
diff --git a/CRM/Mailing/Form/ForwardMailing.php b/CRM/Mailing/Form/ForwardMailing.php
index 83c212b7e438..3d7a04cf2c48 100644
--- a/CRM/Mailing/Form/ForwardMailing.php
+++ b/CRM/Mailing/Form/ForwardMailing.php
@@ -1,9 +1,9 @@
$mailing->subject)));
+ CRM_Utils_System::setTitle(ts('Forward Mailing: %1', [1 => $mailing->subject]));
$this->set('queue_id', $queue_id);
$this->set('job_id', $job_id);
@@ -73,28 +74,28 @@ public function preProcess() {
*/
public function buildQuickForm() {
for ($i = 0; $i < 5; $i++) {
- $this->add('text', "email_$i", ts('Email %1', array(1 => $i + 1)));
+ $this->add('text', "email_$i", ts('Email %1', [1 => $i + 1]));
$this->addRule("email_$i", ts('Email is not valid.'), 'email');
}
//insert message Text by selecting "Select Template option"
- $this->add('textarea', 'forward_comment', ts('Comment'), array('cols' => '80', 'rows' => '8'));
+ $this->add('textarea', 'forward_comment', ts('Comment'), ['cols' => '80', 'rows' => '8']);
$this->add('wysiwyg', 'html_comment',
ts('HTML Message'),
- array('cols' => '80', 'rows' => '8')
+ ['cols' => '80', 'rows' => '8']
);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Forward'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -107,12 +108,12 @@ public function postProcess() {
$timeStamp = date('YmdHis');
$formValues = $this->controller->exportValues($this->_name);
- $params = array();
+ $params = [];
$params['body_text'] = $formValues['forward_comment'];
$html_comment = $formValues['html_comment'];
$params['body_html'] = str_replace('%7B', '{', str_replace('%7D', '}', $html_comment));
- $emails = array();
+ $emails = [];
for ($i = 0; $i < 5; $i++) {
$email = $this->controller->exportValue($this->_name, "email_$i");
if (!empty($email)) {
@@ -122,7 +123,7 @@ public function postProcess() {
$forwarded = NULL;
foreach ($emails as $email) {
- $params = array(
+ $params = [
'version' => 3,
'job_id' => $job_id,
'event_queue_id' => $queue_id,
@@ -131,22 +132,22 @@ public function postProcess() {
'time_stamp' => $timeStamp,
'fromEmail' => $this->_fromEmail,
'params' => $params,
- );
+ ];
$result = civicrm_api('Mailing', 'event_forward', $params);
if (!civicrm_error($result)) {
$forwarded++;
}
}
- $status = ts('Mailing is not forwarded to the given email address.', array(
- 'count' => count($emails),
- 'plural' => 'Mailing is not forwarded to the given email addresses.',
- ));
+ $status = ts('Mailing is not forwarded to the given email address.', [
+ 'count' => count($emails),
+ 'plural' => 'Mailing is not forwarded to the given email addresses.',
+ ]);
if ($forwarded) {
- $status = ts('Mailing is forwarded successfully to %count email address.', array(
- 'count' => $forwarded,
- 'plural' => 'Mailing is forwarded successfully to %count email addresses.',
- ));
+ $status = ts('Mailing is forwarded successfully to %count email address.', [
+ 'count' => $forwarded,
+ 'plural' => 'Mailing is forwarded successfully to %count email addresses.',
+ ]);
}
CRM_Utils_System::setUFMessage($status);
diff --git a/CRM/Mailing/Form/Optout.php b/CRM/Mailing/Form/Optout.php
index 7fe3d2b2aecb..7473fe3af3bc 100644
--- a/CRM/Mailing/Form/Optout.php
+++ b/CRM/Mailing/Form/Optout.php
@@ -1,9 +1,9 @@
add('text', 'email_confirm', ts('Verify email address to opt out:'));
$this->addRule('email_confirm', ts('Email address is required to opt out.'), 'required');
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => ts('Opt Out'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -106,19 +106,18 @@ public function postProcess() {
}
$statusMsg = ts('Email: %1 has been successfully opted out',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
CRM_Core_Session::setStatus($statusMsg, '', 'success');
}
elseif ($result == FALSE) {
// Email address not verified
-
$statusMsg = ts('The email address: %1 you have entered does not match the email associated with this opt out request.',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
- CRM_Core_Session::setStatus($statusMsg, '', 'fail');
+ CRM_Core_Session::setStatus($statusMsg, '', 'error');
}
}
diff --git a/CRM/Mailing/Form/Search.php b/CRM/Mailing/Form/Search.php
index 3c9b6b0fa083..d2d6af941ea9 100644
--- a/CRM/Mailing/Form/Search.php
+++ b/CRM/Mailing/Form/Search.php
@@ -1,9 +1,9 @@
1) {
- $this->addElement('select', 'language', ts('Language'), array('' => ts('- all languages -')) + $enabledLanguages, array('class' => 'crm-select2'));
+ $this->addElement('select', 'language', ts('Language'), ['' => ts('- all languages -')] + $enabledLanguages, ['class' => 'crm-select2']);
}
if ($parent->_sms) {
@@ -72,27 +72,27 @@ public function buildQuickForm() {
}
$this->add('hidden', 'hidden_find_mailings', 1);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
/**
* @return array
*/
public function setDefaultValues() {
- $defaults = $statusVals = array();
+ $defaults = $statusVals = [];
$parent = $this->controller->getParent();
if ($parent->get('unscheduled')) {
$defaults['status_unscheduled'] = 1;
}
if ($parent->get('scheduled')) {
- $statusVals = array('Scheduled', 'Complete', 'Running', 'Canceled');
+ $statusVals = array_keys(CRM_Core_SelectValues::getMailingJobStatus());
$defaults['is_archived'] = 0;
}
if ($parent->get('archived')) {
@@ -115,7 +115,7 @@ public function postProcess() {
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array(
+ $fields = [
'mailing_name',
'mailing_from',
'mailing_to',
@@ -127,16 +127,15 @@ public function postProcess() {
'is_archived',
'language',
'hidden_find_mailings',
- );
+ ];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
) {
- if (in_array($field, array(
- 'mailing_from',
- 'mailing_to',
- )) && !$params["mailing_relative"]
- ) {
+ if (in_array($field, [
+ 'mailing_from',
+ 'mailing_to',
+ ]) && !$params["mailing_relative"]) {
$time = ($field == 'mailing_to') ? '235959' : NULL;
$parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
}
diff --git a/CRM/Mailing/Form/Subscribe.php b/CRM/Mailing/Form/Subscribe.php
index dbe9ad5a4f06..6a8feae66b2e 100644
--- a/CRM/Mailing/Form/Subscribe.php
+++ b/CRM/Mailing/Form/Subscribe.php
@@ -1,9 +1,9 @@
fetch()) {
$this->assign('groupName', $dao->title);
- CRM_Utils_System::setTitle(ts('Subscribe to Mailing List - %1', array(1 => $dao->title)));
+ CRM_Utils_System::setTitle(ts('Subscribe to Mailing List - %1', [1 => $dao->title]));
}
else {
CRM_Core_Error::statusBounce("The specified group is not configured for this action OR The group doesn't exist.");
@@ -101,9 +101,9 @@ public function buildQuickForm() {
AND $groupTypeCondition
ORDER BY title";
$dao = CRM_Core_DAO::executeQuery($query);
- $rows = array();
+ $rows = [];
while ($dao->fetch()) {
- $row = array();
+ $row = [];
$row['id'] = $dao->id;
$row['title'] = $dao->title;
$row['description'] = $dao->description;
@@ -118,7 +118,7 @@ public function buildQuickForm() {
CRM_Core_Error::fatal(ts('There are no public mailing list groups to display.'));
}
$this->assign('rows', $rows);
- $this->addFormRule(array('CRM_Mailing_Form_Subscribe', 'formRule'));
+ $this->addFormRule(['CRM_Mailing_Form_Subscribe', 'formRule']);
}
$addCaptcha = TRUE;
@@ -153,18 +153,17 @@ public function buildQuickForm() {
$this->assign('isCaptcha', TRUE);
}
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Subscribe'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Subscribe'),
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'cancel',
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
/**
@@ -178,13 +177,13 @@ public static function formRule($fields) {
return TRUE;
}
}
- return array('_qf_default' => 'Please select one or more mailing lists.');
+ return ['_qf_default' => 'Please select one or more mailing lists.'];
}
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
- $groups = array();
+ $groups = [];
if ($this->_groupID) {
$groups[] = $this->_groupID;
}
diff --git a/CRM/Mailing/Form/Task.php b/CRM/Mailing/Form/Task.php
index 3b0f9acf240e..edd13fb523c2 100644
--- a/CRM/Mailing/Form/Task.php
+++ b/CRM/Mailing/Form/Task.php
@@ -1,9 +1,9 @@
controller->exportValues($form->get('searchFormName'));
$form->_task = CRM_Utils_Array::value('task', $values);
@@ -76,7 +55,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->assign('taskName', CRM_Utils_Array::value('task', $values));
// ids are mailing event queue ids
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -136,18 +115,17 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
- 'type' => $nextType,
- 'name' => $title,
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => $backType,
- 'name' => ts('Cancel'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => $nextType,
+ 'name' => $title,
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => $backType,
+ 'name' => ts('Cancel'),
+ ],
+ ]);
}
}
diff --git a/CRM/Mailing/Form/Task/AdhocMailing.php b/CRM/Mailing/Form/Task/AdhocMailing.php
index 6a06b30e867f..f08cf4993984 100644
--- a/CRM/Mailing/Form/Task/AdhocMailing.php
+++ b/CRM/Mailing/Form/Task/AdhocMailing.php
@@ -1,9 +1,9 @@
createHiddenGroup();
- $mailing = civicrm_api3('Mailing', 'create', array(
+ $mailing = civicrm_api3('Mailing', 'create', [
'name' => "",
'campaign_id' => NULL,
'replyto_email' => "",
'template_type' => $templateTypes[0]['name'],
- 'template_options' => array('nonce' => 1),
+ 'template_options' => ['nonce' => 1],
'subject' => "",
'body_html' => "",
'body_text' => "",
- 'groups' => array(
- 'include' => array($groupId),
- 'exclude' => array(),
- 'base' => array(),
- ),
- 'mailings' => array(
- 'include' => array(),
- 'exclude' => array(),
- ),
- ));
+ 'groups' => [
+ 'include' => [$groupId],
+ 'exclude' => [],
+ 'base' => [],
+ ],
+ 'mailings' => [
+ 'include' => [],
+ 'exclude' => [],
+ ],
+ ]);
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/a/', NULL, TRUE, '/mailing/' . $mailing['id']));
}
diff --git a/CRM/Mailing/Form/Task/Print.php b/CRM/Mailing/Form/Task/Print.php
index 206b92f1a289..0d1322edd4f6 100644
--- a/CRM/Mailing/Form/Task/Print.php
+++ b/CRM/Mailing/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Print Mailing Recipients'),
- 'js' => array('onclick' => 'window.print()'),
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'back',
- 'name' => ts('Done'),
- ),
- )
- );
+ $this->addButtons([
+ [
+ 'type' => 'next',
+ 'name' => ts('Print Mailing Recipients'),
+ 'js' => ['onclick' => 'window.print()'],
+ 'isDefault' => TRUE,
+ ],
+ [
+ 'type' => 'back',
+ 'name' => ts('Done'),
+ ],
+ ]);
}
/**
diff --git a/CRM/Mailing/Form/Unsubscribe.php b/CRM/Mailing/Form/Unsubscribe.php
index a638a2f70fa5..33cee130f289 100644
--- a/CRM/Mailing/Form/Unsubscribe.php
+++ b/CRM/Mailing/Form/Unsubscribe.php
@@ -1,9 +1,9 @@
$email)
+ [1 => $email]
);
- CRM_Core_Session::setStatus($statusMsg, '', 'fail');
+ CRM_Core_Session::setStatus($statusMsg, '', 'error');
}
$this->assign('groupExist', $groupExist);
@@ -85,17 +85,17 @@ public function buildQuickForm() {
$this->add('text', 'email_confirm', ts('Verify email address to unsubscribe:'));
$this->addRule('email_confirm', ts('Email address is required to unsubscribe.'), 'required');
- $buttons = array(
- array(
+ $buttons = [
+ [
'type' => 'next',
'name' => ts('Unsubscribe'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
$this->addButtons($buttons);
}
@@ -116,26 +116,25 @@ public function postProcess() {
if ($result == TRUE) {
// Email address verified
-
$groups = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($job_id, $queue_id, $hash);
+
if (count($groups)) {
CRM_Mailing_Event_BAO_Unsubscribe::send_unsub_response($queue_id, $groups, FALSE, $job_id);
}
$statusMsg = ts('Email: %1 has been successfully unsubscribed from this Mailing List/Group.',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
CRM_Core_Session::setStatus($statusMsg, '', 'success');
}
elseif ($result == FALSE) {
// Email address not verified
-
$statusMsg = ts('The email address: %1 you have entered does not match the email associated with this unsubscribe request.',
- array(1 => $values['email_confirm'])
+ [1 => $values['email_confirm']]
);
- CRM_Core_Session::setStatus($statusMsg, '', 'fail');
+ CRM_Core_Session::setStatus($statusMsg, '', 'error');
}
diff --git a/CRM/Mailing/Info.php b/CRM/Mailing/Info.php
index 59ec9e123549..a674129e54aa 100644
--- a/CRM/Mailing/Info.php
+++ b/CRM/Mailing/Info.php
@@ -1,9 +1,9 @@
'CiviMail',
'translatedName' => ts('CiviMail'),
'title' => ts('CiviCRM Mailing Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
/**
@@ -69,19 +69,22 @@ public function getAngularModules() {
&& !CRM_Core_Permission::check('schedule mailings')
&& !CRM_Core_Permission::check('approve mailings')
) {
- return array();
+ return [];
}
global $civicrm_root;
- $reportIds = array();
- $reportTypes = array('detail', 'opened', 'bounce', 'clicks');
+ $reportIds = [];
+ $reportTypes = ['detail', 'opened', 'bounce', 'clicks'];
foreach ($reportTypes as $report) {
- $result = civicrm_api3('ReportInstance', 'get', array(
+ $result = civicrm_api3('ReportInstance', 'get', [
'sequential' => 1,
- 'report_id' => 'mailing/' . $report));
- $reportIds[$report] = $result['values'][0]['id'];
+ 'report_id' => 'mailing/' . $report,
+ ]);
+ if (!empty($result['values'])) {
+ $reportIds[$report] = $result['values'][0]['id'];
+ }
}
- $result = array();
+ $result = [];
$result['crmMailing'] = include "$civicrm_root/ang/crmMailing.ang.php";
$result['crmMailingAB'] = include "$civicrm_root/ang/crmMailingAB.ang.php";
$result['crmD3'] = include "$civicrm_root/ang/crmD3.ang.php";
@@ -91,72 +94,74 @@ public function getAngularModules() {
$contactID = $session->get('userID');
// Generic params.
- $params = array(
- 'options' => array('limit' => 0),
+ $params = [
+ 'options' => ['limit' => 0],
'sequential' => 1,
- );
- $groupNames = civicrm_api3('Group', 'get', $params + array(
+ ];
+ $groupNames = civicrm_api3('Group', 'get', $params + [
'is_active' => 1,
'check_permissions' => TRUE,
- 'return' => array('title', 'visibility', 'group_type', 'is_hidden'),
- ));
- $headerfooterList = civicrm_api3('MailingComponent', 'get', $params + array(
+ 'return' => ['title', 'visibility', 'group_type', 'is_hidden'],
+ ]);
+ $headerfooterList = civicrm_api3('MailingComponent', 'get', $params + [
'is_active' => 1,
- 'return' => array('name', 'component_type', 'is_default', 'body_html', 'body_text'),
- ));
+ 'return' => ['name', 'component_type', 'is_default', 'body_html', 'body_text'],
+ ]);
- $emailAdd = civicrm_api3('Email', 'get', array(
+ $emailAdd = civicrm_api3('Email', 'get', [
'sequential' => 1,
'return' => "email",
'contact_id' => $contactID,
- ));
+ ]);
- $mesTemplate = civicrm_api3('MessageTemplate', 'get', $params + array(
+ $mesTemplate = civicrm_api3('MessageTemplate', 'get', $params + [
'sequential' => 1,
'is_active' => 1,
- 'return' => array("id", "msg_title"),
- 'workflow_id' => array('IS NULL' => ""),
- ));
- $mailTokens = civicrm_api3('Mailing', 'gettokens', array(
- 'entity' => array('contact', 'mailing'),
+ 'return' => ["id", "msg_title"],
+ 'workflow_id' => ['IS NULL' => ""],
+ ]);
+ $mailTokens = civicrm_api3('Mailing', 'gettokens', [
+ 'entity' => ['contact', 'mailing'],
'sequential' => 1,
- ));
- $fromAddress = civicrm_api3('OptionValue', 'get', $params + array(
+ ]);
+ $fromAddress = civicrm_api3('OptionValue', 'get', $params + [
'option_group_id' => "from_email_address",
'domain_id' => CRM_Core_Config::domainID(),
- ));
+ ]);
$enabledLanguages = CRM_Core_I18n::languages(TRUE);
$isMultiLingual = (count($enabledLanguages) > 1);
+ // FlexMailer is a refactoring of CiviMail which provides new hooks/APIs/docs. If the sysadmin has opted to enable it, then use that instead of CiviMail.
+ $requiredTokens = defined('CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS') ? Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS, []) : CRM_Utils_Token::getRequiredTokens();
CRM_Core_Resources::singleton()
- ->addSetting(array(
- 'crmMailing' => array(
+ ->addSetting([
+ 'crmMailing' => [
'templateTypes' => CRM_Mailing_BAO_Mailing::getTemplateTypes(),
- 'civiMails' => array(),
+ 'civiMails' => [],
'campaignEnabled' => in_array('CiviCampaign', $config->enableComponents),
- 'groupNames' => array(),
- // @todo see if we can remove this by dynamically generating the test group list
+ 'groupNames' => [],
+ // @todo this is not used in core. Remove once Mosaico no longer depends on it.
'testGroupNames' => $groupNames['values'],
'headerfooterList' => $headerfooterList['values'],
'mesTemplate' => $mesTemplate['values'],
'emailAdd' => $emailAdd['values'],
'mailTokens' => $mailTokens['values'],
'contactid' => $contactID,
- 'requiredTokens' => CRM_Utils_Token::getRequiredTokens(),
+ 'requiredTokens' => $requiredTokens,
'enableReplyTo' => (int) Civi::settings()->get('replyTo'),
'disableMandatoryTokensCheck' => (int) Civi::settings()->get('disable_mandatory_tokens_check'),
'fromAddress' => $fromAddress['values'],
- 'defaultTestEmail' => civicrm_api3('Contact', 'getvalue', array(
- 'id' => 'user_contact_id',
- 'return' => 'email',
- )),
+ 'defaultTestEmail' => civicrm_api3('Contact', 'getvalue', [
+ 'id' => 'user_contact_id',
+ 'return' => 'email',
+ ]),
'visibility' => CRM_Utils_Array::makeNonAssociative(CRM_Core_SelectValues::groupVisibility()),
'workflowEnabled' => CRM_Mailing_Info::workflowEnabled(),
'reportIds' => $reportIds,
'enabledLanguages' => $enabledLanguages,
'isMultiLingual' => $isMultiLingual,
- ),
- ))
- ->addPermissions(array(
+ ],
+ ])
+ ->addPermissions([
'view all contacts',
'edit all contacts',
'access CiviMail',
@@ -165,7 +170,7 @@ public function getAngularModules() {
'approve mailings',
'delete in CiviMail',
'edit message templates',
- ));
+ ]);
return $result;
}
@@ -203,33 +208,33 @@ public static function workflowEnabled() {
* @return array
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviMail' => array(
+ $permissions = [
+ 'access CiviMail' => [
ts('access CiviMail'),
- ),
- 'access CiviMail subscribe/unsubscribe pages' => array(
+ ],
+ 'access CiviMail subscribe/unsubscribe pages' => [
ts('access CiviMail subscribe/unsubscribe pages'),
ts('Subscribe/unsubscribe from mailing list group'),
- ),
- 'delete in CiviMail' => array(
+ ],
+ 'delete in CiviMail' => [
ts('delete in CiviMail'),
ts('Delete Mailing'),
- ),
- 'view public CiviMail content' => array(
+ ],
+ 'view public CiviMail content' => [
ts('view public CiviMail content'),
- ),
- );
+ ],
+ ];
if (self::workflowEnabled() || $getAllUnconditionally) {
- $permissions['create mailings'] = array(
+ $permissions['create mailings'] = [
ts('create mailings'),
- );
- $permissions['schedule mailings'] = array(
+ ];
+ $permissions['schedule mailings'] = [
ts('schedule mailings'),
- );
- $permissions['approve mailings'] = array(
+ ];
+ $permissions['approve mailings'] = [
ts('approve mailings'),
- );
+ ];
}
if (!$descriptions) {
@@ -241,7 +246,6 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
return $permissions;
}
-
/**
* @inheritDoc
* @return null
@@ -264,12 +268,20 @@ public function getUserDashboardObject() {
* @return array
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Mailings'),
'id' => 'mailing',
'url' => 'mailing',
'weight' => 45,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-envelope-o';
}
/**
@@ -277,10 +289,10 @@ public function registerTab() {
* @return array
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Mailings'),
'weight' => 20,
- );
+ ];
}
/**
diff --git a/CRM/Mailing/MailStore.php b/CRM/Mailing/MailStore.php
index 3bec5d9aec45..86b79c38b3f8 100644
--- a/CRM/Mailing/MailStore.php
+++ b/CRM/Mailing/MailStore.php
@@ -1,9 +1,9 @@
_debug) {
print "got to the end of the mailbox\n";
}
- return array();
+ return [];
}
- $mails = array();
+ $mails = [];
$parser = new ezcMailParser();
//set property text attachment as file CRM-5408
$parser->options->parseTextAttachmentsAsFiles = TRUE;
@@ -152,11 +155,11 @@ public function fetchNext($count = 1) {
public function maildir($name) {
$config = CRM_Core_Config::singleton();
$dir = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $name;
- foreach (array(
- 'cur',
- 'new',
- 'tmp',
- ) as $sub) {
+ foreach ([
+ 'cur',
+ 'new',
+ 'tmp',
+ ] as $sub) {
if (!file_exists($dir . DIRECTORY_SEPARATOR . $sub)) {
if ($this->_debug) {
print "creating $dir/$sub\n";
diff --git a/CRM/Mailing/MailStore/Imap.php b/CRM/Mailing/MailStore/Imap.php
index dc918f1d6df7..a805ee43a222 100644
--- a/CRM/Mailing/MailStore/Imap.php
+++ b/CRM/Mailing/MailStore/Imap.php
@@ -1,9 +1,9 @@
$ssl, 'uidReferencing' => TRUE);
+ $options = ['ssl' => $ssl, 'uidReferencing' => TRUE];
$this->_transport = new ezcMailImapTransport($host, NULL, $options);
$this->_transport->authenticate($username, $password);
$this->_transport->selectMailbox($folder);
- $this->_ignored = implode($this->_transport->getHierarchyDelimiter(), array($folder, 'CiviMail', 'ignored'));
- $this->_processed = implode($this->_transport->getHierarchyDelimiter(), array($folder, 'CiviMail', 'processed'));
+ $this->_ignored = implode($this->_transport->getHierarchyDelimiter(), [$folder, 'CiviMail', 'ignored']);
+ $this->_processed = implode($this->_transport->getHierarchyDelimiter(), [$folder, 'CiviMail', 'processed']);
$boxes = $this->_transport->listMailboxes();
if ($this->_debug) {
diff --git a/CRM/Mailing/MailStore/Localdir.php b/CRM/Mailing/MailStore/Localdir.php
index c00cf3adeaf9..8e9c66f1c813 100644
--- a/CRM/Mailing/MailStore/Localdir.php
+++ b/CRM/Mailing/MailStore/Localdir.php
@@ -1,9 +1,9 @@
_dir = $dir;
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
@@ -72,7 +72,7 @@ public function __construct($dir) {
* array of ezcMail objects
*/
public function fetchNext($count = 0) {
- $mails = array();
+ $mails = [];
$path = rtrim($this->_dir, DIRECTORY_SEPARATOR);
if ($this->_debug) {
@@ -95,7 +95,7 @@ public function fetchNext($count = 0) {
print "retrieving message $file\n";
}
- $set = new ezcMailFileSet(array($file));
+ $set = new ezcMailFileSet([$file]);
$parser = new ezcMailParser();
// set property text attachment as file CRM-5408
$parser->options->parseTextAttachmentsAsFiles = TRUE;
@@ -104,7 +104,7 @@ public function fetchNext($count = 0) {
if (!$mail) {
return CRM_Core_Error::createAPIError(ts('%1 could not be parsed',
- array(1 => $file)
+ [1 => $file]
));
}
$mails[$file] = $mail[0];
diff --git a/CRM/Mailing/MailStore/Maildir.php b/CRM/Mailing/MailStore/Maildir.php
index 7a1aeef4f4fa..90b371026ed4 100644
--- a/CRM/Mailing/MailStore/Maildir.php
+++ b/CRM/Mailing/MailStore/Maildir.php
@@ -1,9 +1,9 @@
_dir = $dir;
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
@@ -72,15 +72,15 @@ public function __construct($dir) {
* array of ezcMail objects
*/
public function fetchNext($count = 0) {
- $mails = array();
+ $mails = [];
$parser = new ezcMailParser();
// set property text attachment as file CRM-5408
$parser->options->parseTextAttachmentsAsFiles = TRUE;
- foreach (array(
- 'cur',
- 'new',
- ) as $subdir) {
+ foreach ([
+ 'cur',
+ 'new',
+ ] as $subdir) {
$dir = $this->_dir . DIRECTORY_SEPARATOR . $subdir;
foreach (scandir($dir) as $file) {
if ($file == '.' or $file == '..') {
@@ -94,7 +94,7 @@ public function fetchNext($count = 0) {
}
- $set = new ezcMailFileSet(array($path));
+ $set = new ezcMailFileSet([$path]);
$single = $parser->parseMail($set);
$mails[$path] = $single[0];
}
diff --git a/CRM/Mailing/MailStore/Mbox.php b/CRM/Mailing/MailStore/Mbox.php
index cda2dc234ea8..6ffadf4166e8 100644
--- a/CRM/Mailing/MailStore/Mbox.php
+++ b/CRM/Mailing/MailStore/Mbox.php
@@ -1,9 +1,9 @@
_leftToProcess = count($this->_transport->listMessages());
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
diff --git a/CRM/Mailing/MailStore/Pop3.php b/CRM/Mailing/MailStore/Pop3.php
index c0a8b98a1c40..c552c3e18c7b 100644
--- a/CRM/Mailing/MailStore/Pop3.php
+++ b/CRM/Mailing/MailStore/Pop3.php
@@ -1,9 +1,9 @@
$ssl);
+ $options = ['ssl' => $ssl];
$this->_transport = new ezcMailPop3Transport($host, NULL, $options);
$this->_transport->authenticate($username, $password);
- $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.ignored',
- date('Y'),
- date('m'),
- date('d'),
- )));
- $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, array(
- 'CiviMail.processed',
- date('Y'),
- date('m'),
- date('d'),
- )));
+ $this->_ignored = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.ignored',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
+ $this->_processed = $this->maildir(implode(DIRECTORY_SEPARATOR, [
+ 'CiviMail.processed',
+ date('Y'),
+ date('m'),
+ date('d'),
+ ]));
}
/**
diff --git a/CRM/Mailing/Page/AJAX.php b/CRM/Mailing/Page/AJAX.php
index 0b493a6c08b4..c2586c25071f 100644
--- a/CRM/Mailing/Page/AJAX.php
+++ b/CRM/Mailing/Page/AJAX.php
@@ -1,9 +1,9 @@
selectAdd();
$messageTemplate->selectAdd('msg_text, msg_html, msg_subject, pdf_format_id');
$messageTemplate->find(TRUE);
- $messages = array(
+ $messages = [
'subject' => $messageTemplate->msg_subject,
'msg_text' => $messageTemplate->msg_text,
'msg_html' => $messageTemplate->msg_html,
'pdf_format_id' => $messageTemplate->pdf_format_id,
- );
+ ];
$documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $templateId);
foreach ((array) $documentInfo as $info) {
@@ -67,7 +67,7 @@ public static function template() {
*/
public static function getContactMailings() {
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
- $params += CRM_Core_Page_AJAX::validateParams(array('contact_id' => 'Integer'));
+ $params += CRM_Core_Page_AJAX::validateParams(['contact_id' => 'Integer']);
// get the contact mailings
$mailings = CRM_Mailing_BAO_Mailing::getContactMailingSelector($params);
diff --git a/CRM/Mailing/Page/Browse.php b/CRM/Mailing/Page/Browse.php
index d9b59a46510c..65bf2de542df 100644
--- a/CRM/Mailing/Page/Browse.php
+++ b/CRM/Mailing/Page/Browse.php
@@ -1,9 +1,9 @@
_unscheduled = $this->_archived = $archiveLinks = FALSE;
$this->_mailingId = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
$this->_sms = CRM_Utils_Request::retrieve('sms', 'Positive', $this);
+
+ if ($this->_sms) {
+ // if this is an SMS page, check that the user has permission to browse SMS
+ if (!CRM_Core_Permission::check('send SMS')) {
+ CRM_Core_Error::fatal(ts('You do not have permission to send SMS'));
+ }
+ }
+ else {
+ // If this is not an SMS page, check that the user has an appropriate
+ // permission (specific permissions have been copied from
+ // CRM/Mailing/xml/Menu/Mailing.xml)
+ if (!CRM_Core_Permission::check([['access CiviMail', 'approve mailings', 'create mailings', 'schedule mailings']])) {
+ CRM_Core_Error::fatal(ts('You do not have permission to view this page.'));
+ }
+ }
+
$this->assign('sms', $this->_sms);
// check that the user has permission to access mailing id
CRM_Mailing_BAO_Mailing::checkPermission($this->_mailingId);
@@ -165,6 +181,7 @@ public function run() {
if ($this->_action & CRM_Core_Action::DISABLE) {
if (CRM_Utils_Request::retrieve('confirmed', 'Boolean', $this)) {
CRM_Mailing_BAO_MailingJob::cancel($this->_mailingId);
+ CRM_Core_Session::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
CRM_Utils_System::redirect($context);
}
else {
@@ -176,6 +193,22 @@ public function run() {
$controller->run();
}
}
+ elseif ($this->_action & CRM_Core_Action::CLOSE) {
+ if (!CRM_Core_Permission::checkActionPermission('CiviMail', CRM_Core_Action::CLOSE)) {
+ CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ }
+ CRM_Mailing_BAO_MailingJob::pause($this->_mailingId);
+ CRM_Core_Session::setStatus(ts('The mailing has been paused. Active message deliveries may continue for a few minutes, but CiviMail will not begin delivery of any more batches.'), ts('Paused'), 'success');
+ CRM_Utils_System::redirect($context);
+ }
+ elseif ($this->_action & CRM_Core_Action::REOPEN) {
+ if (!CRM_Core_Permission::checkActionPermission('CiviMail', CRM_Core_Action::CLOSE)) {
+ CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ }
+ CRM_Mailing_BAO_MailingJob::resume($this->_mailingId);
+ CRM_Core_Session::setStatus(ts('The mailing has been resumed.'), ts('Resumed'), 'success');
+ CRM_Utils_System::redirect($context);
+ }
elseif ($this->_action & CRM_Core_Action::DELETE) {
if (CRM_Utils_Request::retrieve('confirmed', 'Boolean', $this)) {
@@ -304,18 +337,18 @@ public function search() {
* @return string
*/
public function whereClause(&$params, $sortBy = TRUE) {
- $values = array();
+ $values = [];
- $clauses = array();
+ $clauses = [];
$title = $this->get('mailing_name');
// echo " name=$title ";
if ($title) {
$clauses[] = 'name LIKE %1';
if (strpos($title, '%') !== FALSE) {
- $params[1] = array($title, 'String', FALSE);
+ $params[1] = [$title, 'String', FALSE];
}
else {
- $params[1] = array($title, 'String', TRUE);
+ $params[1] = [$title, 'String', TRUE];
}
}
@@ -328,7 +361,7 @@ public function whereClause(&$params, $sortBy = TRUE) {
$campainIds = $this->get('campaign_id');
if (!CRM_Utils_System::isNull($campainIds)) {
if (!is_array($campainIds)) {
- $campaignIds = array($campaignIds);
+ $campaignIds = [$campaignIds];
}
$clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campainIds)) . ' ) )';
}
diff --git a/CRM/Mailing/Page/Common.php b/CRM/Mailing/Page/Common.php
index 51fa8b2661f1..f420a0698ce3 100644
--- a/CRM/Mailing/Page/Common.php
+++ b/CRM/Mailing/Page/Common.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=update&id=%%id%%',
'title' => ts('Edit Mailing Component'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Mailing Component'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Mailing Component'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
diff --git a/CRM/Mailing/Page/Confirm.php b/CRM/Mailing/Page/Confirm.php
index b58fbc9028de..b126dac4281f 100644
--- a/CRM/Mailing/Page/Confirm.php
+++ b/CRM/Mailing/Page/Confirm.php
@@ -1,9 +1,9 @@
getVars($options, "CRM_Mailing_Controller_Send_$qfKey");
// get the options if control come from search context, CRM-3711
@@ -74,7 +74,7 @@ public function run() {
// get details of contact with token value including Custom Field Token Values.CRM-3734
$returnProperties = $mailing->getReturnProperties();
- $params = array('contact_id' => $session->get('userID'));
+ $params = ['contact_id' => $session->get('userID')];
$details = CRM_Utils_Token::getTokenDetails($params,
$returnProperties,
diff --git a/CRM/Mailing/Page/Report.php b/CRM/Mailing/Page/Report.php
index 8c01fed87b60..628672a01ede 100644
--- a/CRM/Mailing/Page/Report.php
+++ b/CRM/Mailing/Page/Report.php
@@ -1,9 +1,9 @@
assign('report', $report);
CRM_Utils_System::setTitle(ts('CiviMail Report: %1',
- array(1 => $report['mailing']['name'])
+ [1 => $report['mailing']['name']]
));
$this->assign('public_url', CRM_Mailing_BAO_Mailing::getPublicViewUrl($this->_mailing_id));
diff --git a/CRM/Mailing/Page/Resubscribe.php b/CRM/Mailing/Page/Resubscribe.php
index d950dd84f12c..8df64a00b9a6 100644
--- a/CRM/Mailing/Page/Resubscribe.php
+++ b/CRM/Mailing/Page/Resubscribe.php
@@ -1,9 +1,9 @@
$displayName)));
+ CRM_Utils_System::setTitle(ts('Mailings sent to %1', [1 => $displayName]));
}
/**
diff --git a/CRM/Mailing/Page/Unsubscribe.php b/CRM/Mailing/Page/Unsubscribe.php
index 61be1a0672ac..34da7195d930 100644
--- a/CRM/Mailing/Page/Unsubscribe.php
+++ b/CRM/Mailing/Page/Unsubscribe.php
@@ -1,9 +1,9 @@
_mailing);
-
- // get and format attachments
- $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing',
- $this->_mailing->id
- );
-
- // get contact detail and compose if contact id exists
- $returnProperties = $this->_mailing->getReturnProperties();
- if (isset($this->_contactID)) {
- // get details of contact with token value including Custom Field Token Values.CRM-3734
- $params = array('contact_id' => $this->_contactID);
- $details = CRM_Utils_Token::getTokenDetails($params,
- $returnProperties,
- FALSE, TRUE, NULL,
- $this->_mailing->getFlattenedTokens(),
- get_class($this)
- );
- $details = $details[0][$this->_contactID];
- $contactId = $this->_contactID;
- }
- else {
- // get tokens that are not contact specific resolved
- $params = array('contact_id' => 0);
- $details = CRM_Utils_Token::getAnonymousTokenDetails($params,
- $returnProperties,
- TRUE, TRUE, NULL,
- $this->_mailing->getFlattenedTokens(),
- get_class($this)
- );
-
- $details = CRM_Utils_Array::value(0, $details[0]);
- $contactId = 0;
- }
- $mime = $this->_mailing->compose(NULL, NULL, NULL, $contactId,
- $this->_mailing->from_email,
- $this->_mailing->from_email,
- TRUE, $details, $attachments
- );
+ $contactId = isset($this->_contactID) ? $this->_contactID : 0;
+
+ $result = civicrm_api3('Mailing', 'preview', [
+ 'id' => $this->_mailingID,
+ 'contact_id' => $contactId,
+ ]);
+ $mailing = \CRM_Utils_Array::value('values', $result);
$title = NULL;
- if (isset($this->_mailing->body_html) && empty($_GET['text'])) {
+ if (isset($mailing['body_html']) && empty($_GET['text'])) {
$header = 'text/html; charset=utf-8';
- $content = $mime->getHTMLBody();
+ $content = $mailing['body_html'];
if (strpos($content, '') === FALSE && strpos($content, '') === FALSE) {
- $title = '' . $this->_mailing->subject . '';
+ $title = '' . $mailing['subject'] . '';
}
}
else {
$header = 'text/plain; charset=utf-8';
- $content = $mime->getTXTBody();
+ $content = $mailing['body_text'];
}
- CRM_Utils_System::setTitle($this->_mailing->subject);
+ CRM_Utils_System::setTitle($mailing['subject']);
if (CRM_Utils_Array::value('snippet', $_GET) === 'json') {
CRM_Core_Page_AJAX::returnJsonResponse($content);
diff --git a/CRM/Mailing/PseudoConstant.php b/CRM/Mailing/PseudoConstant.php
index 9a4c25f44b20..c2e43ff7a920 100644
--- a/CRM/Mailing/PseudoConstant.php
+++ b/CRM/Mailing/PseudoConstant.php
@@ -1,9 +1,9 @@
ts('Draft'),
'Testing' => ts('Testing'),
'Final' => ts('Final'),
- );
+ ];
}
return self::$abStatus;
}
@@ -103,11 +104,11 @@ public static function abStatus() {
*/
public static function abTestCriteria() {
if (!is_array(self::$abTestCriteria)) {
- self::$abTestCriteria = array(
+ self::$abTestCriteria = [
'subject' => ts('Test different "Subject" lines'),
'from' => ts('Test different "From" lines'),
'full_email' => ts('Test entirely different emails'),
- );
+ ];
}
return self::$abTestCriteria;
}
@@ -117,11 +118,11 @@ public static function abTestCriteria() {
*/
public static function abWinnerCriteria() {
if (!is_array(self::$abWinnerCriteria)) {
- self::$abWinnerCriteria = array(
+ self::$abWinnerCriteria = [
'open' => ts('Open'),
'unique_click' => ts('Total Unique Clicks'),
'link_click' => ts('Total Clicks on a particular link'),
- );
+ ];
}
return self::$abWinnerCriteria;
}
@@ -131,11 +132,11 @@ public static function abWinnerCriteria() {
*/
public static function mailingTypes() {
if (!is_array(self::$mailingTypes)) {
- self::$mailingTypes = array(
+ self::$mailingTypes = [
'standalone' => ts('Standalone'),
'experiment' => ts('Experimental'),
'winner' => ts('Winner'),
- );
+ ];
}
return self::$mailingTypes;
}
@@ -154,17 +155,17 @@ public static function &component($type = NULL) {
if (!self::$component || !array_key_exists($name, self::$component)) {
if (!self::$component) {
- self::$component = array();
+ self::$component = [];
}
if (!$type) {
self::$component[$name] = NULL;
- CRM_Core_PseudoConstant::populate(self::$component[$name], 'CRM_Mailing_DAO_Component');
+ CRM_Core_PseudoConstant::populate(self::$component[$name], 'CRM_Mailing_BAO_MailingComponent');
}
else {
// we need to add an additional filter for $type
- self::$component[$name] = array();
+ self::$component[$name] = [];
- $object = new CRM_Mailing_DAO_Component();
+ $object = new CRM_Mailing_BAO_MailingComponent();
$object->component_type = $type;
$object->selectAdd();
$object->selectAdd("id, name");
@@ -200,7 +201,7 @@ public static function &defaultComponent($type, $undefined = NULL) {
$dao = CRM_Core_DAO::executeQuery($queryDefaultComponents);
- self::$defaultComponent = array();
+ self::$defaultComponent = [];
while ($dao->fetch()) {
self::$defaultComponent[$dao->component_type] = $dao->id;
}
@@ -258,28 +259,28 @@ public static function &completed($mode = NULL) {
public static function &yesNoOptions($field) {
static $options;
if (!$options) {
- $options = array(
- 'bounce' => array(
+ $options = [
+ 'bounce' => [
'N' => ts('Successful '),
'Y' => ts('Bounced '),
- ),
- 'delivered' => array(
+ ],
+ 'delivered' => [
'Y' => ts('Successful '),
'N' => ts('Bounced '),
- ),
- 'open' => array(
+ ],
+ 'open' => [
'Y' => ts('Opened '),
'N' => ts('Unopened/Hidden '),
- ),
- 'click' => array(
+ ],
+ 'click' => [
'Y' => ts('Clicked '),
'N' => ts('Not Clicked '),
- ),
- 'reply' => array(
+ ],
+ 'reply' => [
'Y' => ts('Replied '),
'N' => ts('No Reply '),
- ),
- );
+ ],
+ ];
}
return $options[$field];
}
diff --git a/CRM/Mailing/Selector/Browse.php b/CRM/Mailing/Selector/Browse.php
index 40a282090d53..1f4aa41c55cb 100644
--- a/CRM/Mailing/Selector/Browse.php
+++ b/CRM/Mailing/Selector/Browse.php
@@ -1,9 +1,9 @@
_parent->get('sms')) ? ts('SMS Name') : ts('Mailing Name');
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => $nameHeaderLabel,
'sort' => 'name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
if (CRM_Core_I18n::isMultilingual()) {
self::$_columnHeaders = array_merge(
self::$_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Language'),
'sort' => 'language',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- )
+ ],
+ ]
);
}
self::$_columnHeaders = array_merge(
self::$_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Status'),
'sort' => 'status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Created By'),
'sort' => 'created_by',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Created Date'),
'sort' => 'created_date',
'direction' => $unscheduledOrder,
- ),
- array(
+ ],
+ [
'name' => ts('Sent By'),
'sort' => 'scheduled_by',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Scheduled'),
'sort' => 'scheduled_date',
'direction' => $scheduledOrder,
- ),
- array(
+ ],
+ [
'name' => ts('Started'),
'sort' => 'start_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Completed'),
'sort' => 'end_date',
'direction' => $completedOrder,
- ),
- )
+ ],
+ ]
);
if (CRM_Campaign_BAO_Campaign::isCampaignEnable()) {
- self::$_columnHeaders[] = array(
+ self::$_columnHeaders[] = [
'name' => ts('Campaign'),
'sort' => 'campaign_id',
'direction' => CRM_Utils_Sort::DONTCARE,
- );
+ ];
}
if ($output != CRM_Core_Selector_Controller::EXPORT) {
- self::$_columnHeaders[] = array('name' => ts('Action'));
+ self::$_columnHeaders[] = ['name' => ts('Action')];
}
}
@@ -209,7 +209,7 @@ public function getTotalCount($action) {
$mailingACL = CRM_Mailing_BAO_Mailing::mailingACL();
// get the where clause.
- $params = array();
+ $params = [];
$whereClause = "$mailingACL AND " . $this->whereClause($params);
// CRM-11919 added addition ON clauses to mailing_job to match getRows
@@ -248,53 +248,65 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$deleteExtra = ts('Are you sure you want to delete this mailing?');
$archiveExtra = ts('Are you sure you want to archive this mailing?');
- $actionLinks = array(
- CRM_Core_Action::ENABLE => array(
+ $actionLinks = [
+ CRM_Core_Action::ENABLE => [
'name' => ts('Approve/Reject'),
'url' => 'civicrm/mailing/approve',
'qs' => 'mid=%%mid%%&reset=1',
'title' => ts('Approve/Reject Mailing'),
- ),
- CRM_Core_Action::VIEW => array(
+ ],
+ CRM_Core_Action::VIEW => [
'name' => ts('Report'),
'url' => 'civicrm/mailing/report',
'qs' => 'mid=%%mid%%&reset=1',
'title' => ts('View Mailing Report'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Re-Use'),
'url' => 'civicrm/mailing/send',
'qs' => 'mid=%%mid%%&reset=1',
'title' => ts('Re-Send Mailing'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Cancel'),
'url' => 'civicrm/mailing/browse',
'qs' => 'action=disable&mid=%%mid%%&reset=1',
'extra' => 'onclick="if (confirm(\'' . $cancelExtra . '\')) this.href+=\'&confirmed=1\'; else return false;"',
'title' => ts('Cancel Mailing'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Continue'),
'url' => 'civicrm/mailing/send',
'qs' => 'mid=%%mid%%&continue=true&reset=1',
'title' => ts('Continue Mailing'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/mailing/browse',
'qs' => 'action=delete&mid=%%mid%%&reset=1',
'extra' => 'onclick="if (confirm(\'' . $deleteExtra . '\')) this.href+=\'&confirmed=1\'; else return false;"',
'title' => ts('Delete Mailing'),
- ),
- CRM_Core_Action::RENEW => array(
+ ],
+ CRM_Core_Action::RENEW => [
'name' => ts('Archive'),
'url' => 'civicrm/mailing/browse/archived',
'qs' => 'action=renew&mid=%%mid%%&reset=1',
'extra' => 'onclick="if (confirm(\'' . $archiveExtra . '\')) this.href+=\'&confirmed=1\'; else return false;"',
'title' => ts('Archive Mailing'),
- ),
- );
+ ],
+ CRM_Core_Action::REOPEN => [
+ 'name' => ts('Resume'),
+ 'url' => 'civicrm/mailing/browse',
+ 'qs' => 'action=reopen&mid=%%mid%%&reset=1',
+ 'title' => ts('Resume mailing'),
+ ],
+ CRM_Core_Action::CLOSE => [
+ 'name' => ts('Pause'),
+ 'url' => 'civicrm/mailing/browse',
+ 'qs' => 'action=close&mid=%%mid%%&reset=1',
+ 'title' => ts('Pause mailing'),
+ ],
+ ];
}
$allAccess = TRUE;
@@ -321,7 +333,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
$mailing = new CRM_Mailing_BAO_Mailing();
- $params = array();
+ $params = [];
$whereClause = ' AND ' . $this->whereClause($params);
@@ -342,7 +354,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
if ($output != CRM_Core_Selector_Controller::EXPORT) {
// create the appropriate $op to use for hook_civicrm_links
- $pageTypes = array('view', 'mailing', 'browse');
+ $pageTypes = ['view', 'mailing', 'browse'];
if ($this->_parent->_unscheduled) {
$pageTypes[] = 'unscheduled';
}
@@ -379,16 +391,22 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$actionMask = CRM_Core_Action::PREVIEW;
}
}
- if (in_array($row['status'], array(
+ if (in_array($row['status'], [
'Scheduled',
'Running',
'Paused',
- ))) {
+ ])) {
if ($allAccess ||
($showApprovalLinks && $showCreateLinks && $showScheduleLinks)
) {
$actionMask |= CRM_Core_Action::DISABLE;
+ if ($row['status'] == "Paused") {
+ $actionMask |= CRM_Core_Action::REOPEN;
+ }
+ else {
+ $actionMask |= CRM_Core_Action::CLOSE;
+ }
}
if ($row['status'] == 'Scheduled' &&
empty($row['approval_status_id'])
@@ -399,7 +417,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
}
- if (in_array($row['status'], array('Complete', 'Canceled')) &&
+ if (in_array($row['status'], ['Complete', 'Canceled']) &&
!$row['archived']
) {
if ($allAccess || $showCreateLinks) {
@@ -423,19 +441,20 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$validLinks = $actionLinks;
if (($mailingUrl = CRM_Mailing_BAO_Mailing::getPublicViewUrl($row['id'])) != FALSE) {
- $validLinks[] = array(
+ $validLinks[CRM_Core_Action::BROWSE] = [
'name' => ts('Public View'),
'url' => 'civicrm/mailing/view',
'qs' => 'id=%%mid%%&reset=1',
'title' => ts('Public View'),
'fe' => TRUE,
- );
+ ];
+ $actionMask |= CRM_Core_Action::BROWSE;
}
$rows[$key]['action'] = CRM_Core_Action::formLink(
$validLinks,
$actionMask,
- array('mid' => $row['id']),
+ ['mid' => $row['id']],
"more",
FALSE,
$opString,
@@ -484,21 +503,21 @@ public function setParent($parent) {
* @return int|string
*/
public function whereClause(&$params, $sortBy = TRUE) {
- $values = $clauses = array();
+ $values = $clauses = [];
$isFormSubmitted = $this->_parent->get('hidden_find_mailings');
$title = $this->_parent->get('mailing_name');
if ($title) {
$clauses[] = 'name LIKE %1';
if (strpos($title, '%') !== FALSE) {
- $params[1] = array($title, 'String', FALSE);
+ $params[1] = [$title, 'String', FALSE];
}
else {
- $params[1] = array($title, 'String', TRUE);
+ $params[1] = [$title, 'String', TRUE];
}
}
- $dateClause1 = $dateClause2 = array();
+ $dateClause1 = $dateClause2 = [];
$from = $this->_parent->get('mailing_from');
if (!CRM_Utils_System::isNull($from)) {
if ($this->_parent->get('unscheduled')) {
@@ -508,7 +527,7 @@ public function whereClause(&$params, $sortBy = TRUE) {
$dateClause1[] = 'civicrm_mailing_job.start_date >= %2';
$dateClause2[] = 'civicrm_mailing_job.scheduled_date >= %2';
}
- $params[2] = array($from, 'String');
+ $params[2] = [$from, 'String'];
}
$to = $this->_parent->get('mailing_to');
@@ -520,10 +539,10 @@ public function whereClause(&$params, $sortBy = TRUE) {
$dateClause1[] = 'civicrm_mailing_job.start_date <= %3';
$dateClause2[] = 'civicrm_mailing_job.scheduled_date <= %3';
}
- $params[3] = array($to, 'String');
+ $params[3] = [$to, 'String'];
}
- $dateClauses = array();
+ $dateClauses = [];
if (!empty($dateClause1)) {
$dateClauses[] = implode(' AND ', $dateClause1);
}
@@ -550,7 +569,7 @@ public function whereClause(&$params, $sortBy = TRUE) {
if (!$isFormSubmitted && $this->_parent->get('scheduled')) {
// mimic default behavior for scheduled screen
$isArchived = 0;
- $mailingStatus = array('Scheduled' => 1, 'Complete' => 1, 'Running' => 1, 'Canceled' => 1);
+ $mailingStatus = ['Scheduled' => 1, 'Complete' => 1, 'Running' => 1, 'Paused' => 1, 'Canceled' => 1];
}
if (!$isFormSubmitted && $this->_parent->get('archived')) {
// mimic default behavior for archived screen
@@ -561,7 +580,7 @@ public function whereClause(&$params, $sortBy = TRUE) {
$isDraft = 1;
}
- $statusClauses = array();
+ $statusClauses = [];
if ($isDraft) {
$statusClauses[] = "civicrm_mailing.scheduled_id IS NULL";
}
@@ -601,26 +620,26 @@ public function whereClause(&$params, $sortBy = TRUE) {
$createOrSentBy = $this->_parent->get('sort_name');
if (!CRM_Utils_System::isNull($createOrSentBy)) {
$clauses[] = '(createdContact.sort_name LIKE %4 OR scheduledContact.sort_name LIKE %4)';
- $params[4] = array('%' . $createOrSentBy . '%', 'String');
+ $params[4] = ['%' . $createOrSentBy . '%', 'String'];
}
$createdId = $this->_parent->get('createdId');
if ($createdId) {
$clauses[] = "(created_id = {$createdId})";
- $params[5] = array($createdId, 'Integer');
+ $params[5] = [$createdId, 'Integer'];
}
$campainIds = $this->_parent->get('campaign_id');
if (!CRM_Utils_System::isNull($campainIds)) {
if (!is_array($campainIds)) {
- $campaignIds = array($campaignIds);
+ $campaignIds = [$campaignIds];
}
$clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campainIds)) . ' ) )';
}
if ($language = $this->_parent->get('language')) {
$clauses[] = "civicrm_mailing.language = %6";
- $params[6] = array($language, 'String');
+ $params[6] = [$language, 'String'];
}
if (empty($clauses)) {
@@ -632,7 +651,7 @@ public function whereClause(&$params, $sortBy = TRUE) {
public function pagerAtoZ() {
- $params = array();
+ $params = [];
$whereClause = $this->whereClause($params, FALSE);
$query = "
diff --git a/CRM/Mailing/Selector/Event.php b/CRM/Mailing/Selector/Event.php
index c7db96ca4c0e..618cbc3e4f19 100644
--- a/CRM/Mailing/Selector/Event.php
+++ b/CRM/Mailing/Selector/Event.php
@@ -1,9 +1,9 @@
$this->eventToTitle()));
+ $params['status'] = ts('%1 %%StatusMessage%%', [1 => $this->eventToTitle()]);
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
@@ -146,18 +151,18 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
$job = CRM_Mailing_BAO_MailingJob::getTableName();
if (!isset($this->_columnHeaders)) {
- $this->_columnHeaders = array(
- 'sort_name' => array(
+ $this->_columnHeaders = [
+ 'sort_name' => [
'name' => ts('Contact'),
'sort' => $contact . '.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
- ),
- 'email' => array(
+ ],
+ 'email' => [
'name' => ts('Email Address'),
'sort' => $email . '.email',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
switch ($this->_event_type) {
case 'queue':
@@ -165,13 +170,13 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
break;
case 'delivered':
- $this->_columnHeaders = array(
- 'contact_id' => array(
+ $this->_columnHeaders = [
+ 'contact_id' => [
'name' => ts('Internal Contact ID'),
'sort' => $contact . '.id',
'direction' => CRM_Utils_Sort::ASCENDING,
- ),
- ) + $this->_columnHeaders;
+ ],
+ ] + $this->_columnHeaders;
$dateSort = CRM_Mailing_Event_BAO_Delivered::getTableName() . '.time_stamp';
break;
@@ -182,14 +187,14 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
case 'bounce':
$dateSort = CRM_Mailing_Event_BAO_Bounce::getTableName() . '.time_stamp';
$this->_columnHeaders = array_merge($this->_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Bounce Type'),
- ),
- array(
+ ],
+ [
'name' => ts('Bounce Reason'),
- ),
- )
+ ],
+ ]
);
break;
@@ -197,11 +202,11 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
$dateSort = CRM_Mailing_Event_BAO_Forward::getTableName() . '.time_stamp';
$this->_columnHeaders = array_merge($this->_columnHeaders,
- array(
- array(
+ [
+ [
'name' => ts('Forwarded Email'),
- ),
- )
+ ],
+ ]
);
break;
@@ -211,42 +216,42 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
case 'unsubscribe':
$dateSort = CRM_Mailing_Event_BAO_Unsubscribe::getTableName() . '.time_stamp';
- $this->_columnHeaders = array_merge($this->_columnHeaders, array(
- array(
+ $this->_columnHeaders = array_merge($this->_columnHeaders, [
+ [
'name' => ts('Unsubscribe'),
- ),
- ));
+ ],
+ ]);
break;
case 'optout':
$dateSort = CRM_Mailing_Event_BAO_Unsubscribe::getTableName() . '.time_stamp';
- $this->_columnHeaders = array_merge($this->_columnHeaders, array(
- array(
+ $this->_columnHeaders = array_merge($this->_columnHeaders, [
+ [
'name' => ts('Opt-Out'),
- ),
- ));
+ ],
+ ]);
break;
case 'click':
$dateSort = CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName() . '.time_stamp';
- $this->_columnHeaders = array_merge($this->_columnHeaders, array(
- array(
+ $this->_columnHeaders = array_merge($this->_columnHeaders, [
+ [
'name' => ts('URL'),
- ),
- ));
+ ],
+ ]);
break;
default:
return 0;
}
- $this->_columnHeaders = array_merge($this->_columnHeaders, array(
- 'date' => array(
+ $this->_columnHeaders = array_merge($this->_columnHeaders, [
+ 'date' => [
'name' => ts('Date'),
'sort' => $dateSort,
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- ));
+ ],
+ ]);
}
return $this->_columnHeaders;
}
@@ -448,7 +453,7 @@ public function eventToTitle() {
static $events = NULL;
if (empty($events)) {
- $events = array(
+ $events = [
'queue' => ts('Intended Recipients'),
'delivered' => ts('Successful Deliveries'),
'bounce' => ts('Bounces'),
@@ -458,7 +463,7 @@ public function eventToTitle() {
'optout' => ts('Opt-out Requests'),
'click' => $this->_is_distinct ? ts('Unique Click-throughs') : ts('Click-throughs'),
'opened' => $this->_is_distinct ? ts('Unique Tracked Opens') : ts('Total Tracked Opens'),
- );
+ ];
}
return $events[$this->_event_type];
}
diff --git a/CRM/Mailing/Selector/Search.php b/CRM/Mailing/Selector/Search.php
index 8558f17c5f00..65ad8038ce66 100644
--- a/CRM/Mailing/Selector/Search.php
+++ b/CRM/Mailing/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view',
'qs' => "reset=1&cid=%%cid%%{$searchContext}{$extraParams}",
'title' => ts('View Contact Details'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/add',
'qs' => "reset=1&action=update&cid=%%cid%%{$searchContext}{$extraParams}",
'title' => ts('Edit Contact Details'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/delete',
'qs' => "reset=1&delete=1&cid=%%cid%%{$searchContext}{$extraParams}",
'title' => ts('Delete Contact'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -279,8 +279,8 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
- $permissions = array(CRM_Core_Permission::getPermission());
+ $rows = [];
+ $permissions = [CRM_Core_Permission::getPermission()];
if (CRM_Core_Permission::check('delete contacts')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
@@ -288,7 +288,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$qfKey = $this->_key;
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (property_exists($result, $property)) {
@@ -298,10 +298,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->mailing_recipients_id;
- $actions = array(
+ $actions = [
'cid' => $result->contact_id,
'cxt' => $this->_context,
- );
+ ];
$row['action'] = CRM_Core_Action::formLink(
self::links($qfKey, $this->_context),
@@ -341,46 +341,54 @@ public function getQILL() {
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
+
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array('desc' => ts('Contact Type')),
- array(
+ $isMultiLingual = CRM_Core_I18n::isMultiLingual();
+ $headers = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Email'),
'sort' => 'email',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Mailing Name'),
'sort' => 'mailing_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ ];
+
+ // Check to see if languages column should be displayed.
+ if ($isMultiLingual) {
+ $headers[] = [
'name' => ts('Language'),
'sort' => 'language',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ];
+ }
+ self::$_columnHeaders = array_merge($headers, [
+ [
'name' => ts('Mailing Subject'),
'sort' => 'mailing_subject',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Mailing Status'),
'sort' => 'mailing_job_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Completed Date'),
'sort' => 'mailing_job_end_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ]);
}
return self::$_columnHeaders;
}
@@ -389,7 +397,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Mailing/Task.php b/CRM/Mailing/Task.php
index 6bdec4b22a42..32a4b0ff74ed 100644
--- a/CRM/Mailing/Task.php
+++ b/CRM/Mailing/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_PRINT => [
'title' => ts('Print Mailing Recipients'),
'class' => 'CRM_Mailing_Form_Task_Print',
'result' => FALSE,
- ),
- );
+ ],
+ ];
- CRM_Utils_Hook::searchTasks('mailing', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles
- * on mailing recipients.
- *
- * @return array
- * the set of task titles.
- */
- public static function &taskTitles() {
- return array();
- }
-
/**
* Show tasks selectively based on the permission level
* of the user.
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $task = array();
- return $task;
+ public static function permissionedTaskTitles($permission, $params = []) {
+ $tasks = [];
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
+ return $tasks;
}
/**
@@ -113,12 +93,13 @@ public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
- $value = 1;
+ $value = self::TASK_PRINT;
}
- return array(
+
+ return [
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
- );
+ ];
}
}
diff --git a/CRM/Mailing/Tokens.php b/CRM/Mailing/Tokens.php
index 53271bc3ef62..efde6376b2e2 100644
--- a/CRM/Mailing/Tokens.php
+++ b/CRM/Mailing/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -40,7 +40,7 @@ class CRM_Mailing_Tokens extends \Civi\Token\AbstractTokenSubscriber {
* Class constructor.
*/
public function __construct() {
- parent::__construct('mailing', array(
+ parent::__construct('mailing', [
'id' => ts('Mailing ID'),
'name' => ts('Mailing Name'),
'group' => ts('Mailing Group(s)'),
@@ -54,14 +54,15 @@ public function __construct() {
'approveUrl' => ts('Mailing Approval URL'),
'creator' => ts('Mailing Creator (Name)'),
'creatorEmail' => ts('Mailing Creator (Email)'),
- ));
+ ]);
}
/**
* @inheritDoc
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
- return !empty($processor->context['mailingId']) || !empty($processor->context['mailing']);
+ return !empty($processor->context['mailingId']) || !empty($processor->context['mailing'])
+ || in_array('mailingId', $processor->context['schema']) || in_array('mailing', $processor->context['schema']);
}
/**
@@ -78,9 +79,9 @@ public function prefetch(\Civi\Token\Event\TokenValueEvent $e) {
? $processor->context['mailing']
: CRM_Mailing_BAO_Mailing::findById($processor->context['mailingId']);
- return array(
+ return [
'mailing' => $mailing,
- );
+ ];
}
/**
diff --git a/CRM/Mailing/xml/Menu/Mailing.xml b/CRM/Mailing/xml/Menu/Mailing.xml
index 33b9e501ea8c..639406b8af87 100644
--- a/CRM/Mailing/xml/Menu/Mailing.xml
+++ b/CRM/Mailing/xml/Menu/Mailing.xml
@@ -5,7 +5,7 @@
civicrm/mailingCiviMailCRM_Mailing_Page_Browse
- access CiviMail;create mailings
+ access CiviMail;create mailings;send SMS1600CiviMail
@@ -71,7 +71,7 @@
Find Mailingsscheduled=trueCRM_Mailing_Page_Browse
- access CiviMail;approve mailings;create mailings;schedule mailings
+ access CiviMail;approve mailings;create mailings;schedule mailings;send SMS1620
diff --git a/CRM/Member/ActionMapping.php b/CRM/Member/ActionMapping.php
index 9645ebcd0612..ee9c1b817076 100644
--- a/CRM/Member/ActionMapping.php
+++ b/CRM/Member/ActionMapping.php
@@ -1,9 +1,9 @@
register(CRM_Member_ActionMapping::create(array(
+ $registrations->register(CRM_Member_ActionMapping::create([
'id' => CRM_Member_ActionMapping::MEMBERSHIP_TYPE_MAPPING_ID,
'entity' => 'civicrm_membership',
'entity_label' => ts('Membership'),
@@ -58,9 +57,21 @@ public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\Mappi
'entity_value_label' => ts('Membership Type'),
'entity_status' => 'auto_renew_options',
'entity_status_label' => ts('Auto Renew Options'),
- 'entity_date_start' => 'membership_join_date',
- 'entity_date_end' => 'membership_end_date',
- )));
+ ]));
+ }
+
+ /**
+ * Get a list of available date fields.
+ *
+ * @return array
+ * Array(string $fieldName => string $fieldLabel).
+ */
+ public function getDateFields() {
+ return [
+ 'join_date' => ts('Membership Join Date'),
+ 'start_date' => ts('Membership Start Date'),
+ 'end_date' => ts('Membership End Date'),
+ ];
}
/**
@@ -85,8 +96,16 @@ public function createQuery($schedule, $phase, $defaultParams) {
$query['casContactIdField'] = 'e.contact_id';
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
+
+ // Leaving this in case of legacy databases
$query['casDateField'] = str_replace('membership_', 'e.', $schedule->start_action_date);
+ // Options currently are just 'join_date', 'start_date', and 'end_date':
+ // they need an alias
+ if (strpos($query['casDateField'], 'e.') !== 0) {
+ $query['casDateField'] = 'e.' . $query['casDateField'];
+ }
+
// FIXME: Numbers should be constants.
if (in_array(2, $selectedStatuses)) {
//auto-renew memberships
@@ -101,11 +120,28 @@ public function createQuery($schedule, $phase, $defaultParams) {
->param('memberTypeValues', $selectedValues);
}
else {
+ // FIXME: The membership type is never null, so nobody will ever get a
+ // reminder if no membership types are selected. Either this should be a
+ // validation on the reminder form or all types should get a reminder if
+ // no types are selected.
$query->where("e.membership_type_id IS NULL");
}
+ // FIXME: This makes a lot of sense for renewal reminders, but a user
+ // scheduling another kind of reminder might not expect members to be
+ // excluded if they have status overrides. Ideally there would be some kind
+ // of setting per reminder.
$query->where("( e.is_override IS NULL OR e.is_override = 0 )");
+
+ // FIXME: Similarly to overrides, excluding contacts who can't edit the
+ // primary member makes sense in the context of renewals (see CRM-11342) but
+ // would be a surprise for other use cases.
$query->merge($this->prepareMembershipPermissionsFilter());
+
+ // FIXME: A lot of undocumented stuff happens with regard to
+ // `is_current_member`, and this is no exception. Ideally there would be an
+ // opportunity to pick statuses when setting up the scheduled reminder
+ // rather than making the assumptions here.
$query->where("e.status_id IN (#memberStatus)")
->param('memberStatus', \CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id'));
@@ -118,39 +154,22 @@ public function createQuery($schedule, $phase, $defaultParams) {
}
/**
- * @return array
+ * Filter out the memberships that are inherited from a contact that the
+ * recipient cannot edit.
+ *
+ * @return CRM_Utils_SQL_Select
*/
protected function prepareMembershipPermissionsFilter() {
- $query = '
-SELECT cm.id AS owner_id, cm.contact_id AS owner_contact, m.id AS slave_id, m.contact_id AS slave_contact, cmt.relationship_type_id AS relation_type, rel.contact_id_a, rel.contact_id_b, rel.is_permission_a_b, rel.is_permission_b_a
-FROM civicrm_membership m
-LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
-LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
-LEFT JOIN civicrm_relationship rel ON ( ( rel.contact_id_a = m.contact_id AND rel.contact_id_b = cm.contact_id AND rel.relationship_type_id = cmt.relationship_type_id )
- OR ( rel.contact_id_a = cm.contact_id AND rel.contact_id_b = m.contact_id AND rel.relationship_type_id = cmt.relationship_type_id ) )
-WHERE m.owner_membership_id IS NOT NULL AND
- ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
-
-';
- $excludeIds = array();
- $dao = \CRM_Core_DAO::executeQuery($query, array());
- while ($dao->fetch()) {
- if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_a_b == 0) {
- $excludeIds[] = $dao->slave_contact;
- }
- elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_b_a == 0) {
- $excludeIds[] = $dao->slave_contact;
- }
- }
+ $joins = [
+ 'cm' => 'LEFT JOIN civicrm_membership cm ON cm.id = e.owner_membership_id',
+ 'rela' => 'LEFT JOIN civicrm_relationship rela ON rela.contact_id_a = e.contact_id AND rela.contact_id_b = cm.contact_id AND rela.is_permission_a_b = #editPerm',
+ 'relb' => 'LEFT JOIN civicrm_relationship relb ON relb.contact_id_a = cm.contact_id AND relb.contact_id_b = e.contact_id AND relb.is_permission_b_a = #editPerm',
+ ];
- if (!empty($excludeIds)) {
- return \CRM_Utils_SQL_Select::fragment()
- ->where("!casContactIdField NOT IN (#excludeMemberIds)")
- ->param(array(
- '#excludeMemberIds' => $excludeIds,
- ));
- }
- return NULL;
+ return \CRM_Utils_SQL_Select::fragment()
+ ->join(NULL, $joins)
+ ->param('#editPerm', CRM_Contact_BAO_Relationship::EDIT)
+ ->where('!( e.owner_membership_id IS NOT NULL AND rela.id IS NULL and relb.id IS NULL )');
}
}
diff --git a/CRM/Member/BAO/Membership.php b/CRM/Member/BAO/Membership.php
index 56376b41611f..49e5181b8be4 100644
--- a/CRM/Member/BAO/Membership.php
+++ b/CRM/Member/BAO/Membership.php
@@ -1,9 +1,9 @@
id = $id;
$membership->save();
- $membership->free();
if (empty($membership->contact_id) || empty($membership->status_id)) {
// this means we are in renewal mode and are just updating the membership
@@ -134,7 +133,7 @@ public static function add(&$params, $ids = array()) {
$membershipLog['modified_id'] = $membership->contact_id;
}
- CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
+ CRM_Member_BAO_MembershipLog::add($membershipLog);
// reset the group contact cache since smart groups might be affected due to this
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
@@ -450,8 +449,8 @@ public static function create(&$params, &$ids, $skipRedirect = FALSE) {
/**
* Check the membership extended through relationship.
*
- * @param int $membershipId
- * Membership id.
+ * @param int $membershipTypeID
+ * Membership type id.
* @param int $contactId
* Contact id.
*
@@ -460,9 +459,8 @@ public static function create(&$params, &$ids, $skipRedirect = FALSE) {
* @return array
* array of contact_id of all related contacts.
*/
- public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action::ADD) {
+ public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action::ADD) {
$contacts = array();
- $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
$membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID);
$relationships = array();
@@ -546,8 +544,6 @@ public static function retrieve(&$params, &$defaults) {
$defaults['active'] = TRUE;
}
- $membership->free();
-
return $membership;
}
@@ -605,6 +601,7 @@ public static function getStatusANDTypeValues($membershipId) {
*
* @param int $membershipId
* Membership id that needs to be deleted.
+ * @param bool $preserveContrib
*
* @return int
* Id of deleted Membership on success, false otherwise.
@@ -620,6 +617,7 @@ public static function del($membershipId, $preserveContrib = FALSE) {
*
* @param int $membershipId
* Membership id that needs to be deleted.
+ * @param bool $preserveContrib
*
* @return int
* Id of deleted Membership on success, false otherwise.
@@ -703,7 +701,6 @@ public static function deleteRelatedMemberships($ownerMembershipId, $contactId =
self::deleteRelatedMemberships($membership->id);
self::deleteMembership($membership->id);
}
- $membership->free();
}
/**
@@ -1119,7 +1116,7 @@ public static function statusAvailabilty() {
* @param CRM_Member_DAO_Membership $membership
* @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
*/
- static public function updateRecurMembership(CRM_Member_DAO_Membership $membership, CRM_Contribute_BAO_Contribution $contribution) {
+ public static function updateRecurMembership(CRM_Member_DAO_Membership $membership, CRM_Contribute_BAO_Contribution $contribution) {
if (empty($contribution->contribution_recur_id)) {
return;
@@ -1145,9 +1142,8 @@ static public function updateRecurMembership(CRM_Member_DAO_Membership $membersh
* Reference to the array.
* containing all values of
* the current membership
- * @param array $changeToday
- * Array of month, day, year.
- * values in case today needs
+ * @param string $changeToday
+ * In case today needs
* to be customised, null otherwise
*/
public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
@@ -1166,10 +1162,8 @@ public static function fixMembershipStatusBeforeRenew(&$currentMembership, $chan
$currentMembership
);
- if (empty($status) ||
- empty($status['id'])
- ) {
- CRM_Core_Error::fatal(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.'));
+ if (empty($status) || empty($status['id'])) {
+ throw new CRM_Core_Exception(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.'));
}
$currentMembership['today_date'] = $today;
@@ -1186,7 +1180,6 @@ public static function fixMembershipStatusBeforeRenew(&$currentMembership, $chan
$memberDAO->end_date = CRM_Utils_Date::isoToMysql($memberDAO->end_date);
$memberDAO->save();
CRM_Core_DAO::storeValues($memberDAO, $currentMembership);
- $memberDAO->free();
$currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue(
'CRM_Member_DAO_MembershipStatus',
@@ -1235,7 +1228,7 @@ public static function fixMembershipStatusBeforeRenew(&$currentMembership, $chan
)
);
- CRM_Member_BAO_MembershipLog::add($logParams, CRM_Core_DAO::$_nullArray);
+ CRM_Member_BAO_MembershipLog::add($logParams);
}
}
@@ -1279,10 +1272,8 @@ public static function updateRelatedMemberships($ownerMembershipId, $params) {
$relatedMembership->id = $membership->id;
$relatedMembership->copyValues($params);
$relatedMembership->save();
- $relatedMembership->free();
}
- $membership->free();
}
/**
@@ -1389,7 +1380,7 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
$allRelatedContacts = array();
$relatedContacts = array();
if (!is_a($membership, 'CRM_Core_Error')) {
- $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->id,
+ $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->membership_type_id,
$membership->contact_id,
CRM_Utils_Array::value('action', $params)
);
@@ -1409,7 +1400,6 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
$nestedRelMembership->id = $membership->owner_membership_id;
$nestedRelMembership->contact_id = $cid;
$nestedRelationship = $nestedRelMembership->find(TRUE);
- $nestedRelMembership->free();
}
if (!$nestedRelationship) {
$relatedContacts[$cid] = $status;
@@ -1439,7 +1429,7 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
// max_related should be set in the parent membership
unset($params['max_related']);
// Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
- $available = ($membership->max_related == NULL ? PHP_INT_MAX : $membership->max_related);
+ $numRelatedAvailable = ($membership->max_related == NULL ? PHP_INT_MAX : $membership->max_related);
// will be used to queue potential memberships to be created.
$queue = array();
@@ -1478,6 +1468,10 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
$params['createActivity'] = TRUE;
}
+ //CRM-20707 - include start/end date
+ $params['start_date'] = $membership->start_date;
+ $params['end_date'] = $membership->end_date;
+
// we should not created contribution record for related contacts, CRM-3371
unset($params['contribution_status_id']);
@@ -1495,9 +1489,9 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
else {
// related membership already exists, so this is just an update
if (isset($params['id'])) {
- if ($available > 0) {
+ if ($numRelatedAvailable > 0) {
CRM_Member_BAO_Membership::create($params, $relMemIds);
- $available--;
+ $numRelatedAvailable--;
}
else {
// we have run out of inherited memberships, so delete extras
@@ -1511,10 +1505,12 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
}
}
// now go over the queue and create any available related memberships
- reset($queue);
- while (($available > 0) && ($params = each($queue))) {
- CRM_Member_BAO_Membership::create($params['value'], $relMemIds);
- $available--;
+ foreach ($queue as $params) {
+ if ($numRelatedAvailable <= 0) {
+ break;
+ }
+ CRM_Member_BAO_Membership::create($params, $relMemIds);
+ $numRelatedAvailable--;
}
}
}
@@ -1523,6 +1519,7 @@ public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE)
* Delete the record that are associated with this Membership Payment.
*
* @param int $membershipId
+ * @param bool $preserveContrib
*
* @return object
* $membershipPayment deleted membership payment object
@@ -1606,7 +1603,6 @@ public static function buildMembershipTypeValues(&$form, $membershipTypeID = arr
$membershipTypeValues[$dao->id][$mtField] = $dao->$mtField;
}
}
- $dao->free();
CRM_Utils_Hook::membershipTypeValues($form, $membershipTypeValues);
@@ -1826,7 +1822,7 @@ public static function linkMembershipPayment($membership, $membershipContributio
* @param int $contactID
* @param int $membershipTypeID
* @param bool $is_test
- * @param $changeToday
+ * @param string $changeToday
* @param int $modifiedID
* @param $customFieldsFormatted
* @param $numRenewTerms
@@ -2114,6 +2110,59 @@ public static function setQuickConfigMembershipParameters($membershipOrg, $membe
return $returnParams;
}
+ /**
+ * Update the status of all deceased members to deceased.
+ *
+ * @return int
+ * Count of updated contacts.
+ */
+ protected static function updateDeceasedMembersStatuses() {
+ $count = 0;
+
+ $deceasedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
+
+ // 'create' context for buildOptions returns only if enabled.
+ $allStatus = self::buildOptions('status_id', 'create');
+ if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
+ // Deceased status is an admin status & is required. We want to fail early if
+ // it is not present or active.
+ // We could make the case 'some databases just don't use deceased so we will check
+ // for the presence of a deceased contact in the DB before rejecting.
+ if (CRM_Core_DAO::singleValueQuery('
+ SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
+ )) {
+ throw new CRM_Core_Exception(
+ ts("Deceased Membership status is missing or not active. Click here to check.",
+ [1 => CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1')]
+ ));
+ }
+ }
+ $deceasedDAO = CRM_Core_DAO::executeQuery(
+ $baseQuery = "
+ SELECT membership.id as membership_id
+ FROM civicrm_membership membership
+ INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
+ INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
+ AND civicrm_membership_type.is_active = 1
+ WHERE membership.is_test = 0
+ AND civicrm_contact.is_deceased = 1
+ AND membership.status_id <> %1
+ ",
+ [1 => [$deceasedStatusId, 'Integer']]
+ );
+ while ($deceasedDAO->fetch()) {
+ civicrm_api3('membership', 'create', [
+ 'id' => $deceasedDAO->membership_id,
+ 'status_id' => $deceasedStatusId,
+ 'createActivity' => TRUE,
+ 'skipStatusCal' => TRUE,
+ 'skipRecentView' => TRUE,
+ ]);
+ $count++;
+ }
+ return $count;
+ }
+
/**
* Process price set and line items.
*
@@ -2146,10 +2195,10 @@ public function processPriceSet($membershipId, $lineItem) {
*
* @param int $membershipId
* Membership id.
- * @all bool
+ * @param bool $all
* if more than one payment associated with membership id need to be returned.
*
- * @return int
+ * @return int|int[]
* contribution id
*/
public static function getMembershipContributionId($membershipId, $all = FALSE) {
@@ -2180,16 +2229,21 @@ public static function getMembershipContributionId($membershipId, $all = FALSE)
* @return array
*/
public static function updateAllMembershipStatus() {
+ // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
- //get all active statuses of membership, CRM-3984
- $allStatus = CRM_Member_PseudoConstant::membershipStatus();
- $statusLabels = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label');
+ $updateCount = $processCount = self::updateDeceasedMembersStatuses();
+
+ // We want all of the statuses as id => name, even the disabled ones (cf.
+ // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
+ // Expired.
+ $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'validate');
$allTypes = CRM_Member_PseudoConstant::membershipType();
- // get only memberships with active membership types
- $query = "
+ // This query retrieves ALL memberships of active types.
+ $baseQuery = "
SELECT civicrm_membership.id as membership_id,
civicrm_membership.is_override as is_override,
+ civicrm_membership.status_override_end_date as status_override_end_date,
civicrm_membership.membership_type_id as membership_type_id,
civicrm_membership.status_id as status_id,
civicrm_membership.join_date as join_date,
@@ -2197,141 +2251,95 @@ public static function updateAllMembershipStatus() {
civicrm_membership.end_date as end_date,
civicrm_membership.source as source,
civicrm_contact.id as contact_id,
- civicrm_contact.is_deceased as is_deceased,
civicrm_membership.owner_membership_id as owner_membership_id,
civicrm_membership.contribution_recur_id as recur_id
FROM civicrm_membership
INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
INNER JOIN civicrm_membership_type ON
(civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
-WHERE civicrm_membership.is_test = 0";
+WHERE civicrm_membership.is_test = 0
+ AND civicrm_contact.is_deceased = 0 ";
- $params = array();
- $dao = CRM_Core_DAO::executeQuery($query, $params);
+ $deceaseStatusId = array_search('Deceased', $allStatus);
+ $pendingStatusId = array_search('Pending', $allStatus);
+ $cancelledStatusId = array_search('Cancelled', $allStatus);
+ // Expired is not reserved so might not exist. A value of `0` won't break.
+ $expiredStatusId = array_search('Expired', $allStatus) ?: 0;
- $processCount = 0;
- $updateCount = 0;
+ $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
+ $dao1 = CRM_Core_DAO::executeQuery($query);
+ while ($dao1->fetch()) {
+ self::processOverriddenUntilDateMembership($dao1);
+ }
- $smarty = CRM_Core_Smarty::singleton();
+ $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
+ AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4)
+ AND civicrm_membership.owner_membership_id IS NULL ";
+ $params = array(
+ 1 => array($pendingStatusId, 'Integer'),
+ 2 => array($cancelledStatusId, 'Integer'),
+ 3 => array($expiredStatusId, 'Integer'),
+ 4 => array($deceaseStatusId, 'Integer'),
+ );
+ $dao2 = CRM_Core_DAO::executeQuery($query, $params);
- while ($dao->fetch()) {
+ while ($dao2->fetch()) {
// echo ".";
$processCount++;
// Put common parameters into array for easy access
$memberParams = array(
- 'id' => $dao->membership_id,
- 'status_id' => $dao->status_id,
- 'contact_id' => $dao->contact_id,
- 'membership_type_id' => $dao->membership_type_id,
- 'membership_type' => $allTypes[$dao->membership_type_id],
- 'join_date' => $dao->join_date,
- 'start_date' => $dao->start_date,
- 'end_date' => $dao->end_date,
- 'source' => $dao->source,
+ 'id' => $dao2->membership_id,
+ 'status_id' => $dao2->status_id,
+ 'contact_id' => $dao2->contact_id,
+ 'membership_type_id' => $dao2->membership_type_id,
+ 'membership_type' => $allTypes[$dao2->membership_type_id],
+ 'join_date' => $dao2->join_date,
+ 'start_date' => $dao2->start_date,
+ 'end_date' => $dao2->end_date,
+ 'source' => $dao2->source,
'skipStatusCal' => TRUE,
'skipRecentView' => TRUE,
);
- $smarty->assign_by_ref('memberParams', $memberParams);
-
- //update membership record to Deceased if contact is deceased
- if ($dao->is_deceased) {
- // check for 'Deceased' membership status, CRM-5636
- $deceaseStatusId = array_search('Deceased', $allStatus);
- if (!$deceaseStatusId) {
- CRM_Core_Error::fatal(ts("Deceased Membership status is missing or not active. Click here to check.", array(1 => CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1'))));
- }
-
- //process only when status change.
- if ($dao->status_id != $deceaseStatusId) {
- //take all params that need to save.
- $deceasedMembership = $memberParams;
- $deceasedMembership['status_id'] = $deceaseStatusId;
- $deceasedMembership['createActivity'] = TRUE;
- $deceasedMembership['version'] = 3;
-
- //since there is change in status.
- $statusChange = array('status_id' => $deceaseStatusId);
- $smarty->append_by_ref('memberParams', $statusChange, TRUE);
- unset(
- $deceasedMembership['contact_id'],
- $deceasedMembership['membership_type_id'],
- $deceasedMembership['membership_type'],
- $deceasedMembership['join_date'],
- $deceasedMembership['start_date'],
- $deceasedMembership['end_date'],
- $deceasedMembership['source']
- );
-
- //process membership record.
- civicrm_api('membership', 'create', $deceasedMembership);
- }
- continue;
- }
-
- //we fetch related, since we need to check for deceased
- //now further processing is handle w/ main membership record.
- if ($dao->owner_membership_id) {
- continue;
- }
+ // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
+ //get the membership status as per id.
+ $newStatus = civicrm_api('membership_status', 'calc',
+ array(
+ 'membership_id' => $dao2->membership_id,
+ 'version' => 3,
+ 'ignore_admin_only' => TRUE,
+ ), TRUE
+ );
+ $statusId = CRM_Utils_Array::value('id', $newStatus);
- //update membership records where status is NOT - Pending OR Cancelled.
- //as well as membership is not override.
- //skipping Expired membership records -> reduced extra processing( kiran )
- if (!$dao->is_override &&
- !in_array($dao->status_id, array(
- array_search('Pending', $allStatus),
- // CRM-15475
- array_search(
- 'Cancelled',
- CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
- ),
- array_search('Expired', $allStatus),
- ))
+ //process only when status change.
+ if ($statusId &&
+ $statusId != $dao2->status_id
) {
-
- // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
- //get the membership status as per id.
- $newStatus = civicrm_api('membership_status', 'calc',
- array(
- 'membership_id' => $dao->membership_id,
- 'version' => 3,
- 'ignore_admin_only' => TRUE,
- ), TRUE
+ //take all params that need to save.
+ $memParams = $memberParams;
+ $memParams['status_id'] = $statusId;
+ $memParams['createActivity'] = TRUE;
+ $memParams['version'] = 3;
+
+ // Unset columns which should remain unchanged from their current saved
+ // values. This avoids race condition in which these values may have
+ // been changed by other processes.
+ unset(
+ $memParams['contact_id'],
+ $memParams['membership_type_id'],
+ $memParams['membership_type'],
+ $memParams['join_date'],
+ $memParams['start_date'],
+ $memParams['end_date'],
+ $memParams['source']
);
- $statusId = CRM_Utils_Array::value('id', $newStatus);
-
- //process only when status change.
- if ($statusId &&
- $statusId != $dao->status_id
- ) {
- //take all params that need to save.
- $memParams = $memberParams;
- $memParams['status_id'] = $statusId;
- $memParams['createActivity'] = TRUE;
- $memParams['version'] = 3;
-
- // Unset columns which should remain unchanged from their current saved
- // values. This avoids race condition in which these values may have
- // been changed by other processes.
- unset(
- $memParams['contact_id'],
- $memParams['membership_type_id'],
- $memParams['membership_type'],
- $memParams['join_date'],
- $memParams['start_date'],
- $memParams['end_date'],
- $memParams['source']
- );
- //since there is change in status.
- $statusChange = array('status_id' => $statusId);
- $smarty->append_by_ref('memberParams', $statusChange, TRUE);
+ //since there is change in status.
- //process member record.
- civicrm_api('membership', 'create', $memParams);
- $updateCount++;
- }
+ //process member record.
+ civicrm_api('membership', 'create', $memParams);
+ $updateCount++;
}
}
$result['is_error'] = 0;
@@ -2342,6 +2350,38 @@ public static function updateAllMembershipStatus() {
return $result;
}
+ /**
+ * Set is_override for the 'overridden until date' membership to
+ * False and clears the 'until date' field in case the 'until date'
+ * is equal or after today date.
+ *
+ * @param CRM_Core_DAO $membership
+ * The membership to be processed
+ */
+ private static function processOverriddenUntilDateMembership($membership) {
+ $isOverriddenUntilDate = !empty($membership->is_override) && !empty($membership->status_override_end_date);
+ if (!$isOverriddenUntilDate) {
+ return;
+ }
+
+ $todayDate = new DateTime();
+ $todayDate->setTime(0, 0);
+
+ $overrideEndDate = new DateTime($membership->status_override_end_date);
+ $overrideEndDate->setTime(0, 0);
+
+ $datesDifference = $todayDate->diff($overrideEndDate);
+ $daysDifference = (int) $datesDifference->format('%R%a');
+ if ($daysDifference <= 0) {
+ $params = array(
+ 'id' => $membership->membership_id,
+ 'is_override' => FALSE,
+ 'status_override_end_date' => 'null',
+ );
+ civicrm_api3('membership', 'create', $params);
+ }
+ }
+
/**
* Returns the membership types for a particular contact
* who has lifetime membership without end date.
@@ -2401,6 +2441,7 @@ public static function recordMembershipContribution(&$params, $ids = array()) {
$contributionParams['receipt_date'] = (CRM_Utils_Array::value('receipt_date', $params)) ? $params['receipt_date'] : 'null';
$contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params);
$contributionParams['non_deductible_amount'] = 'null';
+ $contributionParams['skipCleanMoney'] = TRUE;
$contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor_id', $params);
$contributionSoftParams = CRM_Utils_Array::value('soft_credit', $params);
$recordContribution = array(
@@ -2528,4 +2569,131 @@ public static function getContactsCancelledMembership($contactID, $isTest = FALS
return $cancelledMembershipIds;
}
+ /**
+ * Merges the memberships from otherContactID to mainContactID.
+ *
+ * General idea is to merge memberships in regards to their type. We
+ * move the other contact’s contributions to the main contact’s
+ * membership which has the same type (if any) and then we update
+ * membership to avoid loosing `join_date`, `end_date`, and
+ * `status_id`. In this function, we don’t touch the contributions
+ * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
+ * of it).
+ *
+ * This function adds new SQL queries to the $sqlQueries parameter.
+ *
+ * @param int $mainContactID
+ * Contact id of main contact record.
+ * @param int $otherContactID
+ * Contact id of record which is going to merge.
+ * @param array $sqlQueries
+ * (reference) array of SQL queries to be executed.
+ * @param array $tables
+ * List of tables that have to be merged.
+ * @param array $tableOperations
+ * Special options/params for some tables to be merged.
+ *
+ * @see CRM_Dedupe_Merger::cpTables()
+ */
+ public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
+ /*
+ * If the user requests not to merge memberships but to add them,
+ * just attribute the `civicrm_membership` to the
+ * `$mainContactID`. We have to do this here since the general
+ * merge process is bypassed by this function.
+ */
+ if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
+ $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
+ return;
+ }
+
+ /*
+ * Retrieve all memberships that belongs to each contacts and
+ * keep track of each membership type.
+ */
+ $mainContactMemberships = array();
+ $otherContactMemberships = array();
+
+ $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
+ $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($mainContactID, "Integer")));
+ while ($dao->fetch()) {
+ $mainContactMemberships[$dao->id] = $dao->membership_type_id;
+ }
+
+ $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($otherContactID, "Integer")));
+ while ($dao->fetch()) {
+ $otherContactMemberships[$dao->id] = $dao->membership_type_id;
+ }
+
+ /*
+ * For each membership, move related contributions to the main
+ * contact’s membership (by updating `membership_payments`). Then,
+ * update membership’s `join_date` (if the other membership’s
+ * join_date is older) and `end_date` (if the other membership’s
+ * `end_date` is newer) and `status_id` (if the newly calculated
+ * status is different).
+ *
+ * FIXME: what should we do if we have multiple memberships with
+ * the same type (currently we only take the first one)?
+ */
+ $newSql = array();
+ foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
+ if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
+
+ /*
+ * Move other membership’s contributions to the main one only
+ * if user requested to merge contributions.
+ */
+ if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
+ $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
+ }
+
+ $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
+
+ $newMembership = CRM_Member_DAO_Membership::findById($newMembershipId);
+ $otherMembership = CRM_Member_DAO_Membership::findById($otherMembershipId);
+
+ $updates = array();
+ if (new DateTime($otherMembership->join_date) < new DateTime($newMembership->join_date)) {
+ $updates["join_date"] = $otherMembership->join_date;
+ }
+
+ if (new DateTime($otherMembership->end_date) > new DateTime($newMembership->end_date)) {
+ $updates["end_date"] = $otherMembership->end_date;
+ }
+
+ if (count($updates)) {
+
+ /*
+ * Update status
+ */
+ $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(
+ isset($updates["start_date"]) ? $updates["start_date"] : $newMembership->start_date,
+ isset($updates["end_date"]) ? $updates["end_date"] : $newMembership->end_date,
+ isset($updates["join_date"]) ? $updates["join_date"] : $newMembership->join_date,
+ 'today',
+ FALSE,
+ $newMembershipId,
+ $newMembership
+ );
+
+ if (!empty($status['id']) and $status['id'] != $newMembership->status_id) {
+ $updates['status_id'] = $status['id'];
+ }
+
+ $updates_sql = [];
+ foreach ($updates as $k => $v) {
+ $updates_sql[] = "$k = '{$v}'";
+ }
+
+ $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
+ $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
+ }
+
+ }
+ }
+
+ $sqlQueries = array_merge($sqlQueries, $newSql);
+ }
+
}
diff --git a/CRM/Member/BAO/MembershipBlock.php b/CRM/Member/BAO/MembershipBlock.php
index 921735ba0379..8b785a42ec4d 100644
--- a/CRM/Member/BAO/MembershipBlock.php
+++ b/CRM/Member/BAO/MembershipBlock.php
@@ -1,9 +1,9 @@
copyValues($params);
+ $dao->copyValues($params, TRUE);
$dao->id = CRM_Utils_Array::value('id', $params);
$dao->save();
CRM_Utils_Hook::post($hook, 'MembershipBlock', $dao->id, $dao);
diff --git a/CRM/Member/BAO/MembershipLog.php b/CRM/Member/BAO/MembershipLog.php
index 17d8a11e00cf..d80a05d5e4bf 100644
--- a/CRM/Member/BAO/MembershipLog.php
+++ b/CRM/Member/BAO/MembershipLog.php
@@ -1,9 +1,9 @@
copyValues($params);
$membershipLog->save();
- $membershipLog->free();
return $membershipLog;
}
@@ -75,7 +74,7 @@ public static function resetModifiedID($contactID) {
SET modified_id = null
WHERE modified_id = %1";
- $params = array(1 => array($contactID, 'Integer'));
+ $params = [1 => [$contactID, 'Integer']];
CRM_Core_DAO::executeQuery($query, $params);
}
diff --git a/CRM/Member/BAO/MembershipPayment.php b/CRM/Member/BAO/MembershipPayment.php
index 1853b23d5578..7a509ec3e26d 100644
--- a/CRM/Member/BAO/MembershipPayment.php
+++ b/CRM/Member/BAO/MembershipPayment.php
@@ -1,9 +1,9 @@
$params['membership_id']))) {
+ if (!civicrm_api3('Membership', 'getcount', ['id' => $params['membership_id']])) {
return $dao;
}
@@ -74,10 +73,10 @@ public static function create($params) {
// however, we can assume at this stage that any contribution id will have only one line item with that membership type in the line item table
// OR the caller will have taken responsibility for updating the line items themselves so we will update using SQL here
if (!isset($params['membership_type_id'])) {
- $membership_type_id = civicrm_api3('membership', 'getvalue', array(
+ $membership_type_id = civicrm_api3('membership', 'getvalue', [
'id' => $dao->membership_id,
'return' => 'membership_type_id',
- ));
+ ]);
}
else {
$membership_type_id = $params['membership_type_id'];
@@ -87,11 +86,11 @@ public static function create($params) {
SET entity_table = 'civicrm_membership', entity_id = %1
WHERE pv.membership_type_id = %2
AND contribution_id = %3";
- CRM_Core_DAO::executeQuery($sql, array(
- 1 => array($dao->membership_id, 'Integer'),
- 2 => array($membership_type_id, 'Integer'),
- 3 => array($dao->contribution_id, 'Integer'),
- ));
+ CRM_Core_DAO::executeQuery($sql, [
+ 1 => [$dao->membership_id, 'Integer'],
+ 2 => [$membership_type_id, 'Integer'],
+ 3 => [$dao->contribution_id, 'Integer'],
+ ]);
return $dao;
}
diff --git a/CRM/Member/BAO/MembershipStatus.php b/CRM/Member/BAO/MembershipStatus.php
index d06590ece831..c3508a7e1776 100644
--- a/CRM/Member/BAO/MembershipStatus.php
+++ b/CRM/Member/BAO/MembershipStatus.php
@@ -1,9 +1,9 @@
FALSE,
'is_current_member' => FALSE,
'is_admin' => FALSE,
'is_default' => FALSE,
- );
+ ];
}
/**
@@ -173,7 +174,7 @@ public static function getDefaults() {
* @return array
*/
public static function getMembershipStatus($membershipStatusId) {
- $statusDetails = array();
+ $statusDetails = [];
$membershipStatus = new CRM_Member_DAO_MembershipStatus();
$membershipStatus->id = $membershipStatusId;
if ($membershipStatus->find(TRUE)) {
@@ -194,7 +195,7 @@ public static function del($membershipStatusId) {
//checking if membership status is present in some other table
$check = FALSE;
- $dependency = array('Membership', 'MembershipLog');
+ $dependency = ['Membership', 'MembershipLog'];
foreach ($dependency as $name) {
$baoString = 'CRM_Member_BAO_' . $name;
$dao = new $baoString();
@@ -212,7 +213,6 @@ public static function del($membershipStatusId) {
}
$membershipStatus->delete();
CRM_Member_PseudoConstant::flush('membershipStatus');
- $membershipStatus->free();
}
/**
@@ -235,9 +235,9 @@ public static function del($membershipStatusId) {
*/
public static function getMembershipStatusByDate(
$startDate, $endDate, $joinDate,
- $statusDate = 'today', $excludeIsAdmin = FALSE, $membershipTypeID, $membership = array()
+ $statusDate = 'today', $excludeIsAdmin = FALSE, $membershipTypeID, $membership = []
) {
- $membershipDetails = array();
+ $membershipDetails = [];
if (!$statusDate || $statusDate == 'today') {
$statusDate = getdate();
@@ -255,8 +255,8 @@ public static function getMembershipStatusByDate(
$statusDate = CRM_Utils_Date::customFormat($statusDate, '%Y%m%d');
}
- $dates = array('start', 'end', 'join');
- $events = array('start', 'end');
+ $dates = ['start', 'end', 'join'];
+ $events = ['start', 'end'];
foreach ($dates as $dat) {
if (${$dat . 'Date'} && ${$dat . 'Date'} != "null") {
@@ -361,11 +361,9 @@ public static function getMembershipStatusByDate(
}
//end fetch
- $membershipStatus->free();
-
//we bundle the arguments into an array as we can't pass 8 variables to the hook otherwise
// the membership array might contain the pre-altered settings so we don't want to merge this
- $arguments = array(
+ $arguments = [
'start_date' => $startDate,
'end_date' => $endDate,
'join_date' => $joinDate,
@@ -374,7 +372,7 @@ public static function getMembershipStatusByDate(
'membership_type_id' => $membershipTypeID,
'start_event' => $startEvent,
'end_event' => $endEvent,
- );
+ ];
CRM_Utils_Hook::alterCalculatedMembershipStatus($membershipDetails, $arguments, $membership);
return $membershipDetails;
}
@@ -385,7 +383,7 @@ public static function getMembershipStatusByDate(
* @return array
*/
public static function getMembershipStatusCurrent() {
- $statusIds = array();
+ $statusIds = [];
$membershipStatus = new CRM_Member_DAO_MembershipStatus();
$membershipStatus->is_current_member = 1;
$membershipStatus->find();
@@ -394,7 +392,6 @@ public static function getMembershipStatusCurrent() {
while ($membershipStatus->fetch()) {
$statusIds[] = $membershipStatus->id;
}
- $membershipStatus->free();
return $statusIds;
}
diff --git a/CRM/Member/BAO/MembershipType.php b/CRM/Member/BAO/MembershipType.php
index f53c67175fb5..745294615101 100644
--- a/CRM/Member/BAO/MembershipType.php
+++ b/CRM/Member/BAO/MembershipType.php
@@ -1,9 +1,9 @@
warning('Deprecated: Passing membershipType by $ids array in CRM_Member_BAO_MembershipType::add');
+ }
+ $params['id'] = CRM_Utils_Array::value('membershipType', $ids);
+ }
+
+ $hook = empty($params['id']) ? 'create' : 'edit';
+ CRM_Utils_Hook::pre($hook, 'MembershipType', CRM_Utils_Array::value('id', $params), $params);
+
+ $membershipTypeId = CRM_Utils_Array::value('id', $params);
+
+ if (!$membershipTypeId) {
if (!isset($params['is_active'])) {
// do we need this?
$params['is_active'] = FALSE;
@@ -106,28 +119,30 @@ public static function add(&$params, $ids = array()) {
}
}
- // action is taken depending upon the mode
- $membershipType = new CRM_Member_DAO_MembershipType();
- $membershipType->copyValues($params);
- $membershipType->id = $id;
-
// $previousID is the old organization id for membership type i.e 'member_of_contact_id'. This is used when an organization is changed.
$previousID = NULL;
- if ($id) {
- $previousID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $id, 'member_of_contact_id');
+ if ($membershipTypeId) {
+ $previousID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipTypeId, 'member_of_contact_id');
}
+ // action is taken depending upon the mode
+ $membershipType = new CRM_Member_DAO_MembershipType();
+ $membershipType->copyValues($params);
$membershipType->save();
- if ($id) {
+
+ if ($membershipTypeId) {
// on update we may need to retrieve some details for the price field function - otherwise we get e-notices on attempts to retrieve
// name etc - the presence of previous id tells us this is an update
- $params = array_merge(civicrm_api3('membership_type', 'getsingle', array('id' => $membershipType->id)), $params);
+ $params = array_merge(civicrm_api3('membership_type', 'getsingle', ['id' => $membershipType->id]), $params);
}
self::createMembershipPriceField($params, $previousID, $membershipType->id);
// update all price field value for quick config when membership type is set CRM-11718
- if ($id) {
- self::updateAllPriceFieldValue($id, $params);
+ if ($membershipTypeId) {
+ self::updateAllPriceFieldValue($membershipTypeId, $params);
}
+
+ CRM_Utils_Hook::post($hook, 'MembershipType', $membershipType->id, $membershipType);
+
self::flush();
return $membershipType;
}
@@ -139,8 +154,8 @@ public static function add(&$params, $ids = array()) {
*/
public static function flush() {
CRM_Member_PseudoConstant::membershipType(NULL, TRUE);
- civicrm_api3('membership', 'getfields', array('cache_clear' => 1, 'fieldname' => 'membership_type_id'));
- civicrm_api3('profile', 'getfields', array('action' => 'submit', 'cache_clear' => 1));
+ civicrm_api3('membership', 'getfields', ['cache_clear' => 1, 'fieldname' => 'membership_type_id']);
+ civicrm_api3('profile', 'getfields', ['action' => 'submit', 'cache_clear' => 1]);
}
/**
@@ -154,11 +169,11 @@ public static function flush() {
public static function del($membershipTypeId) {
// Check dependencies.
$check = FALSE;
- $status = array();
- $dependency = array(
+ $status = [];
+ $dependency = [
'Membership' => 'membership_type_id',
'MembershipBlock' => 'membership_type_default',
- );
+ ];
foreach ($dependency as $name => $field) {
$baoString = 'CRM_Member_BAO_' . $name;
@@ -176,20 +191,20 @@ public static function del($membershipTypeId) {
if (in_array('Membership', $status)) {
$findMembersURL = CRM_Utils_System::url('civicrm/member/search', 'reset=1');
$deleteURL = CRM_Utils_System::url('civicrm/contact/search/advanced', 'reset=1');
- $message .= ' ' . ts('%3. There are some contacts who have this membership type assigned to them. Search for contacts with this membership type from Find Members. If you are still getting this message after deleting these memberships, there may be contacts in the Trash (deleted) with this membership type. Try using Advanced Search and checking "Search in Trash".', array(
+ $message .= ' ' . ts('%3. There are some contacts who have this membership type assigned to them. Search for contacts with this membership type from Find Members. If you are still getting this message after deleting these memberships, there may be contacts in the Trash (deleted) with this membership type. Try using Advanced Search and checking "Search in Trash".', [
1 => $findMembersURL,
2 => $deleteURL,
3 => $cnt,
- ));
+ ]);
$cnt++;
}
if (in_array('MembershipBlock', $status)) {
$deleteURL = CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1');
- $message .= ts('%2. This Membership Type is used in an Online Contribution page. Uncheck this membership type in the Memberships tab.', array(
+ $message .= ts('%2. This Membership Type is used in an Online Contribution page. Uncheck this membership type in the Memberships tab.', [
1 => $deleteURL,
2 => $cnt,
- ));
+ ]);
throw new CRM_Core_Exception($message);
}
}
@@ -214,17 +229,17 @@ public static function del($membershipTypeId) {
* An array of membershipType-details.
*/
public static function convertDayFormat(&$membershipType) {
- $periodDays = array(
+ $periodDays = [
'fixed_period_start_day',
'fixed_period_rollover_day',
- );
+ ];
foreach ($membershipType as $id => $details) {
foreach ($periodDays as $pDay) {
if (!empty($details[$pDay])) {
if ($details[$pDay] > 31) {
$month = substr($details[$pDay], 0, strlen($details[$pDay]) - 2);
$day = substr($details[$pDay], -2);
- $monthMap = array(
+ $monthMap = [
'1' => 'Jan',
'2' => 'Feb',
'3' => 'Mar',
@@ -237,7 +252,7 @@ public static function convertDayFormat(&$membershipType) {
'10' => 'Oct',
'11' => 'Nov',
'12' => 'Dec',
- );
+ ];
$membershipType[$id][$pDay] = $monthMap[$month] . ' ' . $day;
}
else {
@@ -256,7 +271,7 @@ public static function convertDayFormat(&$membershipType) {
* @return array
*/
public static function getMembershipTypes($public = TRUE) {
- $membershipTypes = array();
+ $membershipTypes = [];
$membershipType = new CRM_Member_DAO_MembershipType();
$membershipType->is_active = 1;
if ($public) {
@@ -267,7 +282,6 @@ public static function getMembershipTypes($public = TRUE) {
while ($membershipType->fetch()) {
$membershipTypes[$membershipType->id] = $membershipType->name;
}
- $membershipType->free();
return $membershipTypes;
}
@@ -279,14 +293,13 @@ public static function getMembershipTypes($public = TRUE) {
* @return array|null
*/
public static function getMembershipTypeDetails($membershipTypeId) {
- $membershipTypeDetails = array();
+ $membershipTypeDetails = [];
$membershipType = new CRM_Member_DAO_MembershipType();
$membershipType->is_active = 1;
$membershipType->id = $membershipTypeId;
if ($membershipType->find(TRUE)) {
CRM_Core_DAO::storeValues($membershipType, $membershipTypeDetails);
- $membershipType->free();
return $membershipTypeDetails;
}
else {
@@ -314,11 +327,11 @@ public static function getDatesForMembershipType($membershipTypeId, $joinDate =
$membershipTypeDetails = self::getMembershipTypeDetails($membershipTypeId);
// Convert all dates to 'Y-m-d' format.
- foreach (array(
+ foreach ([
'joinDate',
'startDate',
'endDate',
- ) as $dateParam) {
+ ] as $dateParam) {
if (!empty($$dateParam)) {
$$dateParam = CRM_Utils_Date::processDate($$dateParam, NULL, FALSE, 'Y-m-d');
}
@@ -426,11 +439,11 @@ public static function getDatesForMembershipType($membershipTypeId, $joinDate =
}
}
- $membershipDates = array(
+ $membershipDates = [
'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'),
'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'),
'join_date' => CRM_Utils_Date::customFormat($joinDate, '%Y%m%d'),
- );
+ ];
return $membershipDates;
}
@@ -493,6 +506,7 @@ public static function isDuringFixedAnnualRolloverPeriod($startDate, $membership
*
* @param int $membershipId
* @param $changeToday
+ * If provided, specify an alternative date to use as "today" for renewal
* @param int $membershipTypeID
* If provided, overrides the membership type of the $membershipID membership.
* @param int $numRenewTerms
@@ -504,11 +518,11 @@ public static function isDuringFixedAnnualRolloverPeriod($startDate, $membership
* array fo the start date, end date and join date of the membership
*/
public static function getRenewalDatesForMembershipType($membershipId, $changeToday = NULL, $membershipTypeID = NULL, $numRenewTerms = 1) {
- $params = array('id' => $membershipId);
+ $params = ['id' => $membershipId];
$membershipDetails = CRM_Member_BAO_Membership::getValues($params, $values);
$membershipDetails = $membershipDetails[$membershipId];
$statusID = $membershipDetails->status_id;
- $membershipDates = array();
+ $membershipDates = [];
if (!empty($membershipDetails->join_date)) {
$membershipDates['join_date'] = CRM_Utils_Date::customFormat($membershipDetails->join_date, '%Y%m%d');
}
@@ -536,6 +550,8 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
$date = $membershipDetails->end_date;
}
$date = explode('-', $date);
+ // We have to add 1 day first in case it's the end of the month, then subtract afterwards
+ // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
$logStartDate = date('Y-m-d', mktime(0, 0, 0,
(double) $date[1],
(double) ($date[2] + 1),
@@ -620,14 +636,14 @@ public static function getRenewalDatesForMembershipType($membershipId, $changeTo
* array of the details of membership types
*/
public static function getMembershipTypesByOrg($orgID) {
- Civi::log()->warning('Deprecated function getMembershipTypesByOrg, please user membership_type api', array('civi.tag' => 'deprecated'));
- $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', array(
+ CRM_Core_Error::deprecatedFunctionWarning('membership_type api');
+ $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
'member_of_contact_id' => $orgID,
- 'options' => array(
+ 'options' => [
'limit' => 0,
- ),
- ));
- return CRM_Utils_Array::value('values', $memberTypesSameParentOrg, array());
+ ],
+ ]);
+ return CRM_Utils_Array::value('values', $memberTypesSameParentOrg, []);
}
/**
@@ -639,7 +655,7 @@ public static function getMembershipTypesByOrg($orgID) {
* array of the details of membership types with Member of Contact id
*/
public static function getMemberOfContactByMemTypes($membershipTypes) {
- $memTypeOrganizations = array();
+ $memTypeOrganizations = [];
if (empty($membershipTypes)) {
return $memTypeOrganizations;
}
@@ -660,7 +676,7 @@ public static function getMemberOfContactByMemTypes($membershipTypes) {
* @return array
*/
public static function getMembershipTypeOrganization($membershipTypeId = NULL) {
- $allMembershipTypes = array();
+ $allMembershipTypes = [];
$membershipType = new CRM_Member_DAO_MembershipType();
@@ -685,7 +701,7 @@ public static function getMembershipTypeOrganization($membershipTypeId = NULL) {
*/
public static function getMembershipTypeInfo() {
if (!self::$_membershipTypeInfo) {
- $orgs = $types = array();
+ $orgs = $types = [];
$query = 'SELECT memType.id, memType.name, memType.member_of_contact_id, c.sort_name
FROM civicrm_membership_type memType INNER JOIN civicrm_contact c ON c.id = memType.member_of_contact_id
@@ -696,12 +712,11 @@ public static function getMembershipTypeInfo() {
$types[$dao->member_of_contact_id][$dao->id] = $dao->name;
}
- self::$_membershipTypeInfo = array($orgs, $types);
+ self::$_membershipTypeInfo = [$orgs, $types];
}
return self::$_membershipTypeInfo;
}
-
/**
* @param array $params
* @param int $previousID
@@ -719,14 +734,14 @@ public static function createMembershipPriceField($params, $previousID, $members
}
$fieldLabel = 'Membership Amount';
$optionsIds = NULL;
- $fieldParams = array(
+ $fieldParams = [
'price_set_id ' => $priceSetId,
'name' => $fieldName,
- );
- $results = array();
+ ];
+ $results = [];
CRM_Price_BAO_PriceField::retrieve($fieldParams, $results);
if (empty($results)) {
- $fieldParams = array();
+ $fieldParams = [];
$fieldParams['label'] = $fieldLabel;
$fieldParams['name'] = $fieldName;
$fieldParams['price_set_id'] = $priceSetId;
@@ -748,11 +763,11 @@ public static function createMembershipPriceField($params, $previousID, $members
}
else {
$fieldID = $results['id'];
- $fieldValueParams = array(
+ $fieldValueParams = [
'price_field_id' => $fieldID,
'membership_type_id' => $membershipTypeId,
- );
- $results = array();
+ ];
+ $results = [];
CRM_Price_BAO_PriceFieldValue::retrieve($fieldValueParams, $results);
if (!empty($results)) {
$results['label'] = $results['name'] = $params['name'];
@@ -760,14 +775,14 @@ public static function createMembershipPriceField($params, $previousID, $members
$optionsIds['id'] = $results['id'];
}
else {
- $results = array(
+ $results = [
'price_field_id' => $fieldID,
'name' => $params['name'],
'label' => $params['name'],
'amount' => empty($params['minimum_fee']) ? 0 : $params['minimum_fee'],
'membership_type_id' => $membershipTypeId,
'is_active' => 1,
- );
+ ];
}
if ($previousID) {
@@ -791,41 +806,39 @@ public static function createMembershipPriceField($params, $previousID, $members
* @param array $params
*/
public static function updateAllPriceFieldValue($membershipTypeId, $params) {
- $updateFields = array();
- if (!empty($params['minimum_fee'])) {
- $amount = $params['minimum_fee'];
- }
- else {
- $amount = 0;
- }
-
- $updateValues = array(
- 2 => array('financial_type_id', 'financial_type_id', 'Integer'),
- 3 => array('label', 'name', 'String'),
- 4 => array('amount', 'minimum_fee', 'Float'),
- 5 => array('description', 'description', 'String'),
- );
-
- $queryParams = array(1 => array($membershipTypeId, 'Integer'));
- foreach ($updateValues as $key => $value) {
- if (array_key_exists($value[1], $params)) {
- $updateFields[] = "cpfv." . $value[0] . " = %$key";
- if ($value[1] == 'minimum_fee') {
- $fieldValue = $amount;
- }
- else {
- $fieldValue = $params[$value[1]];
+ $defaults = [];
+ $fieldsToUpdate = [
+ 'financial_type_id' => 'financial_type_id',
+ 'name' => 'label',
+ 'minimum_fee' => 'amount',
+ 'description' => 'description',
+ 'visibility' => 'visibility_id',
+ ];
+ $priceFieldValueBAO = new CRM_Price_BAO_PriceFieldValue();
+ $priceFieldValueBAO->membership_type_id = $membershipTypeId;
+ $priceFieldValueBAO->find();
+ while ($priceFieldValueBAO->fetch()) {
+ $updateParams = [
+ 'id' => $priceFieldValueBAO->id,
+ 'price_field_id' => $priceFieldValueBAO->price_field_id,
+ ];
+ //Get priceset details.
+ $fieldParams = ['fid' => $priceFieldValueBAO->price_field_id];
+ $setID = CRM_Price_BAO_PriceSet::getSetId($fieldParams);
+ $setParams = ['id' => $setID];
+ $setValues = CRM_Price_BAO_PriceSet::retrieve($setParams, $defaults);
+ if (!empty($setValues->is_quick_config) && $setValues->name != 'default_membership_type_amount') {
+ foreach ($fieldsToUpdate as $key => $value) {
+ if ($value == 'visibility_id' && !empty($params['visibility'])) {
+ $updateParams['visibility_id'] = CRM_Price_BAO_PriceField::getVisibilityOptionID(strtolower($params['visibility']));
+ }
+ else {
+ $updateParams[$value] = CRM_Utils_Array::value($key, $params);
+ }
}
- $queryParams[$key] = array($fieldValue, $value[2]);
+ CRM_Price_BAO_PriceFieldValue::add($updateParams);
}
}
-
- $query = "UPDATE `civicrm_price_field_value` cpfv
-INNER JOIN civicrm_price_field cpf on cpf.id = cpfv.price_field_id
-INNER JOIN civicrm_price_set cps on cps.id = cpf.price_set_id
-SET " . implode(' , ', $updateFields) . " WHERE cpfv.membership_type_id = %1
-AND cps.is_quick_config = 1 AND cps.name != 'default_membership_type_amount'";
- CRM_Core_DAO::executeQuery($query, $queryParams);
}
}
diff --git a/CRM/Member/BAO/Query.php b/CRM/Member/BAO/Query.php
index 79d9b7b39571..3294569e6c52 100644
--- a/CRM/Member/BAO/Query.php
+++ b/CRM/Member/BAO/Query.php
@@ -1,9 +1,9 @@
dateQueryBuilder($values,
- 'civicrm_membership', 'member_start_date', 'start_date',
+ 'civicrm_membership', $fldName, 'start_date',
'Start Date'
);
return;
+ case 'membership_end_date':
case 'member_end_date_low':
case 'member_end_date_high':
+ $fldName = str_replace(['_low', '_high'], '', $name);
$query->dateQueryBuilder($values,
- 'civicrm_membership', 'member_end_date', 'end_date',
+ 'civicrm_membership', $fldName, 'end_date',
'End Date'
);
return;
@@ -193,7 +197,7 @@ public static function whereClauseSingle(&$values, &$query) {
if ($date) {
$query->_where[$grouping][] = "civicrm_membership.join_date {$op} {$date}";
$format = CRM_Utils_Date::customFormat(CRM_Utils_Date::format(array_reverse($value), '-'));
- $query->_qill[$grouping][] = ts('Member Since %2 %1', array(1 => $format, 2 => $op));
+ $query->_qill[$grouping][] = ts('Member Since %2 %1', [1 => $format, 2 => $op]);
}
return;
@@ -204,7 +208,7 @@ public static function whereClauseSingle(&$values, &$query) {
$value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
$query->_where[$grouping][] = "civicrm_membership.source $op '{$value}'";
- $query->_qill[$grouping][] = ts('Source %2 %1', array(1 => $value, 2 => $op));
+ $query->_qill[$grouping][] = ts('Source %2 %1', [1 => $value, 2 => $op]);
$query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
return;
@@ -226,10 +230,11 @@ public static function whereClauseSingle(&$values, &$query) {
// the load function. The where clause and the whereTables are saved so they should suffice to generate the query
// to get a contact list. But, better to deal with in 4.8 now...
if (is_string($value) && strpos($value, ',') && $op == '=') {
- $value = array('IN' => explode(',', $value));
+ $value = ['IN' => explode(',', $value)];
}
case 'membership_id':
- case 'member_id': // CRM-18523 Updated to membership_id but kept member_id case for backwards compatibility
+ // CRM-18523 Updated to membership_id but kept member_id case for backwards compatibility
+ case 'member_id':
case 'member_campaign_id':
if (strpos($name, 'status') !== FALSE) {
@@ -278,7 +283,7 @@ public static function whereClauseSingle(&$values, &$query) {
case 'member_auto_renew':
$op = '=';
- $where = $qill = array();
+ $where = $qill = [];
foreach ($value as $val) {
if ($val == 1) {
$where[] = ' civicrm_membership.contribution_recur_id IS NULL';
@@ -430,7 +435,7 @@ public static function defaultReturnProperties(
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_MEMBER) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -450,7 +455,7 @@ public static function defaultReturnProperties(
'member_campaign_id' => 1,
'member_is_override' => 1,
'member_auto_renew' => 1,
- );
+ ];
if ($includeCustomFields) {
// also get all the custom membership properties
@@ -473,21 +478,21 @@ public static function defaultReturnProperties(
*/
public static function buildSearchForm(&$form) {
$membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label', FALSE, FALSE);
- $form->add('select', 'membership_status_id', ts('Membership Status'), $membershipStatus, FALSE, array(
+ $form->add('select', 'membership_status_id', ts('Membership Status'), $membershipStatus, FALSE, [
'id' => 'membership_status_id',
'multiple' => 'multiple',
'class' => 'crm-select2',
- ));
+ ]);
- $form->addEntityRef('membership_type_id', ts('Membership Type'), array(
+ $form->addEntityRef('membership_type_id', ts('Membership Type'), [
'entity' => 'MembershipType',
'multiple' => TRUE,
'placeholder' => ts('- any -'),
- 'select' => array('minimumInputLength' => 0),
- ));
+ 'select' => ['minimumInputLength' => 0],
+ ]);
$form->addElement('text', 'member_source', ts('Source'));
- $form->add('number', 'membership_id', ts('Membership ID'), array('class' => 'four', 'min' => 1));
+ $form->add('number', 'membership_id', ts('Membership ID'), ['class' => 'four', 'min' => 1]);
CRM_Core_Form_Date::buildDateRange($form, 'member_join_date', 1, '_low', '_high', ts('From'), FALSE);
$form->addElement('hidden', 'member_join_date_range_error');
@@ -498,7 +503,7 @@ public static function buildSearchForm(&$form) {
CRM_Core_Form_Date::buildDateRange($form, 'member_end_date', 1, '_low', '_high', ts('From'), FALSE);
$form->addElement('hidden', 'member_end_date_range_error');
- $form->addFormRule(array('CRM_Member_BAO_Query', 'formRule'), $form);
+ $form->addFormRule(['CRM_Member_BAO_Query', 'formRule'], $form);
$form->addYesNo('membership_is_current_member', ts('Current Member?'), TRUE);
$form->addYesNo('member_is_primary', ts('Primary Member?'), TRUE);
@@ -506,26 +511,26 @@ public static function buildSearchForm(&$form) {
$form->add('select', 'member_auto_renew',
ts('Auto-Renew Subscription Status?'),
- array(
+ [
'1' => ts('- None -'),
'2' => ts('In Progress'),
'3' => ts('Failed'),
'4' => ts('Cancelled'),
'5' => ts('Ended'),
'6' => ts('Any'),
- ),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -'))
+ ],
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -')]
);
$form->addYesNo('member_test', ts('Membership is a Test?'), TRUE);
$form->addYesNo('member_is_override', ts('Membership Status Is Overriden?'), TRUE);
- self::addCustomFormFields($form, array('Membership'));
+ self::addCustomFormFields($form, ['Membership']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'member_campaign_id');
$form->assign('validCiviMember', TRUE);
- $form->setDefaults(array('member_test' => 0));
+ $form->setDefaults(['member_test' => 0]);
}
/**
@@ -535,7 +540,7 @@ public static function buildSearchForm(&$form) {
*/
public static function tableNames(&$tables) {
if (!empty($tables['civicrm_membership_log']) || !empty($tables['civicrm_membership_status']) || CRM_Utils_Array::value('civicrm_membership_type', $tables)) {
- $tables = array_merge(array('civicrm_membership' => 1), $tables);
+ $tables = array_merge(['civicrm_membership' => 1], $tables);
}
}
@@ -549,7 +554,7 @@ public static function tableNames(&$tables) {
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
if ((empty($fields['member_join_date_low']) || empty($fields['member_join_date_high'])) && (empty($fields['member_start_date_low']) || empty($fields['member_start_date_high'])) && (empty($fields['member_end_date_low']) || empty($fields['member_end_date_high']))) {
return TRUE;
diff --git a/CRM/Member/Controller/Search.php b/CRM/Member/Controller/Search.php
index c72c64293ca7..c1f9bcce080b 100644
--- a/CRM/Member/Controller/Search.php
+++ b/CRM/Member/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_membership';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_id', 'civicrm_membership_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_membership_status', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'owner_membership_id', 'civicrm_membership', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_recur_id', 'civicrm_contribution_recur', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_id', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'status_id', 'civicrm_membership_status', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'owner_membership_id', 'civicrm_membership', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_recur_id', 'civicrm_contribution_recur', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'membership_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'membership_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Membership ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.id',
'headerPattern' => '/^(m(embership\s)?id)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- ) ,
- 'membership_contact_id' => array(
+ ],
+ 'membership_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.contact_id',
'headerPattern' => '/contact(.?id)?/i',
'dataPattern' => '/^\d+$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'membership_type_id' => array(
+ ],
+ ],
+ 'membership_type_id' => [
'name' => 'membership_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Id') ,
- 'description' => 'FK to Membership Type',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Membership Type Id'),
+ 'description' => ts('FK to Membership Type'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.membership_type_id',
'headerPattern' => '/^(m(embership\s)?type)$/i',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_membership_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'join_date' => array(
+ ]
+ ],
+ 'join_date' => [
'name' => 'join_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Member Since') ,
- 'description' => 'Beginning of initial membership period (member since...).',
- 'import' => true,
+ 'title' => ts('Member Since'),
+ 'description' => ts('Beginning of initial membership period (member since...).'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.join_date',
'headerPattern' => '/^join|(j(oin\s)?date)$/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDate',
- ) ,
- ) ,
- 'membership_start_date' => array(
+ ],
+ ],
+ 'membership_start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Start Date') ,
- 'description' => 'Beginning of current uninterrupted membership period.',
- 'import' => true,
+ 'title' => ts('Membership Start Date'),
+ 'description' => ts('Beginning of current uninterrupted membership period.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.start_date',
'headerPattern' => '/(member(ship)?.)?start(s)?(.date$)?/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDate',
- ) ,
- ) ,
- 'membership_end_date' => array(
+ ],
+ ],
+ 'membership_end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Expiration Date') ,
- 'description' => 'Current membership period expire date.',
- 'import' => true,
+ 'title' => ts('Membership Expiration Date'),
+ 'description' => ts('Current membership period expire date.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.end_date',
'headerPattern' => '/(member(ship)?.)?end(s)?(.date$)?/i',
'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
'formatType' => 'activityDate',
- ) ,
- ) ,
- 'membership_source' => array(
+ ],
+ ],
+ 'membership_source' => [
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Source') ,
+ 'title' => ts('Source'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_membership.source',
'headerPattern' => '/^(member(ship?))?source$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'status_id' => array(
+ ],
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Status Id') ,
- 'description' => 'FK to Membership Status',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Membership Status Id'),
+ 'description' => ts('FK to Membership Status'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_membership.status_id',
'headerPattern' => '/(member(ship|).)?(status)$/i',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipStatus',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_membership_status',
'keyColumn' => 'id',
'labelColumn' => 'label',
- )
- ) ,
- 'is_override' => array(
+ ]
+ ],
+ 'is_override' => [
'name' => 'is_override',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Status Override') ,
- 'description' => 'Admin users may set a manual status which overrides the calculated status. When this flag is true, automated status update scripts should NOT modify status for the record.',
- 'import' => true,
+ 'title' => ts('Status Override'),
+ 'description' => ts('Admin users may set a manual status which overrides the calculated status. When this flag is true, automated status update scripts should NOT modify status for the record.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.is_override',
'headerPattern' => '/override$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'owner_membership_id' => array(
+ ],
+ ],
+ 'status_override_end_date' => [
+ 'name' => 'status_override_end_date',
+ 'type' => CRM_Utils_Type::T_DATE,
+ 'title' => ts('Status Override End Date'),
+ 'description' => ts('Then end date of membership status override if \'Override until selected date\' override type is selected.'),
+ 'import' => TRUE,
+ 'where' => 'civicrm_membership.status_override_end_date',
+ 'export' => TRUE,
+ 'default' => 'NULL',
+ 'table_name' => 'civicrm_membership',
+ 'entity' => 'Membership',
+ 'bao' => 'CRM_Member_BAO_Membership',
+ 'localizable' => 0,
+ 'html' => [
+ 'type' => 'Select Date',
+ ],
+ ],
+ 'owner_membership_id' => [
'name' => 'owner_membership_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Primary Member ID') ,
- 'description' => 'Optional FK to Parent Membership.',
- 'export' => true,
+ 'title' => ts('Primary Member ID'),
+ 'description' => ts('Optional FK to Parent Membership.'),
'where' => 'civicrm_membership.owner_membership_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_Membership',
- ) ,
- 'max_related' => array(
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Related') ,
- 'description' => 'Maximum number of related memberships (membership_type override).',
+ 'title' => ts('Max Related'),
+ 'description' => ts('Maximum number of related memberships (membership_type override).'),
+ 'where' => 'civicrm_membership.max_related',
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'member_is_test' => array(
+ ],
+ ],
+ 'member_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.is_test',
'headerPattern' => '/(is.)?test(.member(ship)?)?/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'member_is_pay_later' => array(
+ ],
+ ],
+ 'member_is_pay_later' => [
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Pay Later') ,
- 'import' => true,
+ 'title' => ts('Is Pay Later'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.is_pay_later',
'headerPattern' => '/(is.)?(pay(.)?later)$/i',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'contribution_recur_id' => array(
+ ],
+ ],
+ 'contribution_recur_id' => [
'name' => 'contribution_recur_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Recurring Contribution') ,
- 'description' => 'Conditional foreign key to civicrm_contribution_recur id. Each membership in connection with a recurring contribution carries a foreign key to the recurring contribution record. This assumes we can track these processor initiated events.',
+ 'title' => ts('Membership Recurring Contribution'),
+ 'description' => ts('Conditional foreign key to civicrm_contribution_recur id. Each membership in connection with a recurring contribution carries a foreign key to the recurring contribution record. This assumes we can track these processor initiated events.'),
+ 'where' => 'civicrm_membership.contribution_recur_id',
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionRecur',
- ) ,
- 'member_campaign_id' => array(
+ ],
+ 'member_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this membership is attached.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this membership is attached.'),
+ 'import' => TRUE,
'where' => 'civicrm_membership.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership',
'entity' => 'Membership',
'bao' => 'CRM_Member_BAO_Membership',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -488,10 +501,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -499,24 +513,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_owner_membership_id' => array(
+ $indices = [
+ 'index_owner_membership_id' => [
'name' => 'index_owner_membership_id',
- 'field' => array(
+ 'field' => [
0 => 'owner_membership_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_membership::0::owner_membership_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipBlock.php b/CRM/Member/DAO/MembershipBlock.php
index f20ca244a47d..275fce3e7a38 100644
--- a/CRM/Member/DAO/MembershipBlock.php
+++ b/CRM/Member/DAO/MembershipBlock.php
@@ -1,341 +1,353 @@
__table = 'civicrm_membership_block';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'entity_id', 'civicrm_contribution_page', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_default', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'entity_id', 'civicrm_contribution_page', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_default', 'civicrm_membership_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Block ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
+ 'title' => ts('Membership Block ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_block.id',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block Entity Table') ,
- 'description' => 'Name for Membership Status',
+ 'title' => ts('Membership Block Entity Table'),
+ 'description' => ts('Name for Membership Status'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_membership_block.entity_table',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Block Entity ID') ,
- 'description' => 'FK to civicrm_contribution_page.id',
- 'required' => true,
+ 'title' => ts('Membership Block Entity ID'),
+ 'description' => ts('FK to civicrm_contribution_page.id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_block.entity_id',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
- ) ,
- 'membership_types' => array(
+ ],
+ 'membership_types' => [
'name' => 'membership_types',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block Membership Types') ,
- 'description' => 'Membership types to be exposed by this block',
+ 'title' => ts('Membership Block Membership Types'),
+ 'description' => ts('Membership types to be exposed by this block'),
'maxlength' => 1024,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_block.membership_types',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'membership_type_default' => array(
+ 'serialize' => self::SERIALIZE_PHP,
+ ],
+ 'membership_type_default' => [
'name' => 'membership_type_default',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Block Default Type') ,
- 'description' => 'Optional foreign key to membership_type',
+ 'title' => ts('Membership Block Default Type'),
+ 'description' => ts('Optional foreign key to membership_type'),
+ 'where' => 'civicrm_membership_block.membership_type_default',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- ) ,
- 'display_min_fee' => array(
+ ],
+ 'display_min_fee' => [
'name' => 'display_min_fee',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Membership Block Display Minimum Fee') ,
- 'description' => 'Display minimum membership fee',
+ 'title' => ts('Membership Block Display Minimum Fee'),
+ 'description' => ts('Display minimum membership fee'),
+ 'where' => 'civicrm_membership_block.display_min_fee',
'default' => '1',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'is_separate_payment' => array(
+ ],
+ 'is_separate_payment' => [
'name' => 'is_separate_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Membership Block Is Separate Payment') ,
- 'description' => 'Should membership transactions be processed separately',
+ 'title' => ts('Membership Block Is Separate Payment'),
+ 'description' => ts('Should membership transactions be processed separately'),
+ 'where' => 'civicrm_membership_block.is_separate_payment',
'default' => '1',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'new_title' => array(
+ ],
+ 'new_title' => [
'name' => 'new_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block New Title') ,
- 'description' => 'Title to display at top of block',
+ 'title' => ts('Membership Block New Title'),
+ 'description' => ts('Title to display at top of block'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_block.new_title',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'new_text' => array(
+ ],
+ 'new_text' => [
'name' => 'new_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Membership Block New Text') ,
- 'description' => 'Text to display below title',
+ 'title' => ts('Membership Block New Text'),
+ 'description' => ts('Text to display below title'),
+ 'where' => 'civicrm_membership_block.new_text',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'renewal_title' => array(
+ ],
+ 'renewal_title' => [
'name' => 'renewal_title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Block Renewal Title') ,
- 'description' => 'Title for renewal',
+ 'title' => ts('Membership Block Renewal Title'),
+ 'description' => ts('Title for renewal'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_block.renewal_title',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'renewal_text' => array(
+ ],
+ 'renewal_text' => [
'name' => 'renewal_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Membership Block Renewal Text') ,
- 'description' => 'Text to display for member renewal',
+ 'title' => ts('Membership Block Renewal Text'),
+ 'description' => ts('Text to display for member renewal'),
+ 'where' => 'civicrm_membership_block.renewal_text',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 1,
- ) ,
- 'is_required' => array(
+ ],
+ 'is_required' => [
'name' => 'is_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Required') ,
- 'description' => 'Is membership sign up optional',
+ 'title' => ts('Is Required'),
+ 'description' => ts('Is membership sign up optional'),
+ 'where' => 'civicrm_membership_block.is_required',
+ 'default' => '0',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this membership_block enabled',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this membership_block enabled'),
+ 'where' => 'civicrm_membership_block.is_active',
'default' => '1',
'table_name' => 'civicrm_membership_block',
'entity' => 'MembershipBlock',
'bao' => 'CRM_Member_BAO_MembershipBlock',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -343,10 +355,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_block', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -354,15 +367,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_block', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipLog.php b/CRM/Member/DAO/MembershipLog.php
index 8b7f6b986e4c..30b1e0bf4768 100644
--- a/CRM/Member/DAO/MembershipLog.php
+++ b/CRM/Member/DAO/MembershipLog.php
@@ -1,269 +1,273 @@
__table = 'civicrm_membership_log';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_id', 'civicrm_membership', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_membership_status', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'modified_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_id', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_id', 'civicrm_membership', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'status_id', 'civicrm_membership_status', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'modified_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_id', 'civicrm_membership_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Log ID') ,
- 'required' => true,
+ 'title' => ts('Membership Log ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_log.id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'membership_id' => array(
+ ],
+ 'membership_id' => [
'name' => 'membership_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership ID') ,
- 'description' => 'FK to Membership table',
- 'required' => true,
+ 'title' => ts('Membership ID'),
+ 'description' => ts('FK to Membership table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_log.membership_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_Membership',
- ) ,
- 'status_id' => array(
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Status') ,
- 'description' => 'New status assigned to membership by this action. FK to Membership Status',
- 'required' => true,
+ 'title' => ts('Membership Status'),
+ 'description' => ts('New status assigned to membership by this action. FK to Membership Status'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_log.status_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipStatus',
- ) ,
- 'start_date' => array(
+ ],
+ 'start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Log Start Date') ,
- 'description' => 'New membership period start date',
+ 'title' => ts('Membership Log Start Date'),
+ 'description' => ts('New membership period start date'),
+ 'where' => 'civicrm_membership_log.start_date',
+ 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'end_date' => array(
+ ],
+ 'end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Log End Date') ,
- 'description' => 'New membership period expiration date.',
+ 'title' => ts('Membership Log End Date'),
+ 'description' => ts('New membership period expiration date.'),
+ 'where' => 'civicrm_membership_log.end_date',
+ 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'modified_id' => array(
+ ],
+ 'modified_id' => [
'name' => 'modified_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Log modified By') ,
- 'description' => 'FK to Contact ID of person under whose credentials this data modification was made.',
+ 'title' => ts('Membership Log modified By'),
+ 'description' => ts('FK to Contact ID of person under whose credentials this data modification was made.'),
+ 'where' => 'civicrm_membership_log.modified_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'modified_date' => array(
+ ],
+ 'modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_DATE,
- 'title' => ts('Membership Change Date') ,
- 'description' => 'Date this membership modification action was logged.',
+ 'title' => ts('Membership Change Date'),
+ 'description' => ts('Date this membership modification action was logged.'),
+ 'where' => 'civicrm_membership_log.modified_date',
+ 'dataPattern' => '/\d{4}-?\d{2}-?\d{2}/',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- 'membership_type_id' => array(
+ ],
+ 'membership_type_id' => [
'name' => 'membership_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type ID') ,
- 'description' => 'FK to Membership Type.',
+ 'title' => ts('Membership Type ID'),
+ 'description' => ts('FK to Membership Type.'),
+ 'where' => 'civicrm_membership_log.membership_type_id',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- ) ,
- 'max_related' => array(
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum Related Memberships') ,
- 'description' => 'Maximum number of related memberships.',
+ 'title' => ts('Maximum Related Memberships'),
+ 'description' => ts('Maximum number of related memberships.'),
+ 'where' => 'civicrm_membership_log.max_related',
'table_name' => 'civicrm_membership_log',
'entity' => 'MembershipLog',
'bao' => 'CRM_Member_BAO_MembershipLog',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -271,10 +275,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_log', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_log', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -282,15 +287,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_log', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_log', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipPayment.php b/CRM/Member/DAO/MembershipPayment.php
index 73af131b1e84..82a01b13e695 100644
--- a/CRM/Member/DAO/MembershipPayment.php
+++ b/CRM/Member/DAO/MembershipPayment.php
@@ -1,168 +1,157 @@
__table = 'civicrm_membership_payment';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_id', 'civicrm_membership', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_id', 'civicrm_membership', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Payment ID') ,
- 'required' => true,
+ 'title' => ts('Membership Payment ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_payment.id',
'table_name' => 'civicrm_membership_payment',
'entity' => 'MembershipPayment',
'bao' => 'CRM_Member_BAO_MembershipPayment',
'localizable' => 0,
- ) ,
- 'membership_id' => array(
+ ],
+ 'membership_id' => [
'name' => 'membership_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership') ,
- 'description' => 'FK to Membership table',
- 'required' => true,
+ 'title' => ts('Membership'),
+ 'description' => ts('FK to Membership table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_payment.membership_id',
'table_name' => 'civicrm_membership_payment',
'entity' => 'MembershipPayment',
'bao' => 'CRM_Member_BAO_MembershipPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_Membership',
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution') ,
- 'description' => 'FK to contribution table.',
+ 'title' => ts('Contribution'),
+ 'description' => ts('FK to contribution table.'),
+ 'where' => 'civicrm_membership_payment.contribution_id',
'table_name' => 'civicrm_membership_payment',
'entity' => 'MembershipPayment',
'bao' => 'CRM_Member_BAO_MembershipPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -170,10 +159,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_payment', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -181,26 +171,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_payment', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_contribution_membership' => array(
+ $indices = [
+ 'UI_contribution_membership' => [
'name' => 'UI_contribution_membership',
- 'field' => array(
+ 'field' => [
0 => 'contribution_id',
1 => 'membership_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_membership_payment::1::contribution_id::membership_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipStatus.php b/CRM/Member/DAO/MembershipStatus.php
index 3d7f1d8dafdd..701759ffc036 100644
--- a/CRM/Member/DAO/MembershipStatus.php
+++ b/CRM/Member/DAO/MembershipStatus.php
@@ -1,384 +1,409 @@
__table = 'civicrm_membership_status';
parent::__construct();
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Status ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
+ 'title' => ts('Membership Status ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_status.id',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'membership_status' => array(
+ ],
+ 'membership_status' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Status') ,
- 'description' => 'Name for Membership Status',
+ 'title' => ts('Membership Status'),
+ 'description' => ts('Name for Membership Status'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_membership_status.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label') ,
- 'description' => 'Label for Membership Status',
+ 'title' => ts('Label'),
+ 'description' => ts('Label for Membership Status'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_status.label',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 1,
- ) ,
- 'start_event' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'start_event' => [
'name' => 'start_event',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Start Event') ,
- 'description' => 'Event when this status starts.',
+ 'title' => ts('Start Event'),
+ 'description' => ts('Event when this status starts.'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_membership_status.start_event',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::eventDate',
- )
- ) ,
- 'start_event_adjust_unit' => array(
+ ]
+ ],
+ 'start_event_adjust_unit' => [
'name' => 'start_event_adjust_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Start Event Adjust Unit') ,
- 'description' => 'Unit used for adjusting from start_event.',
+ 'title' => ts('Start Event Adjust Unit'),
+ 'description' => ts('Unit used for adjusting from start_event.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_status.start_event_adjust_unit',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::unitList',
- )
- ) ,
- 'start_event_adjust_interval' => array(
+ ]
+ ],
+ 'start_event_adjust_interval' => [
'name' => 'start_event_adjust_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Start Event Adjust Interval') ,
- 'description' => 'Status range begins this many units from start_event.',
+ 'title' => ts('Start Event Adjust Interval'),
+ 'description' => ts('Status range begins this many units from start_event.'),
+ 'where' => 'civicrm_membership_status.start_event_adjust_interval',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'end_event' => array(
+ ],
+ 'end_event' => [
'name' => 'end_event',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('End Event') ,
- 'description' => 'Event after which this status ends.',
+ 'title' => ts('End Event'),
+ 'description' => ts('Event after which this status ends.'),
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_membership_status.end_event',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::eventDate',
- )
- ) ,
- 'end_event_adjust_unit' => array(
+ ]
+ ],
+ 'end_event_adjust_unit' => [
'name' => 'end_event_adjust_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('End Event Adjust Unit') ,
- 'description' => 'Unit used for adjusting from the ending event.',
+ 'title' => ts('End Event Adjust Unit'),
+ 'description' => ts('Unit used for adjusting from the ending event.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_status.end_event_adjust_unit',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::unitList',
- )
- ) ,
- 'end_event_adjust_interval' => array(
+ ]
+ ],
+ 'end_event_adjust_interval' => [
'name' => 'end_event_adjust_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('End Event Adjust Interval') ,
- 'description' => 'Status range ends this many units from end_event.',
+ 'title' => ts('End Event Adjust Interval'),
+ 'description' => ts('Status range ends this many units from end_event.'),
+ 'where' => 'civicrm_membership_status.end_event_adjust_interval',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_current_member' => array(
+ ],
+ 'is_current_member' => [
'name' => 'is_current_member',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Current Membership?') ,
- 'description' => 'Does this status aggregate to current members (e.g. New, Renewed, Grace might all be TRUE... while Unrenewed, Lapsed, Inactive would be FALSE).',
+ 'title' => ts('Current Membership?'),
+ 'description' => ts('Does this status aggregate to current members (e.g. New, Renewed, Grace might all be TRUE... while Unrenewed, Lapsed, Inactive would be FALSE).'),
+ 'where' => 'civicrm_membership_status.is_current_member',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_admin' => array(
+ ],
+ 'is_admin' => [
'name' => 'is_admin',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Admin Assigned Only?') ,
- 'description' => 'Is this status for admin/manual assignment only.',
+ 'title' => ts('Administrator Only?'),
+ 'description' => ts('Is this status for admin/manual assignment only.'),
+ 'where' => 'civicrm_membership_status.is_admin',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'weight' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
+ 'title' => ts('Order'),
+ 'where' => 'civicrm_membership_status.weight',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_default' => array(
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Default Status?') ,
- 'description' => 'Assign this status to a membership record if no other status match is found.',
+ 'title' => ts('Default Status?'),
+ 'description' => ts('Assign this status to a membership record if no other status match is found.'),
+ 'where' => 'civicrm_membership_status.is_default',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_active' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this membership_status enabled.',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this membership_status enabled.'),
+ 'where' => 'civicrm_membership_status.is_active',
'default' => '1',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- 'is_reserved' => array(
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Reserved') ,
- 'description' => 'Is this membership_status reserved.',
+ 'title' => ts('Is Reserved'),
+ 'description' => ts('Is this membership_status reserved.'),
+ 'where' => 'civicrm_membership_status.is_reserved',
+ 'default' => '0',
'table_name' => 'civicrm_membership_status',
'entity' => 'MembershipStatus',
'bao' => 'CRM_Member_BAO_MembershipStatus',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -386,10 +411,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_status', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_status', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -397,15 +423,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_status', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_status', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/DAO/MembershipType.php b/CRM/Member/DAO/MembershipType.php
index b0e32cc43bd1..c777c9a2e37e 100644
--- a/CRM/Member/DAO/MembershipType.php
+++ b/CRM/Member/DAO/MembershipType.php
@@ -1,521 +1,572 @@
__table = 'civicrm_membership_type';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'member_of_contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'member_of_contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type ID') ,
- 'description' => 'Membership Id',
- 'required' => true,
+ 'title' => ts('Membership Type ID'),
+ 'description' => ts('Membership Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Domain') ,
- 'description' => 'Which Domain is this match entry for',
- 'required' => true,
+ 'title' => ts('Membership Type Domain'),
+ 'description' => ts('Which Domain is this match entry for'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.domain_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'membership_type' => array(
+ ]
+ ],
+ 'membership_type' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type') ,
- 'description' => 'Name of Membership Type',
+ 'title' => ts('Membership Type'),
+ 'description' => ts('Name of Membership Type'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
- 'import' => true,
+ 'import' => TRUE,
'where' => 'civicrm_membership_type.name',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 1,
- ) ,
- 'description' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Name"),
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Description') ,
- 'description' => 'Description of Membership Type',
+ 'title' => ts('Membership Type Description'),
+ 'description' => ts('Description of Membership Type'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.description',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'member_of_contact_id' => array(
+ 'label' => ts("Description"),
+ ],
+ ],
+ 'member_of_contact_id' => [
'name' => 'member_of_contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Organization') ,
- 'description' => 'Owner organization for this membership type. FK to Contact ID',
- 'required' => true,
+ 'title' => ts('Membership Type Organization'),
+ 'description' => ts('Owner organization for this membership type. FK to Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.member_of_contact_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- ) ,
- 'financial_type_id' => array(
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Financial Type') ,
- 'description' => 'If membership is paid by a contribution - what financial type should be used. FK to civicrm_financial_type.id',
- 'required' => true,
+ 'title' => ts('Membership Financial Type'),
+ 'description' => ts('If membership is paid by a contribution - what financial type should be used. FK to civicrm_financial_type.id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_membership_type.financial_type_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'minimum_fee' => array(
+ ]
+ ],
+ 'minimum_fee' => [
'name' => 'minimum_fee',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('membership Type Minimum Fee') ,
- 'description' => 'Minimum fee for this membership (0 for free/complimentary memberships).',
- 'precision' => array(
- 20,
- 2
- ) ,
+ 'title' => ts('Membership Type Minimum Fee'),
+ 'description' => ts('Minimum fee for this membership (0 for free/complimentary memberships).'),
+ 'precision' => [
+ 18,
+ 9
+ ],
+ 'where' => 'civicrm_membership_type.minimum_fee',
+ 'default' => '0',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'duration_unit' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Minimum Fee"),
+ ],
+ ],
+ 'duration_unit' => [
'name' => 'duration_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Duration Unit') ,
- 'description' => 'Unit in which membership period is expressed.',
+ 'title' => ts('Membership Type Duration Unit'),
+ 'description' => ts('Unit in which membership period is expressed.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_type.duration_unit',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::membershipTypeUnitList',
- )
- ) ,
- 'duration_interval' => array(
+ ]
+ ],
+ 'duration_interval' => [
'name' => 'duration_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type Duration Interval') ,
- 'description' => 'Number of duration units in membership period (e.g. 1 year, 12 months).',
+ 'title' => ts('Membership Type Duration Interval'),
+ 'description' => ts('Number of duration units in membership period (e.g. 1 year, 12 months).'),
+ 'where' => 'civicrm_membership_type.duration_interval',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'period_type' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'period_type' => [
'name' => 'period_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Plan') ,
- 'description' => 'Rolling membership period starts on signup date. Fixed membership periods start on fixed_period_start_day.',
+ 'title' => ts('Membership Type Plan'),
+ 'description' => ts('Rolling membership period starts on signup date. Fixed membership periods start on fixed_period_start_day.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_membership_type.period_type',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'html' => [
+ 'type' => 'Select',
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::periodType',
- )
- ) ,
- 'fixed_period_start_day' => array(
+ ]
+ ],
+ 'fixed_period_start_day' => [
'name' => 'fixed_period_start_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Fixed Period Start Day') ,
- 'description' => 'For fixed period memberships, month and day (mmdd) on which subscription/membership will start. Period start is back-dated unless after rollover day.',
+ 'title' => ts('Fixed Period Start Day'),
+ 'description' => ts('For fixed period memberships, month and day (mmdd) on which subscription/membership will start. Period start is back-dated unless after rollover day.'),
+ 'where' => 'civicrm_membership_type.fixed_period_start_day',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'fixed_period_rollover_day' => array(
+ ],
+ 'fixed_period_rollover_day' => [
'name' => 'fixed_period_rollover_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Fixed Period Rollover Day') ,
- 'description' => 'For fixed period memberships, signups after this day (mmdd) rollover to next period.',
+ 'title' => ts('Fixed Period Rollover Day'),
+ 'description' => ts('For fixed period memberships, signups after this day (mmdd) rollover to next period.'),
+ 'where' => 'civicrm_membership_type.fixed_period_rollover_day',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'relationship_type_id' => array(
+ ],
+ 'relationship_type_id' => [
'name' => 'relationship_type_id',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Relationship') ,
- 'description' => 'FK to Relationship Type ID',
+ 'title' => ts('Membership Type Relationship'),
+ 'description' => ts('FK to Relationship Type ID'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_membership_type.relationship_type_id',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'relationship_direction' => array(
+ ],
+ 'relationship_direction' => [
'name' => 'relationship_direction',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Relationship Direction') ,
+ 'title' => ts('Relationship Direction'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.relationship_direction',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'max_related' => array(
+ ],
+ 'max_related' => [
'name' => 'max_related',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Related Members for Type') ,
- 'description' => 'Maximum number of related memberships.',
+ 'title' => ts('Max Related Members for Type'),
+ 'description' => ts('Maximum number of related memberships.'),
+ 'where' => 'civicrm_membership_type.max_related',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'visibility' => array(
+ 'html' => [
+ 'type' => 'Text',
+ 'label' => ts("Max Related"),
+ ],
+ ],
+ 'visibility' => [
'name' => 'visibility',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Visible') ,
+ 'title' => ts('Visible'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_membership_type.visibility',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::memberVisibility',
- )
- ) ,
- 'weight' => array(
+ ]
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
+ 'title' => ts('Order'),
+ 'where' => 'civicrm_membership_type.weight',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- 'receipt_text_signup' => array(
+ 'html' => [
+ 'type' => 'Text',
+ ],
+ ],
+ 'receipt_text_signup' => [
'name' => 'receipt_text_signup',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Receipt Text') ,
- 'description' => 'Receipt Text for membership signup',
+ 'title' => ts('Membership Type Receipt Text'),
+ 'description' => ts('Receipt Text for membership signup'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.receipt_text_signup',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'receipt_text_renewal' => array(
+ ],
+ ],
+ 'receipt_text_renewal' => [
'name' => 'receipt_text_renewal',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Membership Type Renewal Text') ,
- 'description' => 'Receipt Text for membership renewal',
+ 'title' => ts('Membership Type Renewal Text'),
+ 'description' => ts('Receipt Text for membership renewal'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_membership_type.receipt_text_renewal',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'auto_renew' => array(
+ ],
+ ],
+ 'auto_renew' => [
'name' => 'auto_renew',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Auto Renew') ,
- 'description' => '0 = No auto-renew option; 1 = Give option, but not required; 2 = Auto-renew required;',
+ 'title' => ts('Auto Renew'),
+ 'description' => ts('0 = No auto-renew option; 1 = Give option, but not required; 2 = Auto-renew required;'),
+ 'where' => 'civicrm_membership_type.auto_renew',
+ 'default' => '0',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'html' => [
+ 'type' => 'Radio',
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Core_SelectValues::memberAutoRenew',
- )
- ) ,
- 'is_active' => array(
+ ]
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Active') ,
- 'description' => 'Is this membership_type enabled',
+ 'title' => ts('Is Active'),
+ 'description' => ts('Is this membership_type enabled'),
+ 'where' => 'civicrm_membership_type.is_active',
'default' => '1',
'table_name' => 'civicrm_membership_type',
'entity' => 'MembershipType',
'bao' => 'CRM_Member_BAO_MembershipType',
'localizable' => 0,
- ) ,
- );
+ 'html' => [
+ 'type' => 'CheckBox',
+ 'label' => ts("Enabled?"),
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -523,10 +574,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_type', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'membership_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -534,24 +586,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_type', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'membership_type', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_relationship_type_id' => array(
+ $indices = [
+ 'index_relationship_type_id' => [
'name' => 'index_relationship_type_id',
- 'field' => array(
+ 'field' => [
0 => 'relationship_type_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_membership_type::0::relationship_type_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Member/Form.php b/CRM/Member/Form.php
index d6f526fef95e..3bd495fefefd 100644
--- a/CRM/Member/Form.php
+++ b/CRM/Member/Form.php
@@ -1,9 +1,9 @@
statusMessage[] = $message;
+ }
+
+ /**
+ * Get the status message.
+ *
+ * @return string
+ */
+ protected function getStatusMessage() {
+ return implode(' ', $this->statusMessage);
+ }
+
/**
* Values submitted to the form, processed along the way.
*
* @var array
*/
- protected $_params = array();
+ protected $_params = [];
+
+ /**
+ * Fields for the entity to be assigned to the template.
+ *
+ * Fields may have keys
+ * - name (required to show in tpl from the array)
+ * - description (optional, will appear below the field)
+ * - not-auto-addable - this class will not attempt to add the field using addField.
+ * (this will be automatically set if the field does not have html in it's metadata
+ * or is not a core field on the form's entity).
+ * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * - is_freeze (field should be frozen).
+ *
+ * @var array
+ */
+ protected $entityFields = [];
public function preProcess() {
// Check for edit permission.
@@ -102,16 +151,16 @@ public function preProcess() {
}
parent::preProcess();
- $params = array();
- $params['context'] = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'membership');
+ $params = [];
+ $params['context'] = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
$params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $params['mode'] = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $params['mode'] = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
$this->setContextVariables($params);
$this->assign('context', $this->_context);
$this->assign('membershipMode', $this->_mode);
- $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, array(), TRUE);
+ $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, [], TRUE);
foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
if ($membershipType['auto_renew']) {
$this->_recurMembershipTypes[$index] = $membershipType;
@@ -129,9 +178,9 @@ public function preProcess() {
* defaults
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Member_BAO_Membership::retrieve($params, $defaults);
if (isset($defaults['minimum_fee'])) {
$defaults['minimum_fee'] = CRM_Utils_Money::format($defaults['minimum_fee'], NULL, '%a');
@@ -140,6 +189,13 @@ public function setDefaultValues() {
if (isset($defaults['status'])) {
$this->assign('membershipStatus', $defaults['status']);
}
+
+ if (!empty($defaults['is_override'])) {
+ $defaults['is_override'] = CRM_Member_StatusOverrideTypes::PERMANENT;
+ }
+ if (!empty($defaults['status_override_end_date'])) {
+ $defaults['is_override'] = CRM_Member_StatusOverrideTypes::UNTIL_DATE;
+ }
}
if ($this->_action & CRM_Core_Action::ADD) {
@@ -157,7 +213,7 @@ public function setDefaultValues() {
$this->_memType = $defaults['membership_type_id'];
}
if (is_numeric($this->_memType)) {
- $defaults['membership_type_id'] = array();
+ $defaults['membership_type_id'] = [];
$defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
$this->_memType,
'member_of_contact_id',
@@ -175,14 +231,9 @@ public function setDefaultValues() {
* Build the form object.
*/
public function buildQuickForm() {
+ $this->assignSalesTaxMetadataToTemplate();
- if ($this->_mode) {
- $this->add('select', 'payment_processor_id',
- ts('Payment Processor'),
- $this->_processors, TRUE,
- array('onChange' => "buildAutoRenew( null, this.value, '{$this->_mode}');")
- );
- }
+ $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
// Build the form for auto renew. This is displayed when in credit card mode or update mode.
// The reason for showing it in update mode is not that clear.
@@ -192,7 +243,7 @@ public function buildQuickForm() {
}
$autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
- NULL, array('onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );")
+ NULL, ['onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );"]
);
if ($this->_action & CRM_Core_Action::UPDATE) {
$autoRenewElement->freeze();
@@ -208,48 +259,48 @@ public function buildQuickForm() {
$this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
if ($this->_action & CRM_Core_Action::RENEW) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Renew'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
elseif ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
else {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
@@ -304,13 +355,13 @@ public function storeContactFields($formValues) {
* @param array $params
*/
protected function setContextVariables($params) {
- $variables = array(
+ $variables = [
'action' => '_action',
'context' => '_context',
'id' => '_id',
'cid' => '_contactID',
'mode' => '_mode',
- );
+ ];
foreach ($variables as $paramKey => $classVar) {
if (isset($params[$paramKey]) && !isset($this->$classVar)) {
$this->$classVar = $params[$paramKey];
@@ -337,7 +388,7 @@ protected function setContextVariables($params) {
*/
protected function processRecurringContribution($paymentParams) {
$membershipID = $paymentParams['membership_type_id'][1];
- $contributionRecurParams = array(
+ $contributionRecurParams = [
'contact_id' => $paymentParams['contactID'],
'amount' => $paymentParams['total_amount'],
'contribution_status_id' => 'Pending',
@@ -347,18 +398,18 @@ protected function processRecurringContribution($paymentParams) {
'is_email_receipt' => $paymentParams['is_email_receipt'],
'payment_instrument_id' => $paymentParams['payment_instrument_id'],
'invoice_id' => $paymentParams['invoice_id'],
- );
+ ];
- $mapping = array(
+ $mapping = [
'frequency_interval' => 'duration_interval',
'frequency_unit' => 'duration_unit',
- );
- $membershipType = civicrm_api3('MembershipType', 'getsingle', array(
+ ];
+ $membershipType = civicrm_api3('MembershipType', 'getsingle', [
'id' => $membershipID,
'return' => $mapping,
- ));
+ ]);
- $returnParams = array('is_recur' => TRUE);
+ $returnParams = ['is_recur' => TRUE];
foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
$contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
$returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
diff --git a/CRM/Member/Form/Membership.php b/CRM/Member/Form/Membership.php
index e6f5c984ee69..ec39152a4418 100644
--- a/CRM/Member/Form/Membership.php
+++ b/CRM/Member/Form/Membership.php
@@ -1,9 +1,9 @@
entityFields = [
+ 'join_date' => [
+ 'name' => 'join_date',
+ 'description' => ts('Member Since'),
+ ],
+ 'start_date' => [
+ 'name' => 'start_date',
+ 'description' => ts('Start Date'),
+ ],
+ 'end_date' => [
+ 'name' => 'end_date',
+ 'description' => ts('End Date'),
+ ],
+ ];
+ }
/**
- * An array to hold a list of date fields on the form
- * so that they can be converted to ISO in a consistent manner
+ * Set the delete message.
*
- * @var array
+ * We do this from the constructor in order to do a translation.
*/
- protected $_dateFields = array(
- 'receive_date' => array('default' => 'now'),
- );
+ public function setDeleteMessage() {
+ $this->deleteMessage = ''
+ . ts("WARNING: Deleting this membership will also delete any related payment (contribution) records." . ts("This action cannot be undone.")
+ . '
'
+ . ts("Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.")
+ . '
'
+ . ts("Click 'Delete' if you want to continue.") . '
');
+ }
+
+ /**
+ * Overriding this entity trait function as not yet tested.
+ *
+ * We continue to rely on legacy handling.
+ */
+ public function addCustomDataToForm() {}
+
+ /**
+ * Overriding this entity trait function as not yet tested.
+ *
+ * We continue to rely on legacy handling.
+ */
+ public function addFormButtons() {}
/**
* Get selected membership type from the form values.
@@ -120,10 +160,10 @@ class CRM_Member_Form_Membership extends CRM_Member_Form {
* @return array
*/
public static function getSelectedMemberships($priceSet, $params) {
- $memTypeSelected = array();
+ $memTypeSelected = [];
$priceFieldIDS = self::getPriceFieldIDs($params, $priceSet);
if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
- $memTypeSelected = array($params['membership_type_id'][1] => $params['membership_type_id'][1]);
+ $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
}
else {
foreach ($priceFieldIDS as $priceFieldId) {
@@ -144,7 +184,7 @@ public static function getSelectedMemberships($priceSet, $params) {
* @return array
*/
public static function getPriceFieldIDs($params, $priceSet) {
- $priceFieldIDS = array();
+ $priceFieldIDS = [];
if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
foreach ($priceSet['fields'] as $fieldId => $field) {
if (!empty($params['price_' . $fieldId])) {
@@ -173,6 +213,9 @@ public function preProcess() {
// This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
$this->assign('formClass', 'membership');
parent::preProcess();
+ if ($this->isUpdateToExistingRecurringMembership()) {
+ $this->entityFields['end_date']['is_freeze'] = TRUE;
+ }
// get price set id.
$this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
$this->set('priceSetId', $this->_priceSetId);
@@ -189,16 +232,16 @@ public function preProcess() {
if ($this->_action & CRM_Core_Action::ADD) {
if ($this->_contactID) {
//check whether contact has a current membership so we can alert user that they may want to do a renewal instead
- $contactMemberships = array();
- $memParams = array('contact_id' => $this->_contactID);
+ $contactMemberships = [];
+ $memParams = ['contact_id' => $this->_contactID];
CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
- $cMemTypes = array();
+ $cMemTypes = [];
foreach ($contactMemberships as $mem) {
$cMemTypes[] = $mem['membership_type_id'];
}
if (count($cMemTypes) > 0) {
$memberorgs = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($cMemTypes);
- $mems_by_org = array();
+ $mems_by_org = [];
foreach ($contactMemberships as $mem) {
$mem['member_of_contact_id'] = CRM_Utils_Array::value($mem['membership_type_id'], $memberorgs);
if (!empty($mem['membership_end_date'])) {
@@ -228,12 +271,12 @@ public function preProcess() {
// In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
$resources = CRM_Core_Resources::singleton();
$resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
- $passthru = array(
+ $passthru = [
'typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(),
'memtypes' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'membership_type_id'),
'statuses' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'status_id'),
- );
- $resources->addSetting(array('existingMems' => $passthru));
+ ];
+ $resources->addSetting(['existingMems' => $passthru]);
}
}
@@ -243,12 +286,9 @@ public function preProcess() {
$this->_memType = $params['membership_type_id'][1];
}
}
- // when custom data is included in this page
- if (!empty($_POST['hidden_custom'])) {
- CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_memType, 1, 'Membership', $this->_id);
- CRM_Custom_Form_CustomData::buildQuickForm($this);
- CRM_Custom_Form_CustomData::setDefaultValues($this);
- }
+
+ // Add custom data to form
+ CRM_Custom_Form_CustomData::addToForm($this, $this->_memType);
// CRM-4395, get the online pending contribution id.
$this->_onlinePendingContributionId = NULL;
@@ -274,10 +314,8 @@ public function setDefaultValues() {
$defaults = parent::setDefaultValues();
//setting default join date and receive date
- list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
if ($this->_action == CRM_Core_Action::ADD) {
- $defaults['receive_date'] = $now;
- $defaults['receive_date_time'] = $currentTime;
+ $defaults['receive_date'] = date('Y-m-d H:i:s');
}
$defaults['num_terms'] = 1;
@@ -305,8 +343,8 @@ public function setDefaultValues() {
$defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
if (!empty($defaults['record_contribution']) && !$this->_mode) {
- $contributionParams = array('id' => $defaults['record_contribution']);
- $contributionIds = array();
+ $contributionParams = ['id' => $defaults['record_contribution']];
+ $contributionIds = [];
//keep main object campaign in hand.
$memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults);
@@ -316,10 +354,6 @@ public function setDefaultValues() {
//get back original object campaign id.
$defaults['campaign_id'] = $memberCampaignId;
- if (!empty($defaults['receive_date'])) {
- list($defaults['receive_date']) = CRM_Utils_Date::setDateDefaults($defaults['receive_date']);
- }
-
// Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
if (!empty($defaults['membership_source'])) {
$defaults['source'] = $defaults['membership_source'];
@@ -366,16 +400,9 @@ public function setDefaultValues() {
// $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
}
- $dates = array('join_date', 'start_date', 'end_date');
- foreach ($dates as $key) {
- if (!empty($defaults[$key])) {
- list($defaults[$key]) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults));
- }
- }
-
//setting default join date if there is no join date
if (empty($defaults['join_date'])) {
- $defaults['join_date'] = $now;
+ $defaults['join_date'] = date('Y-m-d');
}
if (!empty($defaults['membership_end_date'])) {
@@ -390,14 +417,9 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
- $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
-
+ $this->buildQuickEntityForm();
$this->assign('currency', CRM_Core_Config::singleton()->defaultCurrencySymbol);
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
- if (isset($invoicing)) {
- $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
- }
+ $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
// build price set form.
$buildPriceSet = FALSE;
if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
@@ -413,7 +435,7 @@ public function buildQuickForm() {
$this->set('priceSetId', $this->_priceSetId);
CRM_Price_BAO_PriceSet::buildPriceSet($this);
- $optionsMembershipTypes = array();
+ $optionsMembershipTypes = [];
foreach ($this->_priceSet['fields'] as $pField) {
if (empty($pField['options'])) {
continue;
@@ -446,41 +468,36 @@ public function buildQuickForm() {
if ($buildPriceSet) {
$this->add('select', 'price_set_id', ts('Choose price set'),
- array(
+ [
'' => ts('Choose price set'),
- ) + $priceSets,
- NULL, array('onchange' => "buildAmount( this.value );")
+ ] + $priceSets,
+ NULL, ['onchange' => "buildAmount( this.value );"]
);
}
$this->assign('hasPriceSets', $buildPriceSet);
}
- //need to assign custom data type and subtype to the template
- $this->assign('customDataType', 'Membership');
- $this->assign('customDataSubType', $this->_memType);
- $this->assign('entityID', $this->_id);
-
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
return;
}
if ($this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Contact'), array(
+ $this->addEntityRef('contact_id', ts('Contact'), [
'create' => TRUE,
- 'api' => array('extra' => array('email')),
- ), TRUE);
+ 'api' => ['extra' => ['email']],
+ ], TRUE);
}
$selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
@@ -492,7 +509,7 @@ public function buildQuickForm() {
CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
}
// retrieve all memberships
- $allMembershipInfo = array();
+ $allMembershipInfo = [];
foreach ($this->allMembershipTypeDetails as $key => $values) {
if ($this->_mode && empty($values['minimum_fee'])) {
continue;
@@ -520,14 +537,14 @@ public function buildQuickForm() {
// build membership info array, which is used when membership type is selected to:
// - set the payment information block
// - set the max related block
- $allMembershipInfo[$key] = array(
+ $allMembershipInfo[$key] = [
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
'total_amount_numeric' => $totalAmount,
'auto_renew' => CRM_Utils_Array::value('auto_renew', $values),
'has_related' => isset($values['relationship_type_id']),
'max_related' => CRM_Utils_Array::value('max_related', $values),
- );
+ ];
}
$this->assign('allMembershipInfo', json_encode($allMembershipInfo));
@@ -544,12 +561,12 @@ public function buildQuickForm() {
$selOrgMemType[$index] = $orgMembershipType;
}
- $memTypeJs = array(
+ $memTypeJs = [
'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
- );
+ ];
if (!empty($this->_recurPaymentProcessors)) {
- $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . "buildAutoRenew(this.value, null, '{$this->_mode}');";
+ $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
}
$this->add('text', 'max_related', ts('Max related'),
@@ -562,23 +579,13 @@ public function buildQuickForm() {
$memTypeJs
);
- $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
- $elements = array();
- if ($sel) {
- $elements[] = $sel;
+ $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
+ if ($isUpdateToExistingRecurringMembership) {
+ $sel->freeze();
}
- $this->applyFilter('__ALL__', 'trim');
-
if ($this->_action & CRM_Core_Action::ADD) {
- $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
- }
-
- $this->addDate('join_date', ts('Member Since'), FALSE, array('formatType' => 'activityDate'));
- $this->addDate('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDate'));
- $endDate = $this->addDate('end_date', ts('End Date'), FALSE, array('formatType' => 'activityDate'));
- if ($endDate) {
- $elements[] = $endDate;
+ $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
}
$this->add('text', 'source', ts('Source'),
@@ -594,35 +601,37 @@ public function buildQuickForm() {
if (!$this->_mode) {
$this->add('select', 'status_id', ts('Membership Status'),
- array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
+ ['' => ts('- select -')] + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
);
- $statusOverride = $this->addElement('checkbox', 'is_override',
- ts('Status Override?'), NULL,
- array('onClick' => 'showHideMemberStatus()')
+
+ $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
+ CRM_Member_StatusOverrideTypes::getSelectOptions()
);
- if ($statusOverride) {
- $elements[] = $statusOverride;
+ if ($statusOverride && $isUpdateToExistingRecurringMembership) {
+ $statusOverride->freeze();
}
+ $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => time(), 'time' => FALSE]);
+
$this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
$this->add('text', 'total_amount', ts('Amount'));
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
- $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
$this->add('select', 'payment_instrument_id',
ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
- FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
);
$this->add('text', 'trxn_id', ts('Transaction ID'));
$this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
- 'objectExists', array(
+ 'objectExists', [
'CRM_Contribute_DAO_Contribution',
$this->_id,
'trxn_id',
- )
+ ]
);
$this->add('select', 'contribution_status_id',
@@ -638,18 +647,18 @@ public function buildQuickForm() {
}
$this->add('select', 'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
+ ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
);
$this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
- $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
- $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
+ $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
+ $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
$this->addElement('checkbox',
'send_receipt',
ts('Send Confirmation and Receipt?'), NULL,
- array('onclick' => "showEmailOptions()")
+ ['onclick' => "showEmailOptions()"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
@@ -666,26 +675,15 @@ public function buildQuickForm() {
$this->assign('displayName', $this->_memberDisplayName);
}
- $isRecur = FALSE;
- if ($this->_action & CRM_Core_Action::UPDATE) {
- $recurContributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id,
- 'contribution_recur_id'
+ if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
+ $this->assign('cancelAutoRenew',
+ CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
);
- if ($recurContributionId && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id)) {
- $isRecur = TRUE;
- if (CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
- $this->assign('cancelAutoRenew',
- CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
- );
- }
- foreach ($elements as $elem) {
- $elem->freeze();
- }
- }
}
- $this->assign('isRecur', $isRecur);
- $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
+ $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
+
+ $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
$mailingInfo = Civi::settings()->get('mailing_backend');
$this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
@@ -706,7 +704,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
$priceSetId = self::getPriceSetID($params);
$priceSetDetails = self::getPriceSetDetails($params);
@@ -812,18 +810,22 @@ public static function formRule($params, $files, $self) {
if ($membershipDetails['duration_unit'] == 'lifetime') {
// Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
// process to update status based on end-date. The user must change the status now.
- $result = civicrm_api3('MembershipStatus', 'get', array(
+ $result = civicrm_api3('MembershipStatus', 'get', [
'sequential' => 1,
'is_current_member' => 0,
- ));
+ ]);
$tmp_statuses = $result['values'];
- $status_ids = array();
+ $status_ids = [];
foreach ($tmp_statuses as $cur_stat) {
$status_ids[] = $cur_stat['id'];
}
+
if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
$errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
- $errors['is_override'] = ts('This must be checked because you set an End Date for a lifetime membership');
+ }
+
+ if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes::isPermanent($params['is_override'])) {
+ $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
}
}
else {
@@ -855,7 +857,7 @@ public static function formRule($params, $files, $self) {
}
//CRM-3724, check for availability of valid membership status.
- if (empty($params['is_override']) && !isset($errors['_qf_default'])) {
+ if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
$calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
$endDate,
$joinDate,
@@ -867,9 +869,9 @@ public static function formRule($params, $files, $self) {
if (empty($calcStatus)) {
$url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
$errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
- $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can Configure Membership Status Rules.', array(1 => $url));
+ $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can Configure Membership Status Rules.', [1 => $url]);
if (!$self->_mode) {
- $status .= ' ' . ts('OR You can sign up by setting Status Override? to true.');
+ $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
}
CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
}
@@ -880,10 +882,14 @@ public static function formRule($params, $files, $self) {
$errors['join_date'] = ts('Please enter the Member Since.');
}
- if (isset($params['is_override']) &&
- $params['is_override'] && empty($params['status_id'])
- ) {
- $errors['status_id'] = ts('Please enter the status.');
+ if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isOverridden($params['is_override']) && empty($params['status_id'])) {
+ $errors['status_id'] = ts('Please enter the Membership status.');
+ }
+
+ if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isUntilDate($params['is_override'])) {
+ if (empty($params['status_override_end_date'])) {
+ $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
+ }
}
//total amount condition arise when membership type having no
@@ -916,59 +922,71 @@ public function postProcess() {
}
// get the submitted form values.
$this->_params = $this->controller->exportValues($this->_name);
+ $this->prepareStatusOverrideValues();
$this->submit();
$this->setUserContext();
}
+ /**
+ * Prepares the values related to status override.
+ */
+ private function prepareStatusOverrideValues() {
+ $this->setOverrideDateValue();
+ $this->convertIsOverrideValue();
+ }
+
+ /**
+ * Sets status override end date to empty value if
+ * the selected override option is not 'until date'.
+ */
+ private function setOverrideDateValue() {
+ if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
+ $this->_params['status_override_end_date'] = '';
+ }
+ }
+
+ /**
+ * Convert the value of selected (status override?)
+ * option to TRUE if it indicate an overridden status
+ * or FALSE otherwise.
+ */
+ private function convertIsOverrideValue() {
+ $this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override']);
+ }
+
/**
* Send email receipt.
*
+ * @deprecated
+ * This function is shared with Batch_Entry which has limited overlap
+ * & needs rationalising.
+ *
* @param CRM_Core_Form $form
* Form object.
* @param array $formValues
* @param object $membership
* Object.
+ * @param array $customValues
*
* @return bool
* true if mail was sent successfully
*/
- public static function emailReceipt(&$form, &$formValues, &$membership) {
+ public static function emailReceipt(&$form, &$formValues, &$membership, $customValues = NULL) {
// retrieve 'from email id' for acknowledgement
- $receiptFrom = $formValues['from_email_address'];
+ $receiptFrom = CRM_Utils_Array::value('from_email_address', $formValues);
+ // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
if (!empty($formValues['payment_instrument_id'])) {
$paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
$formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
}
- // retrieve custom data
- $customFields = $customValues = array();
- if (property_exists($form, '_groupTree')
- && !empty($form->_groupTree)
- ) {
- foreach ($form->_groupTree as $groupID => $group) {
- if ($groupID == 'info') {
- continue;
- }
- foreach ($group['fields'] as $k => $field) {
- $field['title'] = $field['label'];
- $customFields["custom_{$k}"] = $field;
- }
- }
- }
-
- $members = array(array('member_id', '=', $membership->id, 0, 0));
- // check whether its a test drive
- if ($form->_mode == 'test') {
- $members[] = array('member_test', '=', 1, 0, 0);
- }
-
- CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
$form->assign('customValues', $customValues);
if ($form->_mode) {
+ // @todo move this outside shared code as Batch entry just doesn't
$form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
$form->_params,
$form->_bltID
@@ -1010,7 +1028,7 @@ public static function emailReceipt(&$form, &$formValues, &$membership) {
else {
$form->assign('receiptType', 'membership signup');
}
- $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues)));
+ $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
$form->assign('formValues', $formValues);
if (empty($lineItem)) {
@@ -1021,6 +1039,7 @@ public static function emailReceipt(&$form, &$formValues, &$membership) {
$form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
}
+ // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
$isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail)) || $isBatchProcess) {
// in this case the form is being called statically from the batch editing screen
@@ -1034,6 +1053,7 @@ public static function emailReceipt(&$form, &$formValues, &$membership) {
$form->_receiptContactId = $formValues['contact_id'];
}
}
+ // @todo determine isEmailPdf in calling function.
$template = CRM_Core_Smarty::singleton();
$taxAmt = $template->get_template_vars('dataArray');
$eventTaxAmt = $template->get_template_vars('totalTaxAmount');
@@ -1047,7 +1067,7 @@ public static function emailReceipt(&$form, &$formValues, &$membership) {
}
list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_membership',
'valueName' => 'membership_offline_receipt',
'contactId' => $form->_receiptContactId,
@@ -1058,7 +1078,7 @@ public static function emailReceipt(&$form, &$formValues, &$membership) {
'isEmailPdf' => $isEmailPdf,
'contributionId' => $formValues['contribution_id'],
'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
- )
+ ]
);
return TRUE;
@@ -1068,26 +1088,21 @@ public static function emailReceipt(&$form, &$formValues, &$membership) {
* Submit function.
*
* This is also accessed by unit tests.
- *
- * @return array
*/
public function submit() {
$isTest = ($this->_mode == 'test') ? 1 : 0;
$this->storeContactFields($this->_params);
$this->beginPostProcess();
- $formValues = $this->_params;
$joinDate = $startDate = $endDate = NULL;
- $membershipTypes = $membership = $calcDate = array();
+ $membershipTypes = $membership = $calcDate = [];
$membershipType = NULL;
$paymentInstrumentID = $this->_paymentProcessor['object']->getPaymentInstrumentID();
+ $params = $softParams = $ids = [];
$mailSend = FALSE;
- $formValues = $this->setPriceSetParameters($formValues);
- $params = $softParams = $ids = array();
-
- $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
- $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$this->processBillingAddress();
+ $formValues = $this->_params;
+ $formValues = $this->setPriceSetParameters($formValues);
if ($this->_id) {
$ids['membership'] = $params['id'] = $this->_id;
@@ -1109,10 +1124,7 @@ public function submit() {
$config = CRM_Core_Config::singleton();
- // @todo this is no longer required if we convert some date fields.
- $this->convertDateFieldsToMySQL($formValues);
-
- $membershipTypeValues = array();
+ $membershipTypeValues = [];
foreach ($this->_memTypeSelected as $memType) {
$membershipTypeValues[$memType]['membership_type_id'] = $memType;
}
@@ -1120,15 +1132,15 @@ public function submit() {
//take the required membership recur values.
if ($this->_mode && !empty($formValues['auto_renew'])) {
$params['is_recur'] = $formValues['is_recur'] = TRUE;
- $mapping = array(
+ $mapping = [
'frequency_interval' => 'duration_interval',
'frequency_unit' => 'duration_unit',
- );
+ ];
$count = 0;
foreach ($this->_memTypeSelected as $memType) {
$recurMembershipTypeValues = CRM_Utils_Array::value($memType,
- $this->_recurMembershipTypes, array()
+ $this->_recurMembershipTypes, []
);
foreach ($mapping as $mapVal => $mapParam) {
$membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam,
@@ -1146,9 +1158,9 @@ public function submit() {
$isQuickConfig = $this->_priceSet['is_quick_config'];
- $termsByType = array();
+ $termsByType = [];
- $lineItem = array($this->_priceSetId => array());
+ $lineItem = [$this->_priceSetId => []];
CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
$formValues, $lineItem[$this->_priceSetId], NULL, $this->_priceSetId);
@@ -1157,7 +1169,6 @@ public function submit() {
$params['tax_amount'] = $formValues['tax_amount'];
}
$params['total_amount'] = CRM_Utils_Array::value('amount', $formValues);
- $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
if (!empty($lineItem[$this->_priceSetId])) {
foreach ($lineItem[$this->_priceSetId] as &$li) {
if (!empty($li['membership_type_id'])) {
@@ -1169,6 +1180,7 @@ public function submit() {
///CRM-11529 for quick config backoffice transactions
//when financial_type_id is passed in form, update the
//lineitems with the financial type selected in form
+ $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
if ($isQuickConfig && $submittedFinancialType) {
$li['financial_type_id'] = $submittedFinancialType;
}
@@ -1177,12 +1189,13 @@ public function submit() {
$params['contact_id'] = $this->_contactID;
- $fields = array(
+ $fields = [
'status_id',
'source',
'is_override',
+ 'status_override_end_date',
'campaign_id',
- );
+ ];
foreach ($fields as $f) {
$params[$f] = CRM_Utils_Array::value($f, $formValues);
@@ -1196,29 +1209,18 @@ public function submit() {
}
// process date params to mysql date format.
- $dateTypes = array(
+ $dateTypes = [
'join_date' => 'joinDate',
'start_date' => 'startDate',
'end_date' => 'endDate',
- );
- $dateModified = FALSE;
+ ];
foreach ($dateTypes as $dateField => $dateVariable) {
- if (!empty($params['id'])) {
- $membershipDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['id'], $dateField, 'id');
- if ($membershipDate != date('Y-m-d', strtotime($formValues[$dateField]))) {
- $dateModified = TRUE;
- }
- }
$$dateVariable = CRM_Utils_Date::processDate($formValues[$dateField]);
}
- //skip status calculation on update if none of the dates are modified.
- if (!empty($params['id']) && empty($params['is_override']) && !$dateModified) {
- $params['skipStatusCal'] = TRUE;
- }
$memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
- $calcDates = array();
+ $calcDates = [];
foreach ($this->_memTypeSelected as $memType) {
if (empty($memTypeNumTerms)) {
$memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
@@ -1240,9 +1242,9 @@ public function submit() {
}
}
- // max related memberships - take from form or inherit from membership type
foreach ($this->_memTypeSelected as $memType) {
if (array_key_exists('max_related', $formValues)) {
+ // max related memberships - take from form or inherit from membership type
$membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
}
$membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
@@ -1267,8 +1269,11 @@ public function submit() {
$softParams['contact_id'] = $this->_contactID;
}
}
+
+ $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
+
if (!empty($formValues['record_contribution'])) {
- $recordContribution = array(
+ $recordContribution = [
'total_amount',
'financial_type_id',
'payment_instrument_id',
@@ -1279,7 +1284,7 @@ public function submit() {
'receive_date',
'card_type_id',
'pan_truncation',
- );
+ ];
foreach ($recordContribution as $f) {
$params[$f] = CRM_Utils_Array::value($f, $formValues);
@@ -1287,20 +1292,21 @@ public function submit() {
if (!$this->_onlinePendingContributionId) {
if (empty($formValues['source'])) {
- $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(
+ $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
1 => $membershipType,
2 => $userName,
- ));
+ ]);
}
else {
$params['contribution_source'] = $formValues['source'];
}
}
+ $completedContributionStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
if (empty($params['is_override']) &&
- CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Completed', $allContributionStatus)
+ CRM_Utils_Array::value('contribution_status_id', $params) != $completedContributionStatusId
) {
- $params['status_id'] = array_search('Pending', $allMemberStatus);
+ $params['status_id'] = $pendingMembershipStatusId;
$params['skipStatusCal'] = TRUE;
$params['is_pay_later'] = 1;
$this->assign('is_pay_later', 1);
@@ -1321,7 +1327,7 @@ public function submit() {
$params['lineItems'] = $lineItem;
$params['processPriceSet'] = TRUE;
}
- $createdMemberships = array();
+ $createdMemberships = [];
if ($this->_mode) {
$params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
@@ -1344,11 +1350,6 @@ public function submit() {
$params['register_date'] = date('YmdHis');
// add all the additional payment params we need
- // @todo the country & state values should be set by the call to $this->assignBillingAddress.
- $formValues["state_province-{$this->_bltID}"] = $formValues["billing_state_province-{$this->_bltID}"]
- = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
- $formValues["country-{$this->_bltID}"] = $formValues["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
-
$formValues['amount'] = $params['total_amount'];
// @todo this is a candidate for beginPostProcessFunction.
$formValues['currencyID'] = $config->defaultCurrency;
@@ -1374,6 +1375,7 @@ public function submit() {
}
// This is a candidate for shared beginPostProcess function.
+ // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
// CRM-7137 -for recurring membership,
// we do need contribution and recurring records.
@@ -1387,7 +1389,7 @@ public function submit() {
$contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
$paymentParams,
NULL,
- array(
+ [
'contact_id' => $this->_contributorContactID,
'line_item' => $lineItem,
'is_test' => $isTest,
@@ -1396,7 +1398,7 @@ public function submit() {
'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams),
'payment_instrument_id' => $paymentInstrumentID,
- ),
+ ],
$financialType,
FALSE,
$this->_bltID,
@@ -1419,16 +1421,18 @@ public function submit() {
$ids['contribution'] = $contribution->id;
$params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
}
+ $paymentStatus = NULL;
if ($params['total_amount'] > 0.0) {
$payment = $this->_paymentProcessor['object'];
try {
$result = $payment->doPayment($paymentParams);
$formValues = array_merge($formValues, $result);
+ $paymentStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
// Assign amount to template if payment was successful.
$this->assign('amount', $params['total_amount']);
}
- catch (PaymentProcessorException $e) {
+ catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
if (!empty($paymentParams['contributionID'])) {
CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID,
$e->getMessage());
@@ -1437,25 +1441,25 @@ public function submit() {
CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
}
- CRM_Core_Error::displaySessionError($result);
+ CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
- "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"
+ "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
));
}
}
- if ($formValues['payment_status_id'] != array_search('Completed', $allContributionStatus)) {
- $params['status_id'] = array_search('Pending', $allMemberStatus);
+ if ($paymentStatus !== 'Completed') {
+ $params['status_id'] = $pendingMembershipStatusId;
$params['skipStatusCal'] = TRUE;
// unset send-receipt option, since receipt will be sent when ipn is received.
unset($formValues['send_receipt'], $formValues['send_receipt']);
//as membership is pending set dates to null.
- $memberDates = array(
+ $memberDates = [
'join_date' => 'joinDate',
'start_date' => 'startDate',
'end_date' => 'endDate',
- );
+ ];
foreach ($memberDates as $dv) {
$$dv = NULL;
foreach ($this->_memTypeSelected as $memType) {
@@ -1464,10 +1468,10 @@ public function submit() {
}
}
$now = date('YmdHis');
- $params['receive_date'] = $now;
+ $params['receive_date'] = date('Y-m-d H:i:s');
$params['invoice_id'] = $formValues['invoiceID'];
$params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
- array(1 => $membershipType, 2 => $userName)
+ [1 => $membershipType, 2 => $userName]
);
$params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
$params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
@@ -1537,7 +1541,7 @@ public function submit() {
$params['componentName'] = 'contribute';
$result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
if (!empty($result) && !empty($params['contribution_id'])) {
- $lineItem = array();
+ $lineItem = [];
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution_id']);
$itemId = key($lineItems);
$priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
@@ -1573,11 +1577,11 @@ public function submit() {
//display end date w/ status message.
$endDate = $membership->end_date;
- if (!in_array($membership->status_id, array(
+ if (!in_array($membership->status_id, [
// CRM-15475
array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
array_search('Expired', CRM_Member_PseudoConstant::membershipStatus()),
- ))
+ ])
) {
$cancelled = FALSE;
}
@@ -1596,9 +1600,13 @@ public function submit() {
$membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
}
+ // @todo figure out why recieve_date isn't being set right here.
+ if (empty($params['receive_date'])) {
+ $params['receive_date'] = date('Y-m-d H:i:s');
+ }
$membershipParams = array_merge($params, $membershipTypeValues[$memType]);
if (!empty($formValues['int_amount'])) {
- $init_amount = array();
+ $init_amount = [];
foreach ($formValues as $key => $value) {
if (strstr($key, 'txt-price')) {
$init_amount[$key] = $value;
@@ -1623,6 +1631,14 @@ public function submit() {
}
}
}
+ $isRecur = CRM_Utils_Array::value('is_recur', $params);
+ if (($this->_action & CRM_Core_Action::UPDATE)) {
+ $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
+ }
+ elseif (($this->_action & CRM_Core_Action::ADD)) {
+ $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
+ $isRecur, $calcDates));
+ }
if (!empty($lineItem[$this->_priceSetId])) {
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
@@ -1643,7 +1659,7 @@ public function submit() {
}
}
if ($invoicing) {
- $dataArray = array();
+ $dataArray = [];
foreach ($lineItem[$this->_priceSetId] as $key => $value) {
if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
if (isset($dataArray[$value['tax_rate']])) {
@@ -1656,7 +1672,8 @@ public function submit() {
}
if ($taxAmount) {
$this->assign('totalTaxAmount', $totalTaxAmount);
- $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
+ // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
+ $this->assign('taxTerm', $this->getSalesTaxTerm());
}
$this->assign('dataArray', $dataArray);
}
@@ -1684,7 +1701,7 @@ public function submit() {
$formValues['receipt_text_signup'] = $formValues['receipt_text'];
// send email receipt
$this->assignBillingName();
- $mailSend = self::emailReceipt($this, $formValues, $membership);
+ $mailSend = $this->emailMembershipReceipt($formValues, $membership);
$receiptSent = TRUE;
}
@@ -1693,10 +1710,13 @@ public function submit() {
$this->_id = $membership->id;
}
- $isRecur = CRM_Utils_Array::value('is_recur', $params);
$this->updateContributionOnMembershipTypeChange($params, $membership);
- $this->setStatusMessage($membership, $endDate, $receiptSent, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend);
- return $createdMemberships;
+ if ($receiptSent && $mailSend) {
+ $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail]));
+ }
+
+ CRM_Core_Session::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
+ $this->setStatusMessage($membership);
}
/**
@@ -1711,9 +1731,12 @@ public function submit() {
*/
protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
- ($this->_action & CRM_Core_Action::UPDATE) && // on update
- $this->_id && // if ID is present
- !in_array($this->_memType, $this->_memTypeSelected) // if selected membership doesn't match with earlier membership
+ // on update
+ ($this->_action & CRM_Core_Action::UPDATE) &&
+ // if ID is present
+ $this->_id &&
+ // if selected membership doesn't match with earlier membership
+ !in_array($this->_memType, $this->_memTypeSelected)
) {
if (CRM_Utils_Array::value('is_recur', $inputParams)) {
CRM_Core_Session::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
@@ -1741,8 +1764,7 @@ protected function updateContributionOnMembershipTypeChange($inputParams, $membe
// add price field information in $inputParams
self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id);
- // paid amount
- $paidAmount = CRM_Utils_Array::value('paid', CRM_Contribute_BAO_Contribution::getPaymentInfo($membership->id, 'membership'));
+
// update related contribution and financial records
CRM_Price_BAO_LineItem::changeFeeSelections(
$inputParams,
@@ -1750,7 +1772,7 @@ protected function updateContributionOnMembershipTypeChange($inputParams, $membe
'membership',
$contributionID,
$priceSetDetails['fields'],
- $lineItems, $paidAmount
+ $lineItems
);
CRM_Core_Session::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
}
@@ -1779,6 +1801,7 @@ public static function addPriceFieldByMembershipType(&$formValues, $priceFields,
}
}
}
+
/**
* Set context in session.
*/
@@ -1810,22 +1833,17 @@ protected function setUserContext() {
*
* @param CRM_Member_BAO_Membership $membership
* @param string $endDate
- * @param bool $receiptSend
*
* @return string
*/
- protected function getStatusMessageForUpdate($membership, $endDate, $receiptSend) {
+ protected function getStatusMessageForUpdate($membership, $endDate) {
// End date can be modified by hooks, so if end date is set then use it.
$endDate = ($membership->end_date) ? $membership->end_date : $endDate;
- $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
+ $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName]);
if ($endDate && $endDate !== 'null') {
$endDate = CRM_Utils_Date::customFormat($endDate);
- $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
- }
-
- if ($receiptSend) {
- $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
+ $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
}
return $statusMsg;
}
@@ -1834,25 +1852,23 @@ protected function getStatusMessageForUpdate($membership, $endDate, $receiptSend
* Get status message for create action.
*
* @param string $endDate
- * @param bool $receiptSend
* @param array $membershipTypes
* @param array $createdMemberships
* @param bool $isRecur
* @param array $calcDates
- * @param bool $mailSent
*
* @return array|string
*/
- protected function getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
- $isRecur, $calcDates, $mailSent) {
+ protected function getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
+ $isRecur, $calcDates) {
// FIX ME: fix status messages
- $statusMsg = array();
+ $statusMsg = [];
foreach ($membershipTypes as $memType => $membershipType) {
- $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
+ $statusMsg[$memType] = ts('%1 membership for %2 has been added.', [
1 => $membershipType,
2 => $this->_memberDisplayName,
- ));
+ ]);
$membership = $createdMemberships[$memType];
$memEndDate = ($membership->end_date) ? $membership->end_date : $endDate;
@@ -1864,37 +1880,17 @@ protected function getStatusMessageForCreate($endDate, $receiptSend, $membership
if ($memEndDate && $memEndDate !== 'null') {
$memEndDate = CRM_Utils_Date::customFormat($memEndDate);
- $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
+ $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
}
}
$statusMsg = implode(' ', $statusMsg);
- if ($receiptSend && !empty($mailSent)) {
- $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
- }
return $statusMsg;
}
/**
* @param $membership
- * @param $endDate
- * @param $receiptSend
- * @param $membershipTypes
- * @param $createdMemberships
- * @param $isRecur
- * @param $calcDates
- * @param $mailSend
*/
- protected function setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend) {
- $statusMsg = '';
- if (($this->_action & CRM_Core_Action::UPDATE)) {
- $statusMsg = $this->getStatusMessageForUpdate($membership, $endDate, $receiptSend);
- }
- elseif (($this->_action & CRM_Core_Action::ADD)) {
- $statusMsg = $this->getStatusMessageForCreate($endDate, $receiptSend, $membershipTypes, $createdMemberships,
- $isRecur, $calcDates, $mailSend);
- }
-
- CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
+ protected function setStatusMessage($membership) {
//CRM-15187
// display message when membership type is changed
if (($this->_action & CRM_Core_Action::UPDATE) && $this->_id && !in_array($this->_memType, $this->_memTypeSelected)) {
@@ -1917,4 +1913,68 @@ protected function setStatusMessage($membership, $endDate, $receiptSend, $member
}
}
+ /**
+ * @return bool
+ */
+ protected function isUpdateToExistingRecurringMembership() {
+ $isRecur = FALSE;
+ if ($this->_action & CRM_Core_Action::UPDATE
+ && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
+ 'contribution_recur_id')
+ && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
+
+ $isRecur = TRUE;
+ }
+ return $isRecur;
+ }
+
+ /**
+ * Send a receipt for the membership.
+ *
+ * @param array $formValues
+ * @param \CRM_Member_BAO_Membership $membership
+ *
+ * @return bool
+ */
+ protected function emailMembershipReceipt($formValues, $membership) {
+ $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
+
+ return self::emailReceipt($this, $formValues, $membership, $customValues);
+ }
+
+ /**
+ * Filter the custom values from the input parameters (for display in the email).
+ *
+ * @todo figure out why the scary code this calls does & document.
+ *
+ * @param array $formValues
+ * @param \CRM_Member_BAO_Membership $membership
+ * @return array
+ */
+ protected function getCustomValuesForReceipt($formValues, $membership) {
+ $customFields = $customValues = [];
+ if (property_exists($this, '_groupTree')
+ && !empty($this->_groupTree)
+ ) {
+ foreach ($this->_groupTree as $groupID => $group) {
+ if ($groupID == 'info') {
+ continue;
+ }
+ foreach ($group['fields'] as $k => $field) {
+ $field['title'] = $field['label'];
+ $customFields["custom_{$k}"] = $field;
+ }
+ }
+ }
+
+ $members = [['member_id', '=', $membership->id, 0, 0]];
+ // check whether its a test drive
+ if ($this->_mode == 'test') {
+ $members[] = ['member_test', '=', 1, 0, 0];
+ }
+
+ CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
+ return $customValues;
+ }
+
}
diff --git a/CRM/Member/Form/MembershipBlock.php b/CRM/Member/Form/MembershipBlock.php
index 25a2751268eb..83df3d77a151 100644
--- a/CRM/Member/Form/MembershipBlock.php
+++ b/CRM/Member/Form/MembershipBlock.php
@@ -1,9 +1,9 @@
_id)) {
$defaults = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
}
@@ -77,13 +76,13 @@ public function setDefaultValues() {
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
$this->assign('isQuick', 1);
$this->_memPriceSetId = $priceSetId;
- $pFIDs = array();
+ $pFIDs = [];
if ($priceSetId) {
- CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = array(
+ CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = [
'html_type',
'name',
'label',
- ));
+ ]);
foreach ($pFIDs as $pid => $pValue) {
if ($pValue['html_type'] == 'Radio' && $pValue['name'] == 'membership_amount') {
$defaults['mem_price_field_id'] = $pValue['id'];
@@ -92,7 +91,7 @@ public function setDefaultValues() {
}
if (!empty($defaults['mem_price_field_id'])) {
- $options = array();
+ $options = [];
$priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($defaults['mem_price_field_id'], $options, 'id', 1);
foreach ($options as $k => $v) {
$newMembershipType[$v['membership_type_id']] = 1;
@@ -130,7 +129,7 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_required', ts('Require Membership Signup'));
$this->addElement('checkbox', 'display_min_fee', ts('Display Membership Fee'));
$this->addElement('checkbox', 'is_separate_payment', ts('Separate Membership Payment'));
- $this->addElement('text', 'membership_type_label', ts('Membership Types Label'), array('placeholder' => ts('Membership')));
+ $this->addElement('text', 'membership_type_label', ts('Membership Types Label'), ['placeholder' => ts('Membership')]);
$paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
$paymentProcessorIds = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
@@ -145,7 +144,7 @@ public function buildQuickForm() {
}
}
- $membership = $membershipDefault = $params = array();
+ $membership = $membershipDefault = $params = [];
foreach ($membershipTypes as $k => $v) {
$membership[] = $this->createElement('advcheckbox', $k, NULL, $v);
$membershipDefault[] = $this->createElement('radio', NULL, NULL, NULL, $k);
@@ -153,9 +152,9 @@ public function buildQuickForm() {
if ($isRecur) {
$autoRenew = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $k, 'auto_renew');
$membershipRequired[$k] = $autoRenew;
- $autoRenewOptions = array();
+ $autoRenewOptions = [];
if ($autoRenew) {
- $autoRenewOptions = array(ts('Not offered'), ts('Give option'), ts('Required'));
+ $autoRenewOptions = [ts('Not offered'), ts('Give option'), ts('Required')];
$this->addElement('select', "auto_renew_$k", ts('Auto-renew'), $autoRenewOptions);
//CRM-15573
if ($autoRenew == 2) {
@@ -172,7 +171,7 @@ public function buildQuickForm() {
$params['membership_types'] = serialize($membershipRequired);
CRM_Member_BAO_MembershipBlock::create($params);
}
- $this->add('hidden', "mem_price_field_id", '', array('id' => "mem_price_field_id"));
+ $this->add('hidden', "mem_price_field_id", '', ['id' => "mem_price_field_id"]);
$this->assign('is_recur', $isRecur);
if (isset($this->_renewOption)) {
$this->assign('auto_renew', $this->_renewOption);
@@ -181,7 +180,7 @@ public function buildQuickForm() {
$this->addGroup($membershipDefault, 'membership_type_default', ts('Membership Types Default'))
->setAttribute('allowClear', TRUE);
- $this->addFormRule(array('CRM_Member_Form_MembershipBlock', 'formRule'), $this->_id);
+ $this->addFormRule(['CRM_Member_Form_MembershipBlock', 'formRule'], $this->_id);
}
$price = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
if (CRM_Utils_System::isNull($price)) {
@@ -190,23 +189,23 @@ public function buildQuickForm() {
else {
$this->assign('price', TRUE);
}
- $this->add('select', 'member_price_set_id', ts('Membership Price Set'), (array('' => ts('- none -')) + $price));
+ $this->add('select', 'member_price_set_id', ts('Membership Price Set'), (['' => ts('- none -')] + $price));
$session = CRM_Core_Session::singleton();
$single = $session->get('singleForm');
if ($single) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
else {
parent::buildQuickForm();
@@ -226,7 +225,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $contributionPageId = NULL) {
- $errors = array();
+ $errors = [];
if (!empty($params['member_price_set_id'])) {
//check if this price set has membership type both auto-renew and non-auto-renew memberships.
@@ -282,7 +281,7 @@ public static function formRule($params, $files, $contributionPageId = NULL) {
}
elseif (array_sum($membershipType) > CRM_Price_Form_Field::NUM_OPTION) {
// for CRM-13079
- $errors['membership_type'] = ts('You cannot select more than %1 choices. For more complex functionality, please use a Price Set.', array(1 => CRM_Price_Form_Field::NUM_OPTION));
+ $errors['membership_type'] = ts('You cannot select more than %1 choices. For more complex functionality, please use a Price Set.', [1 => CRM_Price_Form_Field::NUM_OPTION]);
}
elseif ($isRecur) {
if (empty($params['is_separate_payment']) && array_sum($membershipType) != 0) {
@@ -344,7 +343,7 @@ public function postProcess() {
$params['id'] = $membershipID;
}
- $membershipTypes = array();
+ $membershipTypes = [];
if (is_array($params['membership_type'])) {
foreach ($params['membership_type'] as $k => $v) {
if ($v) {
@@ -393,16 +392,16 @@ public function postProcess() {
$fieldParams['id'] = CRM_Utils_Array::value('mem_price_field_id', $params);
$priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('mem_price_field_id', $params), 'price_set_id');
}
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_set_id' => $priceSetID,
'name' => 'membership_amount',
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (empty($editedResults['id'])) {
$fieldParams['name'] = strtolower(CRM_Utils_String::munge('Membership Amount', '_', 245));
if (empty($params['mem_price_field_id'])) {
- CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', 0, 1, array('price_set_id' => $priceSetID));
+ CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', 0, 1, ['price_set_id' => $priceSetID]);
}
$fieldParams['weight'] = 1;
}
@@ -416,7 +415,7 @@ public function postProcess() {
$fieldParams['is_required'] = !empty($params['is_required']) ? 1 : 0;
$fieldParams['is_display_amounts'] = !empty($params['display_min_fee']) ? 1 : 0;
$rowCount = 1;
- $options = array();
+ $options = [];
if (!empty($fieldParams['id'])) {
CRM_Core_PseudoConstant::populate($options, 'CRM_Price_DAO_PriceFieldValue', TRUE, 'membership_type_id', NULL, " price_field_id = {$fieldParams['id']} ");
}
@@ -471,12 +470,12 @@ public function postProcess() {
if ($deletePriceSet || !CRM_Utils_Array::value('member_is_active', $params, FALSE)) {
if ($this->_memPriceSetId) {
- $pFIDs = array();
- $conditionParams = array(
+ $pFIDs = [];
+ $conditionParams = [
'price_set_id' => $this->_memPriceSetId,
'html_type' => 'radio',
'name' => 'contribution_amount',
- );
+ ];
CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $conditionParams, $pFIDs);
if (empty($pFIDs['id'])) {
diff --git a/CRM/Member/Form/MembershipConfig.php b/CRM/Member/Form/MembershipConfig.php
index e3f2df0ba71d..60dc0a36a051 100644
--- a/CRM/Member/Form/MembershipConfig.php
+++ b/CRM/Member/Form/MembershipConfig.php
@@ -1,9 +1,9 @@
_id = $this->get('id');
- $this->_BAOName = $this->get('BAOName');
- }
-
/**
* Set default values for the form. MobileProvider that in edit/view mode
* the default values are retrieved from the database
*
- *
* @return array
* defaults
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
$baoName = $this->_BAOName;
$baoName::retrieve($params, $defaults);
}
@@ -111,48 +98,48 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::RENEW) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Renew'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
elseif ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
else {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/MembershipRenewal.php b/CRM/Member/Form/MembershipRenewal.php
index 6734e5a71650..a8e9f8504639 100644
--- a/CRM/Member/Form/MembershipRenewal.php
+++ b/CRM/Member/Form/MembershipRenewal.php
@@ -1,9 +1,9 @@
array('default' => 'now'),
- );
+ public function setDeleteMessage() {}
/**
* Pre-process form.
*
* @throws \Exception
*/
+
+ /**
+ * Set the renewal notification status message.
+ */
+ public function setRenewalMessage() {
+ $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $this->membershipTypeName, 2 => $this->_memberDisplayName));
+
+ if ($this->isMailSent) {
+ $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(
+ 1 => $this->_contributorEmail,
+ ));
+ }
+ CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
+ }
+
public function preProcess() {
// This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
@@ -178,10 +198,9 @@ public function setDefaultValues() {
$defaults = parent::setDefaultValues();
// set renewal_date and receive_date to today in correct input format (setDateDefaults uses today if no value passed)
- list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
+ $now = date('Y-m-d');
$defaults['renewal_date'] = $now;
- $defaults['receive_date'] = $now;
- $defaults['receive_date_time'] = $currentTime;
+ $defaults['receive_date'] = $now . ' ' . date('H:i:s');
if ($defaults['id']) {
$defaults['record_contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
@@ -211,9 +230,7 @@ public function setDefaultValues() {
$scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
$defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
- $renewalDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('renewal_date', $defaults),
- NULL, NULL, 'Y-m-d'
- );
+ $renewalDate = CRM_Utils_Array::value('renewal_date', $defaults);
$this->assign('renewalDate', $renewalDate);
$this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
@@ -236,13 +253,15 @@ public function buildQuickForm() {
$this->assign('entityID', $this->_id);
$selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
- $allMembershipInfo = array();
+ $allMembershipInfo = [];
- //CRM-16950
- $taxRates = CRM_Core_PseudoConstant::getTaxRates();
- $taxRate = CRM_Utils_Array::value($this->allMembershipTypeDetails[$defaults['membership_type_id']]['financial_type_id'], $taxRates);
+ // CRM-21485
+ if (is_array($defaults['membership_type_id'])) {
+ $defaults['membership_type_id'] = $defaults['membership_type_id'][1];
+ }
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
+ //CRM-16950
+ $taxRate = $this->getTaxRateForFinancialType($this->allMembershipTypeDetails[$defaults['membership_type_id']]['financial_type_id']);
// auto renew options if enabled for the membership
$options = CRM_Core_SelectValues::memberAutoRenew();
@@ -271,19 +290,20 @@ public function buildQuickForm() {
//CRM-16950
$taxAmount = NULL;
$totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
- if (CRM_Utils_Array::value($values['financial_type_id'], $taxRates)) {
+ // @todo - feels a bug - we use taxRate from the form default rather than from the specified type?!?
+ if ($this->getTaxRateForFinancialType($values['financial_type_id'])) {
$taxAmount = ($taxRate / 100) * CRM_Utils_Array::value('minimum_fee', $values);
$totalAmount = $totalAmount + $taxAmount;
}
// build membership info array, which is used to set the payment information block when
// membership type is selected.
- $allMembershipInfo[$key] = array(
+ $allMembershipInfo[$key] = [
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
'total_amount_numeric' => $totalAmount,
- 'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", array(1 => CRM_Utils_Array::value('tax_term', $invoiceSettings), 2 => CRM_Utils_Money::format($taxAmount))) : $taxAmount,
- );
+ 'tax_message' => $taxAmount ? ts("Includes %1 amount of %2", [1 => $this->getSalesTaxTerm(), 2 => CRM_Utils_Money::format($taxAmount)]) : $taxAmount,
+ ];
if (!empty($values['auto_renew'])) {
$allMembershipInfo[$key]['auto_renew'] = $options[$values['auto_renew']];
@@ -310,45 +330,45 @@ public function buildQuickForm() {
$selOrgMemType[$index] = $orgMembershipType;
}
- $js = array('onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);");
+ $js = ['onChange' => "setPaymentBlock(); CRM.buildCustomData('Membership', this.value);"];
$sel = &$this->addElement('hierselect',
'membership_type_id',
ts('Renewal Membership Organization and Type'), $js
);
- $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
- $elements = array();
+ $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
+ $elements = [];
if ($sel) {
$elements[] = $sel;
}
$this->applyFilter('__ALL__', 'trim');
- $this->addDate('renewal_date', ts('Date Renewal Entered'), FALSE, array('formatType' => 'activityDate'));
+ $this->add('datepicker', 'renewal_date', ts('Date Renewal Entered'), [], FALSE, ['time' => FALSE]);
$this->add('select', 'financial_type_id', ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType()
);
- $this->add('text', 'num_terms', ts('Extend Membership by'), array('onchange' => "setPaymentBlock();"), TRUE);
+ $this->add('number', 'num_terms', ts('Extend Membership by'), ['onchange' => "setPaymentBlock();"], TRUE);
$this->addRule('num_terms', ts('Please enter a whole number for how many periods to renew.'), 'integer');
if (CRM_Core_Permission::access('CiviContribute') && !$this->_mode) {
- $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, array('onclick' => "checkPayment();"));
+ $this->addElement('checkbox', 'record_contribution', ts('Record Renewal Payment?'), NULL, ['onclick' => "checkPayment();"]);
$this->add('text', 'total_amount', ts('Amount'));
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
- $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
$this->add('select', 'payment_instrument_id', ts('Payment Method'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
- FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
+ FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
);
$this->add('text', 'trxn_id', ts('Transaction ID'));
$this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
- 'objectExists', array('CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id')
+ 'objectExists', ['CRM_Contribute_DAO_Contribution', $this->_id, 'trxn_id']
);
$this->add('select', 'contribution_status_id', ts('Payment Status'),
@@ -364,7 +384,7 @@ public function buildQuickForm() {
$this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
}
$this->addElement('checkbox', 'send_receipt', ts('Send Confirmation and Receipt?'), NULL,
- array('onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);")
+ ['onclick' => "showHideByValue( 'send_receipt', '', 'notice', 'table-row', 'radio', false ); showHideByValue( 'send_receipt', '', 'fromEmail', 'table-row', 'radio',false);"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
@@ -389,10 +409,10 @@ public function buildQuickForm() {
);
}
}
- $this->addFormRule(array('CRM_Member_Form_MembershipRenewal', 'formRule'), $this);
+ $this->addFormRule(['CRM_Member_Form_MembershipRenewal', 'formRule'], $this);
$this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
- $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
- $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
+ $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
+ $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
}
/**
@@ -400,12 +420,14 @@ public function buildQuickForm() {
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
+ * @param $files
+ * @param $self
*
* @return bool|array
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
if ($params['membership_type_id'][0] == 0) {
$errors['membership_type_id'] = ts('Oops. It looks like you are trying to change the membership type while renewing the membership. Please click the "change membership type" link, and select a Membership Organization.');
}
@@ -421,7 +443,7 @@ public static function formRule($params, $files, $self) {
// The fields in Renewal form come into this routine in $params array. 'renewal_date' is in the form
// We process both the dates before comparison using CRM utils so that they are in same date format
if (isset($params['renewal_date'])) {
- if (CRM_Utils_Date::processDate($params['renewal_date']) < CRM_Utils_Date::processDate($joinDate)) {
+ if ($params['renewal_date'] < $joinDate) {
$errors['renewal_date'] = ts('Renewal date must be the same or later than Member since (Join Date).');
}
}
@@ -452,30 +474,14 @@ public function postProcess() {
try {
$this->submit();
- $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $this->membershipTypeName, 2 => $this->_memberDisplayName));
-
- if ($this->endDate) {
- $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(
- 1 => CRM_Utils_Date::customFormat(substr($this->endDate, 0, 8)),
- ));
- }
-
- if ($this->isMailSent) {
- $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(
- 1 => $this->_contributorEmail,
- ));
- return $statusMsg;
- }
- return $statusMsg;
+ $this->setRenewalMessage();
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
- CRM_Core_Error::displaySessionError($e->getMessage());
+ CRM_Core_Session::singleton()->setStatus($e->getMessage());
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
"reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"
));
}
-
- CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
}
/**
@@ -487,8 +493,7 @@ protected function submit() {
$this->storeContactFields($this->_params);
$this->beginPostProcess();
$now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
- $this->convertDateFieldsToMySQL($this->_params);
- $this->assign('receive_date', $this->_params['receive_date']);
+ $this->assign('receive_date', CRM_Utils_Array::value('receive_date', $this->_params, date('Y-m-d H:i:s')));
$this->processBillingAddress();
list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
$this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params,
@@ -555,7 +560,7 @@ protected function submit() {
$this->assign('trxn_id', $result['trxn_id']);
}
- $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($this->_params['renewal_date']) : NULL;
+ $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = $this->_params['renewal_date'] : NULL;
// check for test membership.
$isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
@@ -572,7 +577,7 @@ protected function submit() {
$this->_params['is_pay_later'] = 1;
}
- // These variable sets prior to renewMembership may not be required for this form. They were in
+ // These variable sets prior to membership may not be required for this form. They were in
// a function this form shared with other forms.
$membershipSource = NULL;
if (!empty($this->_params['membership_source'])) {
@@ -581,7 +586,7 @@ protected function submit() {
$isPending = ($this->_params['contribution_status_id'] == 2) ? TRUE : FALSE;
- list($renewMembership) = CRM_Member_BAO_Membership::processMembership(
+ list($membership) = CRM_Member_BAO_Membership::processMembership(
$this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership,
$renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId,
$isPending,
@@ -589,9 +594,9 @@ protected function submit() {
$this->_params)
);
- $this->endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
+ $this->endDate = CRM_Utils_Date::processDate($membership->end_date);
- $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id,
+ $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membership->membership_type_id,
'name');
if (!empty($this->_params['record_contribution']) || $this->_mode) {
@@ -599,7 +604,7 @@ protected function submit() {
$this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
//create line items
- $lineItem = array();
+ $lineItem = [];
$this->_params = $this->setPriceSetParameters($this->_params);
CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
$this->_params, $lineItem[$this->_priceSetId], NULL, $this->_priceSetId
@@ -622,10 +627,10 @@ protected function submit() {
if ($this->_contributorContactID != $this->_contactID) {
$this->_params['contribution_contact_id'] = $this->_contributorContactID;
if (!empty($this->_params['soft_credit_type_id'])) {
- $this->_params['soft_credit'] = array(
+ $this->_params['soft_credit'] = [
'soft_credit_type_id' => $this->_params['soft_credit_type_id'],
'contact_id' => $this->_contactID,
- );
+ ];
}
}
$this->_params['contact_id'] = $this->_contactID;
@@ -633,10 +638,10 @@ protected function submit() {
// not a great pattern & ideally it would not receive as a reference. We assign our params as a
// temporary variable to avoid e-notice & to make it clear to future refactorer that
// this function is NOT reliant on that var being set
- $temporaryParams = array_merge($this->_params, array(
- 'membership_id' => $renewMembership->id,
+ $temporaryParams = array_merge($this->_params, [
+ 'membership_id' => $membership->id,
'contribution_recur_id' => $contributionRecurID,
- ));
+ ]);
//Remove `tax_amount` if it is not calculated.
if (CRM_Utils_Array::value('tax_amount', $temporaryParams) === 0) {
unset($temporaryParams['tax_amount']);
@@ -656,7 +661,7 @@ protected function submit() {
$this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->_id, FALSE, $this->_memType);
// retrieve custom data
- $customFields = $customValues = $fo = array();
+ $customFields = $customValues = $fo = [];
foreach ($this->_groupTree as $groupID => $group) {
if ($groupID == 'info') {
continue;
@@ -666,10 +671,10 @@ protected function submit() {
$customFields["custom_{$k}"] = $field;
}
}
- $members = array(array('member_id', '=', $this->_membershipId, 0, 0));
+ $members = [['member_id', '=', $this->_membershipId, 0, 0]];
// check whether its a test drive
if ($this->_mode == 'test') {
- $members[] = array('member_test', '=', 1, 0, 0);
+ $members[] = ['member_test', '=', 1, 0, 0];
}
CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
@@ -679,11 +684,11 @@ protected function submit() {
}
$this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
- $renewMembership->membership_type_id
+ $membership->membership_type_id
));
$this->assign('customValues', $customValues);
- $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
- $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
+ $this->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date));
+ $this->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date));
if ($this->_mode) {
$this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
$this->_params,
@@ -700,7 +705,7 @@ protected function submit() {
}
list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_membership',
'valueName' => 'membership_offline_receipt',
'contactId' => $this->_receiptContactId,
@@ -708,7 +713,7 @@ protected function submit() {
'toName' => $this->_contributorDisplayName,
'toEmail' => $this->_contributorEmail,
'isTest' => $this->_mode == 'test',
- )
+ ]
);
}
}
diff --git a/CRM/Member/Form/MembershipStatus.php b/CRM/Member/Form/MembershipStatus.php
index e20ec7f86cf6..5f644507e375 100644
--- a/CRM/Member/Form/MembershipStatus.php
+++ b/CRM/Member/Form/MembershipStatus.php
@@ -1,9 +1,9 @@
'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'label' => [
+ 'name' => 'label',
+ 'description' => ts("Display name for this Membership status (e.g. New, Current, Grace, Expired...)."),
+ 'required' => TRUE,
+ ],
+ 'is_admin' => [
+ 'name' => 'is_admin',
+ 'description' => ts("Check this box if this status is for use by administrative staff only. If checked, this status is never automatically assigned by CiviMember. It is assigned to a contact's Membership by checking the Status Override flag when adding or editing the Membership record. Start and End Event settings are ignored for Administrator statuses. EXAMPLE: This setting can be useful for special case statuses like 'Non-expiring', 'Barred' or 'Expelled', etc."),
+ ],
+ ];
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('You will not be able to delete this membership status if there are existing memberships with this status. You will need to check all your membership status rules afterwards to ensure that a valid status will always be available.') . " " . ts('Do you want to continue?');
+ }
+
+ public function preProcess() {
+ $this->_id = $this->get('id');
+ $this->_BAOName = 'CRM_Member_BAO_MembershipStatus';
+ }
/**
* Set default values for the form. MobileProvider that in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
+ * @return array
*/
public function setDefaultValues() {
- $defaults = parent::setDefaultValues();
+ $defaults = $this->getEntityDefaults();
+
+ if ($this->_action & CRM_Core_Action::ADD) {
+ $defaults['is_active'] = 1;
+ }
//finding default weight to be put
if (empty($defaults['weight'])) {
@@ -58,18 +121,15 @@ public function setDefaultValues() {
/**
* Build the form object.
- *
- * @return void
*/
public function buildQuickForm() {
+ self::buildQuickEntityForm();
parent::buildQuickForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
- $this->applyFilter('__ALL__', 'trim');
-
if ($this->_id) {
$name = $this->add('text', 'name', ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'name')
@@ -77,27 +137,23 @@ public function buildQuickForm() {
$name->freeze();
$this->assign('id', $this->_id);
}
- $this->add('text', 'label', ts('Label'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'label'), TRUE
- );
$this->addRule('label', ts('A membership status with this label already exists. Please select another label.'),
- 'objectExists', array('CRM_Member_DAO_MembershipStatus', $this->_id, 'name')
+ 'objectExists', ['CRM_Member_DAO_MembershipStatus', $this->_id, 'name']
);
$this->add('select', 'start_event', ts('Start Event'), CRM_Core_SelectValues::eventDate(), TRUE);
- $this->add('select', 'start_event_adjust_unit', ts('Start Event Adjustment'), array('' => ts('- select -')) + CRM_Core_SelectValues::unitList());
+ $this->add('select', 'start_event_adjust_unit', ts('Start Event Adjustment'), ['' => ts('- select -')] + CRM_Core_SelectValues::unitList());
$this->add('text', 'start_event_adjust_interval', ts('Start Event Adjust Interval'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'start_event_adjust_interval')
);
- $this->add('select', 'end_event', ts('End Event'), array('' => ts('- select -')) + CRM_Core_SelectValues::eventDate());
- $this->add('select', 'end_event_adjust_unit', ts('End Event Adjustment'), array('' => ts('- select -')) + CRM_Core_SelectValues::unitList());
+ $this->add('select', 'end_event', ts('End Event'), ['' => ts('- select -')] + CRM_Core_SelectValues::eventDate());
+ $this->add('select', 'end_event_adjust_unit', ts('End Event Adjustment'), ['' => ts('- select -')] + CRM_Core_SelectValues::unitList());
$this->add('text', 'end_event_adjust_interval', ts('End Event Adjust Interval'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'end_event_adjust_interval')
);
$this->add('checkbox', 'is_current_member', ts('Current Membership?'));
- $this->add('checkbox', 'is_admin', ts('Administrator Only?'));
- $this->add('text', 'weight', ts('Order'),
+ $this->add('number', 'weight', ts('Order'),
CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipStatus', 'weight')
);
$this->add('checkbox', 'is_default', ts('Default?'));
@@ -106,9 +162,6 @@ public function buildQuickForm() {
/**
* Process the form submission.
- *
- *
- * @return void
*/
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
@@ -121,7 +174,6 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected membership status has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $params = $ids = array();
// store the submitted values in an array
$params = $this->exportValues();
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
@@ -130,7 +182,7 @@ public function postProcess() {
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['membershipStatus'] = $this->_id;
+ $params['id'] = $this->getEntityId();
}
$oldWeight = NULL;
if ($this->_id) {
@@ -143,9 +195,9 @@ public function postProcess() {
$params['name'] = $params['label'];
}
- $membershipStatus = CRM_Member_BAO_MembershipStatus::add($params, $ids);
+ $membershipStatus = CRM_Member_BAO_MembershipStatus::add($params);
CRM_Core_Session::setStatus(ts('The membership status \'%1\' has been saved.',
- array(1 => $membershipStatus->label)
+ [1 => $membershipStatus->label]
), ts('Saved'), 'success');
}
}
diff --git a/CRM/Member/Form/MembershipType.php b/CRM/Member/Form/MembershipType.php
index 62788066985c..3e1c01588ee3 100644
--- a/CRM/Member/Form/MembershipType.php
+++ b/CRM/Member/Form/MembershipType.php
@@ -1,9 +1,9 @@
'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * - required
+ * - is_freeze (field should be frozen).
+ *
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'name' => [
+ 'required' => 'TRUE',
+ 'name' => 'name',
+ 'description' => ts("e.g. 'Student', 'Senior', 'Honor Society'..."),
+ ],
+ 'description' => [
+ 'name' => 'description',
+ 'description' => ts("Description of this membership type for internal use. May include eligibility, benefits, terms, etc."),
+ ],
+ 'member_of_contact_id' => [
+ 'name' => 'member_of_contact_id',
+ 'description' => ts("Members assigned this membership type belong to which organization (e.g. this is for membership in 'Save the Whales - Northwest Chapter'). NOTE: This organization/group/chapter must exist as a CiviCRM Organization type contact."),
+ ],
+ 'minimum_fee' => [
+ 'name' => 'minimum_fee',
+ 'description' => ts('Minimum fee required for this membership type. For free/complimentary memberships - set minimum fee to zero (0). NOTE: When using CiviCRM to process sales taxes this should be the tax exclusive amount.'),
+ 'formatter' => 'crmMoney',
+ ],
+ 'financial_type_id' => [
+ 'name' => 'financial_type_id',
+ 'description' => ts('Select the financial type assigned to fees for this membership type (for example \'Membership Fees\'). This is required for all membership types - including free or complimentary memberships.'),
+ ],
+ 'auto_renew' => [
+ 'name' => 'auto_renew',
+ 'options' => CRM_Core_SelectValues::memberAutoRenew(),
+ 'place_holder' => ts('You will need to select and configure a supported payment processor (currently Authorize.Net, PayPal Pro, or PayPal Website Standard) in order to offer automatically renewing memberships.'),
+ ],
+ 'duration_interval' => [
+ 'name' => 'duration_interval',
+ 'required' => TRUE,
+ ],
+ 'duration_unit' => [
+ 'name' => 'duration_unit',
+ 'description' => ts('Duration of this membership (e.g. 30 days, 2 months, 5 years, 1 lifetime)'),
+ 'required' => TRUE,
+ ],
+ 'period_type' => [
+ 'name' => 'period_type',
+ 'description' => ts("Select 'rolling' if membership periods begin at date of signup. Select 'fixed' if membership periods begin on a set calendar date."),
+ 'help' => ['id' => 'period-type', 'file' => "CRM/Member/Page/MembershipType.hlp"],
+ 'required' => TRUE,
+ ],
+ 'fixed_period_start_day' => [
+ 'name' => 'fixed_period_start_day',
+ 'description' => ts("Month and day on which a fixed period membership or subscription begins. Example: A fixed period membership with Start Day set to Jan 01 means that membership periods would be 1/1/06 - 12/31/06 for anyone signing up during 2006."),
+ ],
+ 'fixed_period_rollover_day' => [
+ 'name' => 'fixed_period_rollover_day',
+ 'description' => ts('Membership signups on or after this date cover the following calendar year as well. Example: If the rollover day is November 30, membership period for signups during December will cover the following year.'),
+ ],
+ 'relationship_type_id' => [
+ 'name' => 'relationship_type_id',
+ ],
+ 'max_related' => [
+ 'name' => 'max_related',
+ 'description' => ts('Maximum number of related memberships (leave blank for unlimited).'),
+ ],
+ 'visibility' => [
+ 'name' => 'visibility',
+ 'description' => ts("Can this membership type be used for self-service signups ('Public'), or is it only for CiviCRM users with 'Edit Contributions' permission ('Admin')."),
+ ],
+ 'weight' => [
+ 'name' => 'weight',
+ ],
+ 'is_active' => [
+ 'name' => 'is_active',
+ ],
+ ];
+
+ if (!CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(['Recurring'])) {
+ $this->entityFields['auto_renew']['not-auto-addable'] = TRUE;
+ $this->entityFields['auto_renew']['documentation_link'] = ['page' => 'user/contributions/payment-processors'];
+ }
+ }
+
+ /**
+ * Deletion message to be assigned to the form.
+ *
+ * @var string
+ */
+ protected $deleteMessage;
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'MembershipType';
+ }
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {
+ $this->deleteMessage = ts('WARNING: Deleting this option will result in the loss of all membership records of this type.') . ts('This may mean the loss of a substantial amount of data, and the action cannot be undone.') . ts('Do you want to continue?');
+ }
+
+ /**
+ * Explicitly declare the form context.
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
/**
* Max number of contacts we will display for membership-organisation
*/
@@ -61,8 +190,8 @@ public function preProcess() {
* Set default values for the form. MobileProvider that in edit/view mode
* the default values are retrieved from the database
*
- *
- * @return void
+ * @return array
+ * defaults
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
@@ -77,19 +206,19 @@ public function setDefaultValues() {
// Set values for relation type select box
$relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_type_id']);
$relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['relationship_direction']);
- $defaults['relationship_type_id'] = array();
+ $defaults['relationship_type_id'] = [];
foreach ($relTypeIds as $key => $value) {
$defaults['relationship_type_id'][] = $value . '_' . $relDirections[$key];
}
}
//setting default fixed_period_start_day & fixed_period_rollover_day
- $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
+ $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
foreach ($periods as $per) {
if (isset($defaults[$per])) {
$date = $defaults[$per];
- $defaults[$per] = array();
+ $defaults[$per] = [];
if ($date > 31) {
$date = ($date < 999) ? '0' . $date : $date;
$defaults[$per]['M'] = substr($date, 0, 2);
@@ -109,38 +238,27 @@ public function setDefaultValues() {
* Build the form object.
*
* @return void
+ * @throws \CRM_Core_Exception
+ * @throws \CiviCRM_API3_Exception
*/
public function buildQuickForm() {
- parent::buildQuickForm();
+ self::buildQuickEntityForm();
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
-
- $this->applyFilter('__ALL__', 'trim');
- $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
+ // This is a temporary variable as we work towards moving over towards using the EntityField.tpl.
+ // Fields in this array have been tested & in the tpl have been switched over to metadata.
+ // Note this kinda 'works from the top' - ie. once we hit a field that needs some thought we need
+ // to stop & make that one work.
+ $this->assign('tpl_standardised_fields', ['name', 'description', 'member_of_contact_id', 'minimum_fee']);
$this->addRule('name', ts('A membership type with this name already exists. Please select another name.'),
- 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)
- );
- $this->add('text', 'description', ts('Description'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')
- );
- $this->add('text', 'minimum_fee', ts('Minimum Fee'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')
+ 'objectExists', ['CRM_Member_DAO_MembershipType', $this->_id]
);
$this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
- $this->addSelect('duration_unit', array(), TRUE);
-
- //period type
- $this->addSelect('period_type', array(), TRUE);
-
- $this->add('text', 'duration_interval', ts('Duration Interval'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')
- );
-
- $props = array('api' => array('params' => array('contact_type' => 'Organization')));
+ $props = ['api' => ['params' => ['contact_type' => 'Organization']]];
$this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE);
//start day
@@ -148,11 +266,10 @@ public function buildQuickForm() {
CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
);
- //Auto-renew Option
- $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
+ // Add Auto-renew options if we have a payment processor that supports recurring contributions
$isAuthorize = FALSE;
- $options = array();
- if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
+ $options = [];
+ if (CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(['Recurring'])) {
$isAuthorize = TRUE;
$options = CRM_Core_SelectValues::memberAutoRenew();
}
@@ -160,7 +277,7 @@ public function buildQuickForm() {
$this->addRadio('auto_renew', ts('Auto-renew Option'), $options);
$this->assign('authorize', $isAuthorize);
- //rollover day
+ // rollover day
$this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'),
CRM_Core_SelectValues::date(NULL, 'M d'), FALSE
);
@@ -168,7 +285,7 @@ public function buildQuickForm() {
CRM_Core_SelectValues::date(NULL, 'd'), FALSE
);
$this->add('select', 'financial_type_id', ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action), TRUE, array('class' => 'crm-select2')
+ ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action), TRUE, ['class' => 'crm-select2']
);
$relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
@@ -176,18 +293,13 @@ public function buildQuickForm() {
asort($relTypeInd);
}
$memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'),
- $relTypeInd, FALSE, array('class' => 'crm-select2 huge', 'multiple' => 1));
+ $relTypeInd, FALSE, ['class' => 'crm-select2 huge', 'multiple' => 1]);
- $this->addSelect('visibility', array('placeholder' => NULL, 'option_url' => NULL));
-
- $this->add('text', 'weight', ts('Order'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')
- );
- $this->add('checkbox', 'is_active', ts('Enabled?'));
+ $this->addField('visibility', ['placeholder' => NULL, 'option_url' => NULL]);
$membershipRecords = FALSE;
if ($this->_action & CRM_Core_Action::UPDATE) {
- $result = civicrm_api3("Membership", "get", array("membership_type_id" => $this->_id, "options" => array("limit" => 1)));
+ $result = civicrm_api3("Membership", "get", ["membership_type_id" => $this->_id, "options" => ["limit" => 1]]);
$membershipRecords = ($result["count"] > 0);
if ($membershipRecords) {
$memberRel->freeze();
@@ -196,11 +308,7 @@ public function buildQuickForm() {
$this->assign('membershipRecordsExists', $membershipRecords);
- $this->add('text', 'max_related', ts('Max related'),
- CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related')
- );
-
- $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
+ $this->addFormRule(['CRM_Member_Form_MembershipType', 'formRule']);
$this->assign('membershipTypeId', $this->_id);
@@ -220,7 +328,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params) {
- $errors = array();
+ $errors = [];
if (!$params['name']) {
$errors['name'] = ts('Please enter a membership type name.');
@@ -234,10 +342,10 @@ public static function formRule($params) {
$errors['duration_interval'] = ts('Please enter a duration interval.');
}
- if (in_array(CRM_Utils_Array::value('auto_renew', $params), array(
+ if (in_array(CRM_Utils_Array::value('auto_renew', $params), [
1,
2,
- ))) {
+ ])) {
if (($params['duration_interval'] > 1 && $params['duration_unit'] == 'year') ||
($params['duration_interval'] > 12 && $params['duration_unit'] == 'month')
) {
@@ -254,7 +362,7 @@ public static function formRule($params) {
if (($params['period_type'] == 'fixed') &&
($params['duration_unit'] == 'year')
) {
- $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
+ $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
foreach ($periods as $period) {
$month = $params[$period]['M'];
$date = $params[$period]['d'];
@@ -292,7 +400,6 @@ public static function formRule($params) {
/**
* Process the form submission.
*
- *
* @return void
*/
public function postProcess() {
@@ -306,43 +413,17 @@ public function postProcess() {
CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.'), ts('Record Deleted'), 'success');
}
else {
- $buttonName = $this->controller->getButtonName();
- $submitted = $this->controller->exportValues($this->_name);
-
- $fields = array(
- 'name',
- 'weight',
- 'is_active',
- 'member_of_contact_id',
- 'visibility',
- 'period_type',
- 'minimum_fee',
- 'description',
- 'auto_renew',
- 'duration_unit',
- 'duration_interval',
- 'financial_type_id',
- 'fixed_period_start_day',
- 'fixed_period_rollover_day',
- 'month_fixed_period_rollover_day',
- 'max_related',
- );
+ $params = $this->exportValues();
- $params = $ids = array();
- foreach ($fields as $fld) {
- $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL');
- }
-
- //clean money.
if ($params['minimum_fee']) {
$params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']);
}
$hasRelTypeVal = FALSE;
- if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) {
+ if (!CRM_Utils_System::isNull($params['relationship_type_id'])) {
// To insert relation ids and directions with value separator
- $relTypeDirs = $submitted['relationship_type_id'];
- $relIds = $relDirection = array();
+ $relTypeDirs = $params['relationship_type_id'];
+ $relIds = $relDirection = [];
foreach ($relTypeDirs as $key => $value) {
$relationId = explode('_', $value);
if (count($relationId) == 3 &&
@@ -359,7 +440,7 @@ public function postProcess() {
}
}
if (!$hasRelTypeVal) {
- $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'NULL';
+ $params['relationship_type_id'] = $params['relationship_direction'] = $params['max_related'] = 'null';
}
if ($params['duration_unit'] == 'lifetime' &&
@@ -368,21 +449,21 @@ public function postProcess() {
$params['duration_interval'] = 1;
}
- $periods = array('fixed_period_start_day', 'fixed_period_rollover_day');
- foreach ($periods as $per) {
- if (!empty($params[$per]['M']) && !empty($params[$per]['d'])) {
- $mon = $params[$per]['M'];
- $dat = $params[$per]['d'];
+ $periods = ['fixed_period_start_day', 'fixed_period_rollover_day'];
+ foreach ($periods as $period) {
+ if (!empty($params[$period]['M']) && !empty($params[$period]['d'])) {
+ $mon = $params[$period]['M'];
+ $dat = $params[$period]['d'];
$mon = ($mon < 10) ? '0' . $mon : $mon;
$dat = ($dat < 10) ? '0' . $dat : $dat;
- $params[$per] = $mon . $dat;
+ $params[$period] = $mon . $dat;
}
- elseif ($per == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
+ elseif ($period == 'fixed_period_rollover_day' && !empty($params['month_fixed_period_rollover_day'])) {
$params['fixed_period_rollover_day'] = $params['month_fixed_period_rollover_day']['d'];
unset($params['month_fixed_period_rollover_day']);
}
else {
- $params[$per] = 'NULL';
+ $params[$period] = 'null';
}
}
$oldWeight = NULL;
@@ -397,15 +478,17 @@ public function postProcess() {
);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $ids['membershipType'] = $this->_id;
+ $params['id'] = $this->_id;
}
- $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids);
+ $membershipTypeResult = civicrm_api3('MembershipType', 'create', $params);
+ $membershipTypeName = $membershipTypeResult['values'][$membershipTypeResult['id']]['name'];
- CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.',
- array(1 => $membershipType->name)
+ CRM_Core_Session::setStatus(ts("The membership type '%1' has been saved.",
+ [1 => $membershipTypeName]
), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
+ $buttonName = $this->controller->getButtonName();
if ($buttonName == $this->getButtonName('upload', 'new')) {
$session->replaceUserContext(
CRM_Utils_System::url('civicrm/admin/member/membershipType/add', 'action=add&reset=1')
@@ -422,18 +505,18 @@ public function postProcess() {
*/
public static function checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, &$optionsIds) {
if ($previousID) {
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_set_id ' => $priceSetId,
'name' => $previousID,
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (!empty($editedResults)) {
- $editedFieldParams = array(
+ $editedFieldParams = [
'price_field_id' => $editedResults['id'],
'membership_type_id' => $membershipTypeId,
- );
- $editedResults = array();
+ ];
+ $editedResults = [];
CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
$optionsIds['option_id'][1] = CRM_Utils_Array::value('id', $editedResults);
}
diff --git a/CRM/Member/Form/MembershipView.php b/CRM/Member/Form/MembershipView.php
index 65c63d486883..05520fb1d342 100644
--- a/CRM/Member/Form/MembershipView.php
+++ b/CRM/Member/Form/MembershipView.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=view&id=%%id%%&cid=%%cid%%&relAction=delete&mid=%%mid%%&reset=1' . $this->addContext(),
'title' => ts('Cancel Related Membership'),
- ),
- CRM_Core_Action::ADD => array(
+ ],
+ CRM_Core_Action::ADD => [
'name' => ts('Create'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=view&id=%%id%%&cid=%%cid%%&relAction=create&rid=%%rid%%&reset=1' . $this->addContext(),
'title' => ts('Create Related Membership'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -103,13 +116,13 @@ public function relAction($action, $owner) {
$relatedContactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$relatedDisplayName = CRM_Contact_BAO_Contact::displayName($relatedContactId);
CRM_Member_BAO_Membership::del($id);
- CRM_Core_Session::setStatus(ts('Related membership for %1 has been deleted.', array(1 => $relatedDisplayName)),
+ CRM_Core_Session::setStatus(ts('Related membership for %1 has been deleted.', [1 => $relatedDisplayName]),
ts('Membership Deleted'), 'success');
break;
case 'create':
- $ids = array();
- $params = array(
+ $ids = [];
+ $params = [
'contact_id' => CRM_Utils_Request::retrieve('rid', 'Positive', $this),
'membership_type_id' => $owner['membership_type_id'],
'owner_membership_id' => $owner['id'],
@@ -122,10 +135,10 @@ public function relAction($action, $owner) {
'status_id' => $owner['status_id'],
'skipStatusCal' => TRUE,
'createActivity' => TRUE,
- );
+ ];
CRM_Member_BAO_Membership::create($params, $ids);
$relatedDisplayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
- CRM_Core_Session::setStatus(ts('Related membership for %1 has been created.', array(1 => $relatedDisplayName)),
+ CRM_Core_Session::setStatus(ts('Related membership for %1 has been created.', [1 => $relatedDisplayName]),
ts('Membership Added'), 'success');
break;
@@ -148,22 +161,22 @@ public function relAction($action, $owner) {
* @return void
*/
public function preProcess() {
-
- $values = array();
- $id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
+ $values = [];
+ $this->membershipID = CRM_Utils_Request::retrieve('id', 'Positive', $this);
+ $this->contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
// Make sure context is assigned to template for condition where we come here view civicrm/membership/view
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $context);
- if ($id) {
- $params = array('id' => $id);
+ if ($this->membershipID) {
+ $params = ['id' => $this->membershipID];
CRM_Member_BAO_Membership::retrieve($params, $values);
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
$finTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values['membership_type_id'], 'financial_type_id');
$finType = CRM_Contribute_PseudoConstant::financialType($finTypeId);
if (!CRM_Core_Permission::check('view contributions of type ' . $finType)) {
- CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
}
}
else {
@@ -181,12 +194,12 @@ public function preProcess() {
$this->assign('accessContribution', FALSE);
if (CRM_Core_Permission::access('CiviContribute')) {
$this->assign('accessContribution', TRUE);
- CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $id);
+ CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $this->membershipID);
}
//Provide information about membership source when it is the result of a relationship (CRM-1901)
$values['owner_membership_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
- $id,
+ $this->membershipID,
'owner_membership_id'
);
@@ -242,8 +255,7 @@ public function preProcess() {
$relTypeId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
$relDirection = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
foreach ($relTypeId as $rid) {
- $dir = each($relDirection);
- $relTypeDir[substr($dir['value'], 0, 1)][] = $rid;
+ $relTypeDir[substr($relDirection[0], 0, 1)][] = $rid;
}
// build query in 2 parts with a UNION if necessary
// _x and _y are replaced with _a and _b first, then vice-versa
@@ -260,7 +272,7 @@ public function preProcess() {
LEFT JOIN civicrm_membership_status ms ON ms.id = m.status_id
WHERE r.contact_id_y = {$values['contact_id']} AND r.is_active = 1 AND c.is_deleted = 0";
$query = '';
- foreach (array('a', 'b') as $dir) {
+ foreach (['a', 'b'] as $dir) {
if (isset($relTypeDir[$dir])) {
$query .= ($query ? ' UNION ' : '')
. str_replace('_y', '_' . $dir, str_replace('_x', '_' . ($dir == 'a' ? 'b' : 'a'), $select))
@@ -269,9 +281,9 @@ public function preProcess() {
}
$query .= " ORDER BY is_current_member DESC";
$dao = CRM_Core_DAO::executeQuery($query);
- $related = array();
+ $related = [];
$relatedRemaining = CRM_Utils_Array::value('max_related', $values, PHP_INT_MAX);
- $rowElememts = array(
+ $rowElememts = [
'id',
'cid',
'name',
@@ -282,21 +294,21 @@ public function preProcess() {
'end_date',
'is_current_member',
'status',
- );
+ ];
while ($dao->fetch()) {
- $row = array();
+ $row = [];
foreach ($rowElememts as $field) {
$row[$field] = $dao->$field;
}
if ($row['mid'] && ($row['is_current_member'] == 1)) {
$relatedRemaining--;
$row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::DELETE,
- array(
+ [
'id' => CRM_Utils_Request::retrieve('id', 'Positive', $this),
'cid' => $row['cid'],
'mid' => $row['mid'],
- ),
+ ],
ts('more'),
FALSE,
'membership.relationship.action',
@@ -307,11 +319,11 @@ public function preProcess() {
else {
if ($relatedRemaining > 0) {
$row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::ADD,
- array(
+ [
'id' => CRM_Utils_Request::retrieve('id', 'Positive', $this),
'cid' => $row['cid'],
'rid' => $row['cid'],
- ),
+ ],
ts('more'),
FALSE,
'membership.relationship.action',
@@ -328,10 +340,10 @@ public function preProcess() {
}
else {
if ($relatedRemaining < 100000) {
- $this->assign('related_text', ts('%1 available', array(1 => $relatedRemaining)));
+ $this->assign('related_text', ts('%1 available', [1 => $relatedRemaining]));
}
else {
- $this->assign('related_text', ts('Unlimited', array(1 => $relatedRemaining)));
+ $this->assign('related_text', ts('Unlimited', [1 => $relatedRemaining]));
}
}
}
@@ -353,7 +365,7 @@ public function preProcess() {
"action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -375,21 +387,21 @@ public function preProcess() {
CRM_Member_Page_Tab::setContext($this, $values['contact_id']);
- $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $id, "membership_type_id");
+ $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $this->membershipID, "membership_type_id");
- $groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $id, 0, $memType);
- CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $id);
+ $groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', NULL, $this->membershipID, 0, $memType);
+ CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->membershipID);
- $isRecur = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $id, 'contribution_recur_id');
+ $isRecur = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->membershipID, 'contribution_recur_id');
$autoRenew = $isRecur ? TRUE : FALSE;
}
if (!empty($values['is_test'])) {
- $values['membership_type'] .= ' (test) ';
+ $values['membership_type'] = CRM_Core_TestEntity::appendTestText($values['membership_type']);
}
- $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($id);
+ $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->membershipID);
$values['auto_renew'] = ($autoRenew && !$subscriptionCancelled) ? 'Yes' : 'No';
//do check for campaigns
@@ -407,14 +419,14 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/Search.php b/CRM/Member/Form/Search.php
index e21293931a3b..8eba67bfa9c7 100644
--- a/CRM/Member/Form/Search.php
+++ b/CRM/Member/Form/Search.php
@@ -1,9 +1,9 @@
_done = FALSE;
- $this->defaults = array();
-
- /*
- * we allow the controller to set force/reset externally, useful when we are being
- * driven by the wizard framework
- */
-
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
+ $this->loadStandardSearchOptionsFromUrl();
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
@@ -153,7 +142,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
+ $this->addContactSearchFields();
CRM_Member_BAO_Query::buildSearchForm($this);
@@ -163,9 +152,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Member_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Member_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -192,6 +179,36 @@ protected function getSortNameLabelWithOutEmail() {
return ts('Member Name');
}
+ /**
+ * Get the label for the tag field.
+ *
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
+ *
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Member Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getGroupLabel() {
+ return ts('Member Group(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Member Contact Type');
+ }
+
/**
* The post processing of the form gets done here.
*
@@ -305,8 +322,8 @@ public function fixFormValues() {
$membershipType = CRM_Utils_Request::retrieve('type', 'String');
if ($membershipType) {
- $this->_formValues['membership_type_id'] = array($membershipType);
- $this->_defaults['membership_type_id'] = array($membershipType);
+ $this->_formValues['membership_type_id'] = [$membershipType];
+ $this->_defaults['membership_type_id'] = [$membershipType];
}
$cid = CRM_Utils_Request::retrieve('cid', 'Positive');
@@ -353,7 +370,7 @@ public function fixFormValues() {
//LCD also allow restrictions to membership owner via GET
$owner = CRM_Utils_Request::retrieve('owner', 'String');
- if (in_array($owner, array('0', '1'))) {
+ if (in_array($owner, ['0', '1'])) {
$this->_formValues['member_is_primary'] = $this->_defaults['member_is_primary'] = $owner;
}
}
diff --git a/CRM/Member/Form/Task.php b/CRM/Member/Form/Task.php
index 7624334c19e5..7cc08118ee44 100644
--- a/CRM/Member/Form/Task.php
+++ b/CRM/Member/Form/Task.php
@@ -1,9 +1,9 @@
_memberIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_memberIds = [];
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
- $memberTasks = CRM_Member_Task::tasks();
- $form->assign('taskName', $memberTasks[$form->_task]);
+ $tasks = CRM_Member_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission());
+ if (!array_key_exists($form->_task, $tasks)) {
+ CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
+ }
+ $form->assign('taskName', $tasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -156,7 +130,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_memberIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_memberIds,
'civicrm_membership'
);
}
@@ -174,17 +148,17 @@ public function setContactIDs() {
* @return void
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => $backType,
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/Task/Batch.php b/CRM/Member/Form/Task/Batch.php
index 32e513a47d93..99d6af35a4e6 100644
--- a/CRM/Member/Form/Task/Batch.php
+++ b/CRM/Member/Form/Task/Batch.php
@@ -1,9 +1,9 @@
ts('Name')),
+ $readOnlyFields = array_merge(['sort_name' => ts('Name')],
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
@@ -96,12 +96,12 @@ public function buildQuickForm() {
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
- $this->_fields = array();
+ $this->_fields = [];
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
// remove file type field and then limit fields
$suppressFields = FALSE;
- $removehtmlTypes = array('File', 'Autocomplete-Select');
+ $removehtmlTypes = ['File'];
foreach ($this->_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
@@ -119,24 +119,24 @@ public function buildQuickForm() {
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'submit',
'name' => ts('Update Members(s)'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_memberIds);
//load all campaigns.
if (array_key_exists('member_campaign_id', $this->_fields)) {
- $this->_componentCampaigns = array();
+ $this->_componentCampaigns = [];
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Member_DAO_Membership',
TRUE, 'campaign_id', 'id',
@@ -150,7 +150,7 @@ public function buildQuickForm() {
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $customFields);
- $entityColumnValue = array();
+ $entityColumnValue = [];
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
@@ -175,7 +175,7 @@ public function buildQuickForm() {
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_Batch_next') {
- CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple memberships."), ts('Unsupported Field Type'), 'error');
+ CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple memberships."), ts('Unsupported Field Type'), 'error');
}
$this->addDefaultButtons(ts('Update Memberships'));
@@ -192,7 +192,7 @@ public function setDefaultValues() {
return;
}
- $defaults = array();
+ $defaults = [];
foreach ($this->_memberIds as $memberId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $memberId, 'Membership');
}
@@ -208,13 +208,16 @@ public function setDefaultValues() {
*/
public function postProcess() {
$params = $this->exportValues();
- $dates = array(
+ // @todo extract submit functions &
+ // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test
+ // handling of custom data, specifically checkbox fields.
+ $dates = [
'join_date',
'membership_start_date',
'membership_end_date',
- );
+ ];
if (isset($params['field'])) {
- $customFields = array();
+ $customFields = [];
foreach ($params['field'] as $key => $value) {
$ids['membership'] = $key;
if (!empty($value['membership_source'])) {
diff --git a/CRM/Member/Form/Task/Delete.php b/CRM/Member/Form/Task/Delete.php
index 21efb65d0b2c..a6cbf2235b9b 100644
--- a/CRM/Member/Form/Task/Delete.php
+++ b/CRM/Member/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count memberships deleted.', 'count' => $deleted));
+ $msg = ts('%count membership deleted.', ['plural' => '%count memberships deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Member/Form/Task/Email.php b/CRM/Member/Form/Task/Email.php
index 2efd8140ec92..be38db71a038 100644
--- a/CRM/Member/Form/Task/Email.php
+++ b/CRM/Member/Form/Task/Email.php
@@ -1,9 +1,9 @@
array('IN' => $this->_memberIds),
+ $labelRows = [];
+ $memberships = civicrm_api3('membership', 'get', [
+ 'id' => ['IN' => $this->_memberIds],
'return' => 'contact_id',
- ));
+ ]);
foreach ($memberships['values'] as $id => $membership) {
if (isset($rows[$membership['contact_id']])) {
$labelRows[$id] = $rows[$membership['contact_id']];
@@ -142,7 +142,7 @@ public function postProcess() {
}
//call function to create labels
CRM_Contact_Form_Task_LabelCommon::createLabel($labelRows, $labelName);
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
}
diff --git a/CRM/Member/Form/Task/PDFLetter.php b/CRM/Member/Form/Task/PDFLetter.php
index 04176fc47d37..cb917cec1c75 100644
--- a/CRM/Member/Form/Task/PDFLetter.php
+++ b/CRM/Member/Form/Task/PDFLetter.php
@@ -1,9 +1,9 @@
_cid ? array($form->_cid) : $contactIDs;
self::createActivities($form, $html_message, $contactIDs, $formValues['subject'], CRM_Utils_Array::value('campaign_id', $formValues));
CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
$form->postProcessHook();
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
@@ -59,13 +55,13 @@ public static function postProcessMembers(&$form, $membershipIDs, $skipOnHold, $
*/
public static function generateHTML($membershipIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $html_message, $categories) {
$memberships = CRM_Utils_Token::getMembershipTokenDetails($membershipIDs);
- $html = array();
+ $html = [];
foreach ($membershipIDs as $membershipID) {
$membership = $memberships[$membershipID];
// get contact information
$contactId = $membership['contact_id'];
- $params = array('contact_id' => $contactId);
+ $params = ['contact_id' => $contactId];
//getTokenDetails is much like calling the api contact.get function - but - with some minor
// special handlings. It precedes the existence of the api
list($contacts) = CRM_Utils_Token::getTokenDetails(
diff --git a/CRM/Member/Form/Task/PickProfile.php b/CRM/Member/Form/Task/PickProfile.php
index 1f5aefb07d30..68b6ba1b53c7 100644
--- a/CRM/Member/Form/Task/PickProfile.php
+++ b/CRM/Member/Form/Task/PickProfile.php
@@ -1,9 +1,9 @@
_memberIds) > $this->_maxMembers) {
- CRM_Core_Session::setStatus(ts("The maximum number of members you can select for Update multiple memberships is %1. You have selected %2. Please select fewer members from your search results and try again.", array(
+ CRM_Core_Session::setStatus(ts("The maximum number of members you can select for Update multiple memberships is %1. You have selected %2. Please select fewer members from your search results and try again.", [
1 => $this->_maxMembers,
2 => count($this->_memberIds),
- )), ts('Update multiple records error'), 'error');
+ ]), ts('Update multiple records error'), 'error');
$validate = TRUE;
}
@@ -91,18 +93,18 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $types = array('Membership');
+ $types = ['Membership'];
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
if (empty($profiles)) {
- CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple memberships. Navigate to Administer CiviCRM >> CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts('Update multiple records error'), 'error');
+ CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple memberships. Navigate to Administer CiviCRM >> CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", [1 => $types[0]]), ts('Update multiple records error'), 'error');
CRM_Utils_System::redirect($this->_userContext);
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
- array(
+ [
'' => ts('- select profile -'),
- ) + $profiles, TRUE
+ ] + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
@@ -114,7 +116,7 @@ public function buildQuickForm() {
* @return void
*/
public function addRules() {
- $this->addFormRule(array('CRM_Member_Form_Task_PickProfile', 'formRule'));
+ $this->addFormRule(['CRM_Member_Form_Task_PickProfile', 'formRule']);
}
/**
diff --git a/CRM/Member/Form/Task/Print.php b/CRM/Member/Form/Task/Print.php
index 7c89789747eb..423a3d588bbb 100644
--- a/CRM/Member/Form/Task/Print.php
+++ b/CRM/Member/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Print Members'),
- 'js' => array('onclick' => 'window.print()'),
+ 'js' => ['onclick' => 'window.print()'],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'back',
'name' => ts('Done'),
- ),
- ));
+ ],
+ ]);
}
/**
diff --git a/CRM/Member/Form/Task/Result.php b/CRM/Member/Form/Task/Result.php
index 3f2e3dc30dcc..7f68f5c76f38 100644
--- a/CRM/Member/Form/Task/Result.php
+++ b/CRM/Member/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Form/Task/SearchTaskHookSample.php b/CRM/Member/Form/Task/SearchTaskHookSample.php
index bccbea6f5e91..9a780079f66e 100644
--- a/CRM/Member/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Member/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_memberIds);
@@ -61,12 +61,12 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'start_date' => CRM_Utils_Date::customFormat($dao->start_date),
'end_date' => CRM_Utils_Date::customFormat($dao->end_date),
'source' => $dao->source,
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -77,13 +77,13 @@ public function preProcess() {
* @return void
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Member/Import/Controller.php b/CRM/Member/Import/Controller.php
index 5148f9643c43..f0483d0284f7 100644
--- a/CRM/Member/Import/Controller.php
+++ b/CRM/Member/Import/Controller.php
@@ -1,9 +1,9 @@
addActions($config->uploadDir, array('uploadFile'));
+ $this->addActions($config->uploadDir, ['uploadFile']);
}
}
diff --git a/CRM/Member/Import/Field.php b/CRM/Member/Import/Field.php
index 5be748109877..93bb374bc825 100644
--- a/CRM/Member/Import/Field.php
+++ b/CRM/Member/Import/Field.php
@@ -1,9 +1,9 @@
_value);
case 'trxn_id':
- static $seenTrxnIds = array();
+ static $seenTrxnIds = [];
if (in_array($this->_value, $seenTrxnIds)) {
return FALSE;
}
diff --git a/CRM/Member/Import/Form/DataSource.php b/CRM/Member/Import/Form/DataSource.php
index 11eb187608b3..46342000a65b 100644
--- a/CRM/Member/Import/Form/DataSource.php
+++ b/CRM/Member/Import/Form/DataSource.php
@@ -1,9 +1,9 @@
createElement('radio',
NULL, NULL, ts('Insert new Membership'), CRM_Import_Parser::DUPLICATE_SKIP
);
@@ -61,9 +61,9 @@ public function buildQuickForm() {
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('Import mode')
);
- $this->setDefaults(array(
+ $this->setDefaults([
'onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP,
- ));
+ ]);
$this->addContactTypeSelector();
}
@@ -74,12 +74,12 @@ public function buildQuickForm() {
* @return void
*/
public function postProcess() {
- $this->storeFormValues(array(
+ $this->storeFormValues([
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
- ));
+ ]);
$this->submitFileForMapping('CRM_Member_Import_Parser_Membership');
}
diff --git a/CRM/Member/Import/Form/MapField.php b/CRM/Member/Import/Form/MapField.php
index bfab1fdddeca..fa849f6449fd 100644
--- a/CRM/Member/Import/Form/MapField.php
+++ b/CRM/Member/Import/Form/MapField.php
@@ -1,9 +1,9 @@
$params['saveMappingName'],
'description' => $params['saveMappingDesc'],
- 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
- 'Import Membership',
- 'name'
- ),
+ 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
diff --git a/CRM/Member/Import/Form/Preview.php b/CRM/Member/Import/Form/Preview.php
index a595b0a28ded..33eba538071a 100644
--- a/CRM/Member/Import/Form/Preview.php
+++ b/CRM/Member/Import/Form/Preview.php
@@ -1,9 +1,9 @@
set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
- $properties = array(
+ $properties = [
'mapper',
'dataValues',
'columnCount',
@@ -98,7 +98,8 @@ public function preProcess() {
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
- );
+ ];
+ $this->setStatusUrl();
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
@@ -120,9 +121,9 @@ public function postProcess() {
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
- $mapperKeys = array();
- $mapperLocType = array();
- $mapperPhoneType = array();
+ $mapperKeys = [];
+ $mapperLocType = [];
+ $mapperPhoneType = [];
// Note: we keep the multi-dimension array (even thought it's not
// needed in the case of memberships import) so that we can merge
// the common code with contacts import later and subclass contact
@@ -150,7 +151,7 @@ public function postProcess() {
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
- $header = array();
+ $header = [];
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
@@ -161,17 +162,18 @@ public function postProcess() {
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$this->get('contactType'),
- $onDuplicate
+ $onDuplicate,
+ $this->get('statusID'),
+ $this->get('totalRowCount')
);
// add all the necessary variables to the form
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// check if there is any error occurred
-
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
- $errorMessage = array();
+ $errorMessage = [];
if (is_array($errors)) {
foreach ($errors as $key => $value) {
diff --git a/CRM/Member/Import/Form/Summary.php b/CRM/Member/Import/Form/Summary.php
index ebd8345710f7..f4940ff02c9d 100644
--- a/CRM/Member/Import/Form/Summary.php
+++ b/CRM/Member/Import/Form/Summary.php
@@ -1,9 +1,9 @@
assign('dupeActionString', $dupeActionString);
- $properties = array(
+ $properties = [
'totalRowCount',
'validRowCount',
'invalidRowCount',
@@ -105,7 +105,7 @@ public function preProcess() {
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
- );
+ ];
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
diff --git a/CRM/Member/Import/Parser.php b/CRM/Member/Import/Parser.php
index fe2ae708ada4..cf7367687609 100644
--- a/CRM/Member/Import/Parser.php
+++ b/CRM/Member/Import/Parser.php
@@ -1,9 +1,9 @@
_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
- $this->_errors = array();
- $this->_warnings = array();
- $this->_conflicts = array();
+ $this->_errors = [];
+ $this->_warnings = [];
+ $this->_conflicts = [];
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
- $this->_rows = array();
+ $this->_rows = [];
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
+ if ($statusID) {
+ $this->progressImport($statusID);
+ $startTimestamp = $currTimestamp = $prevTimestamp = time();
+ }
while (!feof($fd)) {
$this->_lineCount++;
@@ -146,7 +158,6 @@ public function run(
}
/* trim whitespace around the values */
-
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
@@ -168,6 +179,9 @@ public function run(
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
+ if ($statusID && (($this->_lineCount % 50) == 0)) {
+ $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
+ }
}
else {
$returnCode = self::ERROR;
@@ -191,11 +205,9 @@ public function run(
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
- if ($this->_invalidRowCount < $this->_maxErrorCount) {
- $recordNumber = $this->_lineCount;
- array_unshift($values, $recordNumber);
- $this->_errors[] = $values;
- }
+ $recordNumber = $this->_lineCount;
+ array_unshift($values, $recordNumber);
+ $this->_errors[] = $values;
}
if ($returnCode & self::CONFLICT) {
@@ -244,27 +256,27 @@ public function run(
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
- $headers = array_merge(array(
+ $headers = array_merge([
ts('Line Number'),
ts('Reason'),
- ), $customHeaders);
+ ], $customHeaders);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
- $headers = array_merge(array(
+ $headers = array_merge([
ts('Line Number'),
ts('Reason'),
- ), $customHeaders);
+ ], $customHeaders);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
- $headers = array_merge(array(
+ $headers = array_merge([
ts('Line Number'),
ts('View Membership URL'),
- ), $customHeaders);
+ ], $customHeaders);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
@@ -300,7 +312,7 @@ public function setActiveFields($fieldKeys) {
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
- $params = array();
+ $params = [];
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
@@ -405,7 +417,7 @@ public function set($store, $mode = self::MODE_SUMMARY) {
* @return void
*/
public static function exportCSV($fileName, $header, $data) {
- $output = array();
+ $output = [];
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
diff --git a/CRM/Member/Import/Parser/Membership.php b/CRM/Member/Import/Parser/Membership.php
index a66d1f2816e8..66147109a9b3 100644
--- a/CRM/Member/Import/Parser/Membership.php
+++ b/CRM/Member/Import/Parser/Membership.php
@@ -1,9 +1,9 @@
addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
- $this->_newMemberships = array();
+ $this->_newMemberships = [];
$this->setActiveFields($this->_mapperKeys);
@@ -211,6 +211,17 @@ public function summary(&$values) {
}
break;
+ case 'status_override_end_date':
+ if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
+ if (!CRM_Utils_Rule::date($params[$key])) {
+ CRM_Contact_Import_Parser_Contact::addToErrorMsg('Status Override End Date', $errorMessage);
+ }
+ }
+ else {
+ CRM_Contact_Import_Parser_Contact::addToErrorMsg('Status Override End Date', $errorMessage);
+ }
+ break;
+
case 'membership_type_id':
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
if (!CRM_Utils_Array::crmInArray($val, $membershipTypes) &&
@@ -278,17 +289,17 @@ public function import($onDuplicate, &$values) {
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
- $formatted = array();
+ $formatted = [];
$customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Membership';
$customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
// don't add to recent items, CRM-4399
$formatted['skipRecentView'] = TRUE;
- $dateLabels = array(
+ $dateLabels = [
'join_date' => ts('Member Since'),
'membership_start_date' => ts('Start Date'),
'membership_end_date' => ts('End Date'),
- );
+ ];
foreach ($params as $key => $val) {
if ($val) {
switch ($key) {
@@ -342,7 +353,7 @@ public function import($onDuplicate, &$values) {
$indieFields = $tempIndieFields;
}
- $formatValues = array();
+ $formatValues = [];
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
@@ -372,7 +383,7 @@ public function import($onDuplicate, &$values) {
if (!empty($formatValues['membership_id'])) {
$dao = new CRM_Member_BAO_Membership();
$dao->id = $formatValues['membership_id'];
- $dates = array('join_date', 'start_date', 'end_date');
+ $dates = ['join_date', 'start_date', 'end_date'];
foreach ($dates as $v) {
if (empty($formatted[$v])) {
$formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
@@ -384,10 +395,10 @@ public function import($onDuplicate, &$values) {
'Membership'
);
if ($dao->find(TRUE)) {
- $ids = array(
+ $ids = [
'membership' => $formatValues['membership_id'],
'userId' => $session->get('userID'),
- );
+ ];
if (empty($params['line_item']) && !empty($formatted['membership_type_id'])) {
CRM_Price_BAO_LineItem::getLineItemArray($formatted, NULL, 'membership', $formatted['membership_type_id']);
@@ -474,10 +485,10 @@ public function import($onDuplicate, &$values) {
}
else {
// Using new Dedupe rule.
- $ruleParams = array(
+ $ruleParams = [
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
- );
+ ];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = '';
@@ -594,11 +605,11 @@ public function fini() {
*
*/
public function formattedDates($calcDates, &$formatted) {
- $dates = array(
+ $dates = [
'join_date',
'start_date',
'end_date',
- );
+ ];
foreach ($dates as $d) {
if (isset($formatted[$d]) &&
@@ -647,10 +658,10 @@ public function membership_format_params($params, &$values, $create = FALSE) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
$values[$key] = $value;
$type = $customFields[$customFieldID]['html_type'];
- if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
+ if ($type == 'CheckBox' || $type == 'Multi-Select') {
$mulValues = explode(',', $value);
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
- $values[$key] = array();
+ $values[$key] = [];
foreach ($mulValues as $v1) {
foreach ($customOption as $customValueID => $customLabel) {
$customValue = $customLabel['value'];
@@ -675,7 +686,7 @@ public function membership_format_params($params, &$values, $create = FALSE) {
throw new Exception("contact_id not valid: $value");
}
$dao = new CRM_Core_DAO();
- $qParams = array();
+ $qParams = [];
$svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
$qParams
);
@@ -746,11 +757,11 @@ public function membership_format_params($params, &$values, $create = FALSE) {
// membership_end_date and membership_source. So, if $values contains
// membership_start_date, membership_end_date or membership_source,
// convert it to start_date, end_date or source
- $changes = array(
+ $changes = [
'membership_start_date' => 'start_date',
'membership_end_date' => 'end_date',
'membership_source' => 'source',
- );
+ ];
foreach ($changes as $orgVal => $changeVal) {
if (isset($values[$orgVal])) {
diff --git a/CRM/Member/Info.php b/CRM/Member/Info.php
index 4d7e6d594fd0..059c72072607 100644
--- a/CRM/Member/Info.php
+++ b/CRM/Member/Info.php
@@ -1,9 +1,9 @@
'CiviMember',
'translatedName' => ts('CiviMember'),
'title' => ts('CiviCRM Membership Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
-
/**
* @inheritDoc
* Provides permissions that are used by component.
@@ -82,20 +83,20 @@ public function getInfo() {
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviMember' => array(
+ $permissions = [
+ 'access CiviMember' => [
ts('access CiviMember'),
ts('View memberships'),
- ),
- 'edit memberships' => array(
+ ],
+ 'edit memberships' => [
ts('edit memberships'),
ts('Create and update memberships'),
- ),
- 'delete in CiviMember' => array(
+ ],
+ 'delete in CiviMember' => [
ts('delete in CiviMember'),
ts('Delete memberships'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -115,19 +116,20 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* collection of required dashboard settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Memberships'),
'title' => ts('Your Membership(s)'),
// this is CiviContribute specific permission, since
// there is no permission that could be checked for
// CiviMember
- 'perm' => array('make online contributions'),
+ 'perm' => ['make online contributions'],
'weight' => 30,
- );
+ ];
}
/**
@@ -139,15 +141,24 @@ public function getUserDashboardElement() {
* collection of required dashboard settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Memberships'),
'url' => 'membership',
'weight' => 30,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-id-badge';
}
/**
@@ -159,14 +170,15 @@ public function registerTab() {
* collection of required pane settings,
* null if no element offered
*/
+
/**
* @return array|null
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Memberships'),
'weight' => 30,
- );
+ ];
}
/**
@@ -179,6 +191,7 @@ public function registerAdvancedSearchPane() {
* @return array|null
* collection of activity types
*/
+
/**
* @return array|null
*/
@@ -195,20 +208,20 @@ public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviMember') &&
CRM_Core_Permission::check('edit memberships')
) {
- $shortCut[] = array(
+ $shortCut[] = [
'path' => 'civicrm/member/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-membership',
'title' => ts('Membership'),
- );
+ ];
if ($newCredit) {
$title = ts('Membership') . ' (' . ts('credit card') . ')';
- $shortCut[0]['shortCuts'][] = array(
+ $shortCut[0]['shortCuts'][] = [
'path' => 'civicrm/member/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-membership-cc',
'title' => $title,
- );
+ ];
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
diff --git a/CRM/Member/Page/AJAX.php b/CRM/Member/Page/AJAX.php
index 5e364ded053e..b309dc37f480 100644
--- a/CRM/Member/Page/AJAX.php
+++ b/CRM/Member/Page/AJAX.php
@@ -1,9 +1,9 @@
array($memType, 'Positive')));
- $properties = array('financial_type_id', 'total_amount', 'name', 'auto_renew');
+ $dao = CRM_Core_DAO::executeQuery($query, [1 => [$memType, 'Positive']]);
+ $properties = ['financial_type_id', 'total_amount', 'name', 'auto_renew'];
while ($dao->fetch()) {
foreach ($properties as $property) {
$details[$property] = $dao->$property;
diff --git a/CRM/Member/Page/DashBoard.php b/CRM/Member/Page/DashBoard.php
index 84ace2eba77c..b9bf7885fd60 100644
--- a/CRM/Member/Page/DashBoard.php
+++ b/CRM/Member/Page/DashBoard.php
@@ -1,9 +1,9 @@
$details) {
- foreach ($details as $key => $value) {
- switch ($key) {
- case 'premonth':
- $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$preMonth&joinEnd=$preMonthEnd&start=$preMonth&end=$preMonthEnd");
- $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$prePreMonthEnd&start=$preMonth&end=$preMonthEnd");
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$preMonth&end=$preMonthEnd");
- break;
-
- case 'month':
- $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$monthStart&joinEnd=$ymd&start=$monthStart&end=$ymd");
- $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$preMonthStart&start=$monthStart&end=$ymd");
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$monthStart&end=$ymd");
- break;
-
- case 'year':
- $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$yearStart&joinEnd=$ymd&start=$yearStart&end=$ymd");
- $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$preYearStart&start=$yearStart&end=$ymd");
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$yearStart&end=$ymd");
- break;
-
- case 'current':
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID");
- break;
-
- case 'total':
- if (!$isCurrentMonth) {
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search',
- "reset=1&force=1&start=&end=$ymd&status=$status&type=$typeID"
- );
- }
- else {
- $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search',
- "reset=1&force=1&status=$status"
- );
- }
- break;
-
- //LCD add owner urls
-
- case 'premonth_owner':
- $membershipSummary[$typeID][$key]['premonth_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$preMonth&end=$preMonthEnd&owner=1");
- break;
-
- case 'month_owner':
- $membershipSummary[$typeID][$key]['month_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$monthStart&end=$ymd&owner=1");
- break;
-
- case 'year_owner':
- $membershipSummary[$typeID][$key]['year_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$yearStart&end=$ymd&owner=1");
- break;
-
- case 'current_owner':
- $membershipSummary[$typeID][$key]['current_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&owner=1");
- break;
-
- case 'total_owner':
- if (!$isCurrentMonth) {
- $membershipSummary[$typeID][$key]['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&start=&end=$ymd&status=$status&type=$typeID&owner=1");
- }
- else {
- $membershipSummary[$typeID][$key]['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&owner=1");
- }
- break;
- //LCD end
- }
- }
- }
- @codingStandardsIgnoreEnd */
-
- // Temporary replacement for current totals column
-
foreach ($membershipSummary as $typeID => $details) {
if (!$isCurrentMonth) {
$membershipSummary[$typeID]['total']['total']['url'] = CRM_Utils_System::url('civicrm/member/search',
@@ -306,65 +228,38 @@ public function preProcess() {
$totalCount['premonth']['new'] = array(
'count' => $newCountPreMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=1&dateLow=$preMonth&dateHigh=$preMonthEnd"
- //),
);
$totalCount['premonth']['renew'] = array(
'count' => $renewCountPreMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=2&dateLow=$preMonth&dateHigh=$preMonthEnd"
- //),
);
$totalCount['premonth']['total'] = array(
'count' => $totalCountPreMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=3&dateLow=$preMonth&dateHigh=$preMonthEnd"
- //),
);
$totalCount['month']['new'] = array(
'count' => $newCountMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=1&dateLow=$monthStart&dateHigh=$ymd"
- //),
);
$totalCount['month']['renew'] = array(
'count' => $renewCountMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=2&dateLow=$monthStart&dateHigh=$ymd"
- //),
);
$totalCount['month']['total'] = array(
'count' => $totalCountMonth,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=3&dateLow=$monthStart&dateHigh=$ymd"
- //),
);
$totalCount['year']['new'] = array(
'count' => $newCountYear,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=1&dateLow=$yearStart&dateHigh=$ymd"
- //),
);
$totalCount['year']['renew'] = array(
'count' => $renewCountYear,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=2&dateLow=$yearStart&dateHigh=$ymd"
- //),
);
$totalCount['year']['total'] = array(
'count' => $totalCountYear,
- //'url' => CRM_Utils_System::url('civicrm/activity/search',
- // "reset=1&force=1&signupType=3&dateLow=$yearStart&dateHigh=$ymd"
- //),
);
$totalCount['current']['total'] = array(
@@ -428,7 +323,7 @@ public function preProcess() {
$this->assign('membershipSummary', $membershipSummary);
$this->assign('totalCount', $totalCount);
- $this->assign('month', CRM_Utils_Date::customFormat($monthStartTs, '%B'));
+ $this->assign('month', CRM_Utils_Date::customFormatTs($monthStartTs, '%B'));
$this->assign('year', date('Y', $monthStartTs));
$this->assign('premonth', CRM_Utils_Date::customFormat($preMonth, '%B'));
$this->assign('currentMonth', date('F'));
diff --git a/CRM/Member/Page/MembershipStatus.php b/CRM/Member/Page/MembershipStatus.php
index aa9732200190..c4e4b605d0c3 100644
--- a/CRM/Member/Page/MembershipStatus.php
+++ b/CRM/Member/Page/MembershipStatus.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/member/membershipStatus',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Membership Status'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Membership Status'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Membership Status'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/member/membershipStatus',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Membership Status'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -101,14 +101,14 @@ public function &links() {
*/
public function browse() {
// get all custom groups sorted by weight
- $membershipStatus = array();
+ $membershipStatus = [];
$dao = new CRM_Member_DAO_MembershipStatus();
$dao->orderBy('weight');
$dao->find();
while ($dao->fetch()) {
- $membershipStatus[$dao->id] = array();
+ $membershipStatus[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membershipStatus[$dao->id]);
// form all action links
@@ -122,7 +122,7 @@ public function browse() {
$action -= CRM_Core_Action::DISABLE;
}
$membershipStatus[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'membershipStatus.manage.action',
diff --git a/CRM/Member/Page/MembershipType.php b/CRM/Member/Page/MembershipType.php
index 7c83f7e6356e..e7807d67dad4 100644
--- a/CRM/Member/Page/MembershipType.php
+++ b/CRM/Member/Page/MembershipType.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/member/membershipType/add',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Membership Type'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Membership Type'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Membership Type'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/member/membershipType/add',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Membership Type'),
- ),
- );
+ ],
+ ];
}
return self::$_links;
}
@@ -107,7 +107,7 @@ public function run() {
*/
public function browse() {
// get all membership types sorted by weight
- $membershipType = array();
+ $membershipType = [];
$dao = new CRM_Member_DAO_MembershipType();
$dao->orderBy('weight');
@@ -120,7 +120,7 @@ public function browse() {
continue;
}
$links = self::links();
- $membershipType[$dao->id] = array();
+ $membershipType[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membershipType[$dao->id]);
$membershipType[$dao->id]['period_type'] = CRM_Utils_Array::value($dao->period_type, CRM_Core_SelectValues::periodType(), '');
@@ -162,7 +162,7 @@ public function browse() {
}
$membershipType[$dao->id]['order'] = $membershipType[$dao->id]['weight'];
$membershipType[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action,
- array('id' => $dao->id),
+ ['id' => $dao->id],
ts('more'),
FALSE,
'membershipType.manage.action',
diff --git a/CRM/Member/Page/RecurringContributions.php b/CRM/Member/Page/RecurringContributions.php
new file mode 100644
index 000000000000..07661c9fb7f9
--- /dev/null
+++ b/CRM/Member/Page/RecurringContributions.php
@@ -0,0 +1,144 @@
+membershipID = CRM_Utils_Request::retrieve('membershipID', 'Positive', $this);
+ $this->contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
+
+ $this->loadRecurringContributions();
+
+ return parent::run();
+ }
+
+ /**
+ * Loads recurring contributions and assigns them to the form, to be used on
+ * the template.
+ */
+ private function loadRecurringContributions() {
+ $recurringContributions = $this->getRecurContributions($this->membershipID);
+
+ if (!empty($recurringContributions)) {
+ $this->assign('recurRows', $recurringContributions);
+ $this->assign('recur', TRUE);
+ }
+ }
+
+ /**
+ * Obtains list of recurring contributions associated to a membership.
+ *
+ * @param int $membershipID
+ *
+ * @return array
+ */
+ private function getRecurContributions($membershipID) {
+ $result = civicrm_api3('MembershipPayment', 'get', [
+ 'sequential' => 1,
+ 'contribution_id.contribution_recur_id.id' => ['IS NOT NULL' => TRUE],
+ 'options' => ['limit' => 0],
+ 'return' => [
+ 'contribution_id.contribution_recur_id.id',
+ 'contribution_id.contribution_recur_id.contact_id',
+ 'contribution_id.contribution_recur_id.start_date',
+ 'contribution_id.contribution_recur_id.end_date',
+ 'contribution_id.contribution_recur_id.next_sched_contribution_date',
+ 'contribution_id.contribution_recur_id.amount',
+ 'contribution_id.contribution_recur_id.currency',
+ 'contribution_id.contribution_recur_id.frequency_unit',
+ 'contribution_id.contribution_recur_id.frequency_interval',
+ 'contribution_id.contribution_recur_id.installments',
+ 'contribution_id.contribution_recur_id.contribution_status_id',
+ 'contribution_id.contribution_recur_id.is_test',
+ 'contribution_id.contribution_recur_id.payment_processor_id',
+ ],
+ 'membership_id' => $membershipID,
+ ]);
+ $recurringContributions = [];
+ $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus();
+
+ foreach ($result['values'] as $payment) {
+ $recurringContributionID = $payment['contribution_id.contribution_recur_id.id'];
+ $alreadyProcessed = isset($recurringContributions[$recurringContributionID]);
+
+ if ($alreadyProcessed) {
+ continue;
+ }
+
+ foreach ($payment as $field => $value) {
+ $key = strtr($field, ['contribution_id.contribution_recur_id.' => '']);
+ $recurringContributions[$recurringContributionID][$key] = $value;
+ }
+
+ $contactID = $recurringContributions[$recurringContributionID]['contact_id'];
+ $contributionStatusID = $recurringContributions[$recurringContributionID]['contribution_status_id'];
+
+ $recurringContributions[$recurringContributionID]['id'] = $recurringContributionID;
+ $recurringContributions[$recurringContributionID]['contactId'] = $contactID;
+ $recurringContributions[$recurringContributionID]['contribution_status'] = CRM_Utils_Array::value($contributionStatusID, $contributionStatuses);
+
+ $this->setActionsForRecurringContribution($recurringContributionID, $recurringContributions[$recurringContributionID]);
+ }
+ return $recurringContributions;
+ }
+
+ /**
+ * Calculates and assigns the actions available for given recurring
+ * contribution.
+ *
+ * @param int $recurID
+ * @param array $recurringContribution
+ */
+ private function setActionsForRecurringContribution($recurID, &$recurringContribution) {
+ $action = array_sum(array_keys(CRM_Contribute_Page_Tab::recurLinks($recurID, 'contribution')));
+
+ // no action allowed if it's not active
+ $recurringContribution['is_active'] = ($recurringContribution['contribution_status_id'] != 3);
+
+ if ($recurringContribution['is_active']) {
+ $details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurringContribution['id'], 'recur');
+ $hideUpdate = $details->membership_id & $details->auto_renew;
+
+ if ($hideUpdate) {
+ $action -= CRM_Core_Action::UPDATE;
+ }
+
+ $recurringContribution['action'] = CRM_Core_Action::formLink(
+ CRM_Contribute_Page_Tab::recurLinks($recurID, 'contribution'),
+ $action,
+ [
+ 'cid' => $this->contactID,
+ 'crid' => $recurID,
+ 'cxt' => 'contribution',
+ ],
+ ts('more'),
+ FALSE,
+ 'contribution.selector.recurring',
+ 'Contribution',
+ $recurID
+ );
+ }
+ }
+
+}
diff --git a/CRM/Member/Page/Tab.php b/CRM/Member/Page/Tab.php
index ecbdab6b77f6..9d6f944e1158 100644
--- a/CRM/Member/Page/Tab.php
+++ b/CRM/Member/Page/Tab.php
@@ -1,9 +1,9 @@
contact_id = $this->_contactId;
- $dao->is_test = 0;
$dao->whereAdd($addWhere);
- //$dao->orderBy('name');
$dao->find();
//CRM--4418, check for view, edit, delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit memberships')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -83,7 +81,7 @@ public function browse() {
//checks membership of contact itself
while ($dao->fetch()) {
- $membership[$dao->id] = array();
+ $membership[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membership[$dao->id]);
//carry campaign.
@@ -91,7 +89,7 @@ public function browse() {
//get the membership status and type values.
$statusANDType = CRM_Member_BAO_Membership::getStatusANDTypeValues($dao->id);
- foreach (array('status', 'membership_type') as $fld) {
+ foreach (['status', 'membership_type'] as $fld) {
$membership[$dao->id][$fld] = CRM_Utils_Array::value($fld, $statusANDType[$dao->id]);
}
if (!empty($statusANDType[$dao->id]['is_current_member'])) {
@@ -110,9 +108,7 @@ public function browse() {
$paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity(
$membership[$dao->id]['membership_id'], 'membership', 'obj');
if (!empty($paymentObject)) {
- // @todo - get this working with syntax style $paymentObject->supports(array
- //('updateSubscriptionBillingInfo'));
- $isUpdateBilling = $paymentObject->isSupported('updateSubscriptionBillingInfo');
+ $isUpdateBilling = $paymentObject->supports('updateSubscriptionBillingInfo');
}
// @todo - get this working with syntax style $paymentObject->supports(array
@@ -128,10 +124,10 @@ public function browse() {
self::getPermissionedLinks($dao->membership_type_id, $links);
$membership[$dao->id]['action'] = CRM_Core_Action::formLink($links,
$currentMask,
- array(
+ [
'id' => $dao->id,
'cid' => $this->_contactId,
- ),
+ ],
ts('Renew') . '...',
FALSE,
'membership.tab.row',
@@ -144,10 +140,10 @@ public function browse() {
self::getPermissionedLinks($dao->membership_type_id, $links);
$membership[$dao->id]['action'] = CRM_Core_Action::formLink($links,
$mask,
- array(
+ [
'id' => $dao->id,
'cid' => $this->_contactId,
- ),
+ ],
ts('more'),
FALSE,
'membership.tab.row',
@@ -156,11 +152,14 @@ public function browse() {
);
}
- //does membership have auto renew CRM-7137.
- if (!empty($membership[$dao->id]['contribution_recur_id']) &&
- !CRM_Member_BAO_Membership::isSubscriptionCancelled($membership[$dao->id]['membership_id'])
- ) {
- $membership[$dao->id]['auto_renew'] = 1;
+ // Display Auto-renew status on page (0=disabled, 1=enabled, 2=enabled, but error
+ if (!empty($membership[$dao->id]['contribution_recur_id'])) {
+ if (CRM_Member_BAO_Membership::isSubscriptionCancelled($membership[$dao->id]['membership_id'])) {
+ $membership[$dao->id]['auto_renew'] = 2;
+ }
+ else {
+ $membership[$dao->id]['auto_renew'] = 1;
+ }
}
else {
$membership[$dao->id]['auto_renew'] = 0;
@@ -180,10 +179,10 @@ public function browse() {
WHERE m.owner_membership_id = {$dao->id} AND m.is_test = 0 AND ms.is_current_member = 1 AND ct.is_deleted = 0";
$num_related = CRM_Core_DAO::singleValueQuery($query);
$max_related = CRM_Utils_Array::value('max_related', $membership[$dao->id]);
- $membership[$dao->id]['related_count'] = ($max_related == '' ? ts('%1 created', array(1 => $num_related)) : ts('%1 out of %2', array(
+ $membership[$dao->id]['related_count'] = ($max_related == '' ? ts('%1 created', [1 => $num_related]) : ts('%1 out of %2', [
1 => $num_related,
2 => $max_related,
- )));
+ ]));
}
else {
$membership[$dao->id]['related_count'] = ts('N/A');
@@ -192,21 +191,21 @@ public function browse() {
//Below code gives list of all Membership Types associated
//with an Organization(CRM-2016)
- $membershipTypesResult = civicrm_api3('MembershipType', 'get', array(
+ $membershipTypesResult = civicrm_api3('MembershipType', 'get', [
'member_of_contact_id' => $this->_contactId,
- 'options' => array(
+ 'options' => [
'limit' => 0,
- ),
- ));
+ ],
+ ]);
$membershipTypes = CRM_Utils_Array::value('values', $membershipTypesResult, NULL);
foreach ($membershipTypes as $key => $value) {
$membershipTypes[$key]['action'] = CRM_Core_Action::formLink(self::membershipTypeslinks(),
$mask,
- array(
+ [
'id' => $value['id'],
'cid' => $this->_contactId,
- ),
+ ],
ts('more'),
FALSE,
'membershipType.organization.action',
@@ -226,10 +225,10 @@ public function browse() {
$this->assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId);
// Refresh other tabs with related data
- $this->ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
'#tab_rel' => CRM_Contact_BAO_Contact::getCountComponent('rel', $this->_contactId),
- );
+ ];
if (CRM_Core_Permission::access('CiviContribute')) {
$this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
@@ -261,7 +260,7 @@ public function view() {
*/
public function edit() {
// set https for offline cc transaction
- $mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
+ $mode = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
if ($mode == 'test' || $mode == 'live') {
CRM_Utils_System::redirectToSSL();
}
@@ -303,7 +302,7 @@ public function edit() {
}
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -387,7 +386,7 @@ public function run() {
* @param int $contactId
*/
public static function setContext(&$form, $contactId = NULL) {
- $context = CRM_Utils_Request::retrieve('context', 'String', $form, FALSE, 'search');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form, FALSE, 'search');
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $form);
@@ -493,43 +492,43 @@ public static function &links(
$isUpdateBilling = FALSE
) {
if (!CRM_Utils_Array::value('view', self::$_links)) {
- self::$_links['view'] = array(
- CRM_Core_Action::VIEW => array(
+ self::$_links['view'] = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=view&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('View Membership'),
- ),
- );
+ ],
+ ];
}
if (!CRM_Utils_Array::value('all', self::$_links)) {
- $extraLinks = array(
- CRM_Core_Action::UPDATE => array(
+ $extraLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=update&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('Edit Membership'),
- ),
- CRM_Core_Action::RENEW => array(
+ ],
+ CRM_Core_Action::RENEW => [
'name' => ts('Renew'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=renew&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('Renew Membership'),
- ),
- CRM_Core_Action::FOLLOWUP => array(
+ ],
+ CRM_Core_Action::FOLLOWUP => [
'name' => ts('Renew-Credit Card'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=renew&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member&mode=live',
'title' => ts('Renew Membership Using Credit Card'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&context=membership&selectedChild=member',
'title' => ts('Delete Membership'),
- ),
- );
+ ],
+ ];
if (!$isPaymentProcessor || !$accessContribution) {
//unset the renew with credit card when payment
//processor is not available or user is not permitted to create contributions
@@ -540,25 +539,25 @@ public static function &links(
if ($isCancelSupported) {
$cancelMessage = ts('WARNING: If you cancel the recurring contribution associated with this membership, the membership will no longer be renewed automatically. However, the current membership status will not be affected.');
- self::$_links['all'][CRM_Core_Action::DISABLE] = array(
+ self::$_links['all'][CRM_Core_Action::DISABLE] = [
'name' => ts('Cancel Auto-renewal'),
'url' => 'civicrm/contribute/unsubscribe',
'qs' => 'reset=1&cid=%%cid%%&mid=%%id%%&context=membership&selectedChild=member',
'title' => ts('Cancel Auto Renew Subscription'),
'extra' => 'onclick = "if (confirm(\'' . $cancelMessage . '\') ) { return true; else return false;}"',
- );
+ ];
}
elseif (isset(self::$_links['all'][CRM_Core_Action::DISABLE])) {
unset(self::$_links['all'][CRM_Core_Action::DISABLE]);
}
if ($isUpdateBilling) {
- self::$_links['all'][CRM_Core_Action::MAP] = array(
+ self::$_links['all'][CRM_Core_Action::MAP] = [
'name' => ts('Change Billing Details'),
'url' => 'civicrm/contribute/updatebilling',
'qs' => 'reset=1&cid=%%cid%%&mid=%%id%%&context=membership&selectedChild=member',
'title' => ts('Change Billing Details'),
- );
+ ];
}
elseif (isset(self::$_links['all'][CRM_Core_Action::MAP])) {
unset(self::$_links['all'][CRM_Core_Action::MAP]);
@@ -574,20 +573,20 @@ public static function &links(
*/
public static function &membershipTypesLinks() {
if (!self::$_membershipTypesLinks) {
- self::$_membershipTypesLinks = array(
- CRM_Core_Action::VIEW => array(
+ self::$_membershipTypesLinks = [
+ CRM_Core_Action::VIEW => [
'name' => ts('Members'),
'url' => 'civicrm/member/search/',
'qs' => 'reset=1&force=1&type=%%id%%',
'title' => ts('Search'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/admin/member/membershipType',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Membership Type'),
- ),
- );
+ ],
+ ];
}
return self::$_membershipTypesLinks;
}
diff --git a/CRM/Member/Page/UserDashboard.php b/CRM/Member/Page/UserDashboard.php
index c83c4ce73e0f..5240ee9d818a 100644
--- a/CRM/Member/Page/UserDashboard.php
+++ b/CRM/Member/Page/UserDashboard.php
@@ -1,9 +1,9 @@
contact_id = $this->_contactId;
$dao->is_test = 0;
$dao->find();
while ($dao->fetch()) {
- $membership[$dao->id] = array();
+ $membership[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $membership[$dao->id]);
//get the membership status and type values.
$statusANDType = CRM_Member_BAO_Membership::getStatusANDTypeValues($dao->id);
- foreach (array(
+ foreach ([
'status',
'membership_type',
- ) as $fld) {
+ ] as $fld) {
$membership[$dao->id][$fld] = CRM_Utils_Array::value($fld, $statusANDType[$dao->id]);
}
if (!empty($statusANDType[$dao->id]['is_current_member'])) {
diff --git a/CRM/Member/PseudoConstant.php b/CRM/Member/PseudoConstant.php
index e51bf25bfac6..417de01f0f77 100644
--- a/CRM/Member/PseudoConstant.php
+++ b/CRM/Member/PseudoConstant.php
@@ -1,9 +1,9 @@
array(
+ self::$_links['view'] = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=member' . $extraParams,
'title' => ts('View Membership'),
- ),
- );
+ ],
+ ];
}
if (!isset(self::$_links['all']) || !self::$_links['all']) {
- $extraLinks = array(
- CRM_Core_Action::UPDATE => array(
+ $extraLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Membership'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Membership'),
- ),
- CRM_Core_Action::RENEW => array(
+ ],
+ CRM_Core_Action::RENEW => [
'name' => ts('Renew'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'reset=1&action=renew&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Renew Membership'),
- ),
- CRM_Core_Action::FOLLOWUP => array(
+ ],
+ CRM_Core_Action::FOLLOWUP => [
'name' => ts('Renew-Credit Card'),
'url' => 'civicrm/contact/view/membership',
'qs' => 'action=renew&reset=1&cid=%%cid%%&id=%%id%%&context=%%cxt%%&mode=live' . $extraParams,
'title' => ts('Renew Membership Using Credit Card'),
- ),
- );
+ ],
+ ];
if (!$isPaymentProcessor || !$accessContribution) {
//unset the renew with credit card when payment
//processor is not available or user not permitted to make contributions
@@ -251,12 +251,12 @@ public static function &links(
}
if ($isCancelSupported) {
- self::$_links['all'][CRM_Core_Action::DISABLE] = array(
+ self::$_links['all'][CRM_Core_Action::DISABLE] = [
'name' => ts('Cancel Auto-renewal'),
'url' => 'civicrm/contribute/unsubscribe',
'qs' => 'reset=1&mid=%%id%%&context=%%cxt%%' . $extraParams,
'title' => ts('Cancel Auto Renew Subscription'),
- );
+ ];
}
elseif (isset(self::$_links['all'][CRM_Core_Action::DISABLE])) {
unset(self::$_links['all'][CRM_Core_Action::DISABLE]);
@@ -316,7 +316,7 @@ public function getTotalCount($action) {
* @param string $output
* What should the result set include (web/email/csv).
*
- * @return int
+ * @return array
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
@@ -350,10 +350,10 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
+ $rows = [];
//CRM-4418 check for view, edit, delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit memberships')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -363,7 +363,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
@@ -377,7 +377,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['campaign_id'] = $result->member_campaign_id;
if (!empty($row['member_is_test'])) {
- $row['membership_type'] = $row['membership_type'] . " (test)";
+ $row['membership_type'] = CRM_Core_TestEntity::appendTestText($row['membership_type']);
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->membership_id;
@@ -413,11 +413,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
}
$row['action'] = CRM_Core_Action::formLink($links,
$currentMask,
- array(
+ [
'id' => $result->membership_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('Renew') . '...',
FALSE,
'membership.selector.row',
@@ -428,11 +428,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
else {
$links = self::links('view');
$row['action'] = CRM_Core_Action::formLink($links, $mask,
- array(
+ [
'id' => $result->membership_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'membership.selector.row',
@@ -441,14 +441,18 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
}
- //does membership have auto renew CRM-7137.
- $autoRenew = FALSE;
- if (isset($result->membership_recur_id) && $result->membership_recur_id &&
- !CRM_Member_BAO_Membership::isSubscriptionCancelled($row['membership_id'])
- ) {
- $autoRenew = TRUE;
+ // Display Auto-renew status on page (0=disabled, 1=enabled, 2=enabled, but error
+ if (!empty($result->membership_recur_id)) {
+ if (CRM_Member_BAO_Membership::isSubscriptionCancelled($row['membership_id'])) {
+ $row['auto_renew'] = 2;
+ }
+ else {
+ $row['auto_renew'] = 1;
+ }
+ }
+ else {
+ $row['auto_renew'] = 0;
}
- $row['auto_renew'] = $autoRenew;
$row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
);
@@ -481,52 +485,52 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Type'),
'sort' => 'membership_type',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Member Since'),
'sort' => 'join_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Start Date'),
'sort' => 'membership_start_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('End Date'),
'sort' => 'membership_end_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Source'),
'sort' => 'membership_source',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'membership_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Auto-renew?'),
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact Type')),
- array(
+ $pre = [
+ ['desc' => ts('Contact Type')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
@@ -539,7 +543,7 @@ public function &getColumnHeaders($action = NULL, $output = NULL) {
* @return mixed
*/
public function alphabetQuery() {
- return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
+ return $this->_query->alphabetQuery();
}
/**
diff --git a/CRM/Member/StateMachine/Search.php b/CRM/Member/StateMachine/Search.php
index 49453bc2753c..fe95f9dcab7b 100644
--- a/CRM/Member/StateMachine/Search.php
+++ b/CRM/Member/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Member_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -80,7 +80,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Member/StatusOverrideTypes.php b/CRM/Member/StatusOverrideTypes.php
new file mode 100644
index 000000000000..05770d4da2d4
--- /dev/null
+++ b/CRM/Member/StatusOverrideTypes.php
@@ -0,0 +1,116 @@
+ 'Type 1 Label'] format
+ */
+ public static function getSelectOptions() {
+ return [
+ self::NO => ts('No'),
+ self::PERMANENT => ts('Override Permanently'),
+ self::UNTIL_DATE => ts('Override Until Selected Date'),
+ ];
+ }
+
+ /**
+ * Determines if the override type means
+ * that the membership is overridden or not.
+ * For now, only "NO" type means that the membership
+ * status is not overridden.
+ *
+ * @param $overrideType
+ *
+ * @return bool
+ */
+ public static function isOverridden($overrideType) {
+ if ($overrideType == self::NO) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ public static function isNo($overrideType) {
+ if ($overrideType != self::NO) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ public static function isPermanent($overrideType) {
+ if ($overrideType != self::PERMANENT) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ public static function isUntilDate($overrideType) {
+ if ($overrideType != self::UNTIL_DATE) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+}
diff --git a/CRM/Member/Task.php b/CRM/Member/Task.php
index 7f2da7b08e72..3d17b53fdf82 100644
--- a/CRM/Member/Task.php
+++ b/CRM/Member/Task.php
@@ -1,9 +1,9 @@
array(
+ public static function tasks() {
+ if (!self::$_tasks) {
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete memberships'),
'class' => 'CRM_Member_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Member_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export members'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- 4 => array(
- 'title' => ts('Email - send now'),
+ ],
+ self::TASK_EMAIL => [
+ 'title' => ts('Email - send now (to %1 or less)', [
+ 1 => Civi::settings()
+ ->get('simple_mail_limit'),
+ ]),
'class' => 'CRM_Member_Form_Task_Email',
'result' => TRUE,
- ),
- 5 => array(
+ ],
+ self::BATCH_UPDATE => [
'title' => ts('Update multiple memberships'),
- 'class' => array(
+ 'class' => [
'CRM_Member_Form_Task_PickProfile',
'CRM_Member_Form_Task_Batch',
- ),
+ ],
'result' => TRUE,
- ),
- 6 => array(
+ ],
+ self::LABEL_MEMBERS => [
'title' => ts('Mailing labels - print'),
- 'class' => array(
+ 'class' => [
'CRM_Member_Form_Task_Label',
- ),
+ ],
'result' => TRUE,
- ),
- 7 => array(
+ ],
+ self::PDF_LETTER => [
'title' => ts('Print/merge document for memberships'),
'class' => 'CRM_Member_Form_Task_PDFLetter',
'result' => FALSE,
- ),
- );
+ ],
+ self::SAVE_SEARCH => [
+ 'title' => ts('Group - create smart group'),
+ 'class' => 'CRM_Contact_Form_Task_SaveSearch',
+ 'result' => TRUE,
+ ],
+ self::SAVE_SEARCH_UPDATE => [
+ 'title' => ts('Group - update smart group'),
+ 'class' => 'CRM_Contact_Form_Task_SaveSearch_Update',
+ 'result' => TRUE,
+ ],
+ ];
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviMember')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit memberships')) {
- unset(self::$_tasks[5]);
+ unset(self::$_tasks[self::BATCH_UPDATE]);
}
- CRM_Utils_Hook::searchTasks('membership', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
@@ -134,13 +140,8 @@ public static function &tasks() {
* @return array
* the set of task titles
*/
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
+ public static function taskTitles() {
+ return parent::taskTitles();
}
/**
@@ -148,27 +149,29 @@ public static function &taskTitles() {
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit memberships')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- 4 => self::$_tasks[4]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ self::TASK_EMAIL => self::$_tasks[self::TASK_EMAIL]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviMember')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -184,13 +187,10 @@ public static function &permissionedTaskTitles($permission) {
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
- // make the print task by default
- $value = 2;
+ // Make the print task the default
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Member/Tokens.php b/CRM/Member/Tokens.php
index cc664cfec4a7..44100317acad 100644
--- a/CRM/Member/Tokens.php
+++ b/CRM/Member/Tokens.php
@@ -2,9 +2,9 @@
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.7 |
+ | CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
@@ -45,7 +45,7 @@ class CRM_Member_Tokens extends \Civi\Token\AbstractTokenSubscriber {
*/
public function __construct() {
parent::__construct('membership', array_merge(
- array(
+ [
'fee' => ts('Membership Fee'),
'id' => ts('Membership ID'),
'join_date' => ts('Membership Join Date'),
@@ -53,7 +53,7 @@ public function __construct() {
'end_date' => ts('Membership End Date'),
'status' => ts('Membership Status'),
'type' => ts('Membership Type'),
- ),
+ ],
CRM_Utils_Token::getCustomFieldTokens('Membership')
));
}
@@ -63,8 +63,7 @@ public function __construct() {
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
// Extracted from scheduled-reminders code. See the class description.
- return
- !empty($processor->context['actionMapping'])
+ return !empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_membership';
}
@@ -92,7 +91,7 @@ public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQuery
public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) {
$actionSearchResult = $row->context['actionSearchResult'];
- if (in_array($field, array('start_date', 'end_date', 'join_date'))) {
+ if (in_array($field, ['start_date', 'end_date', 'join_date'])) {
$row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->$field));
}
elseif (isset($actionSearchResult->$field)) {
diff --git a/CRM/Note/Form/Note.php b/CRM/Note/Form/Note.php
index be20ded1b99e..9e1cfeebde32 100644
--- a/CRM/Note/Form/Note.php
+++ b/CRM/Note/Form/Note.php
@@ -1,9 +1,9 @@
_action & CRM_Core_Action::UPDATE) {
if (isset($this->_id)) {
@@ -112,6 +112,20 @@ public function setDefaultValues() {
return $defaults;
}
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'Note';
+ }
+
+ /**
+ * Explicitly declare the form context.
+ */
+ public function getDefaultContext() {
+ return 'create';
+ }
+
/**
* Build the form object.
*
@@ -119,41 +133,39 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
return;
}
- $this->add('text', 'subject', ts('Subject:'), array('size' => 20));
- $this->add('textarea', 'note', ts('Note:'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note', 'note'), TRUE);
- $this->add('select', 'privacy', ts('Privacy:'), CRM_Core_OptionGroup::values('note_privacy'));
-
+ $this->addField('subject');
+ $this->addField('note', [], TRUE);
+ $this->addField('privacy');
$this->add('hidden', 'parent_id');
// add attachments part
CRM_Core_BAO_File::buildAttachment($this, 'civicrm_note', $this->_id, NULL, TRUE);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
}
@@ -190,7 +202,7 @@ public function postProcess() {
// add attachments as needed
CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_note', $params['id']);
- $ids = array();
+ $ids = [];
$note = CRM_Core_BAO_Note::add($params, $ids);
CRM_Core_Session::setStatus(ts('Your Note has been saved.'), ts('Saved'), 'success');
diff --git a/CRM/PCP/BAO/PCP.php b/CRM/PCP/BAO/PCP.php
index 16f38739c335..367fa10429a3 100644
--- a/CRM/PCP/BAO/PCP.php
+++ b/CRM/PCP/BAO/PCP.php
@@ -1,9 +1,9 @@
array($contactId, 'Integer'));
+ $params = [1 => [$contactId, 'Integer']];
$pcpInfoDao = CRM_Core_DAO::executeQuery($query, $params);
- $pcpInfo = array();
+ $pcpInfo = [];
$hide = $mask = array_sum(array_keys($links['all']));
- $contactPCPPages = array();
+ $contactPCPPages = [];
$event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
$contribute = CRM_Contribute_PseudoConstant::contributionPage();
@@ -128,11 +128,11 @@ public static function getPcpDashboardInfo($contactId) {
while ($pcpInfoDao->fetch()) {
$mask = $hide;
if ($links) {
- $replace = array(
+ $replace = [
'pcpId' => $pcpInfoDao->id,
'pcpBlock' => $pcpInfoDao->pcp_block_id,
'pageComponent' => $pcpInfoDao->page_type,
- );
+ ];
}
$pcpLink = $links['all'];
@@ -156,14 +156,14 @@ public static function getPcpDashboardInfo($contactId) {
$component = $pcpInfoDao->page_type;
$pageTitle = CRM_Utils_Array::value($pcpInfoDao->page_id, $$component);
- $pcpInfo[] = array(
+ $pcpInfo[] = [
'pageTitle' => $pageTitle,
'pcpId' => $pcpInfoDao->id,
'pcpTitle' => $pcpInfoDao->title,
'pcpStatus' => $pcpStatus[$pcpInfoDao->status_id],
'action' => $action,
'class' => $class,
- );
+ ];
$contactPCPPages[$pcpInfoDao->page_type][] = $pcpInfoDao->page_id;
}
@@ -188,30 +188,30 @@ public static function getPcpDashboardInfo($contactId) {
ORDER BY target_entity_type, target_entity_id
";
$pcpBlockDao = CRM_Core_DAO::executeQuery($query);
- $pcpBlock = array();
+ $pcpBlock = [];
$mask = 0;
while ($pcpBlockDao->fetch()) {
if ($links) {
- $replace = array(
+ $replace = [
'pageId' => $pcpBlockDao->target_entity_id,
'pageComponent' => $pcpBlockDao->target_entity_type,
- );
+ ];
}
$pcpLink = $links['add'];
$action = CRM_Core_Action::formLink($pcpLink, $mask, $replace, ts('more'),
FALSE, 'pcp.dashboard.other', "{$pcpBlockDao->target_entity_type}_PCP", $pcpBlockDao->target_entity_id);
$component = $pcpBlockDao->target_entity_type;
if ($pageTitle = CRM_Utils_Array::value($pcpBlockDao->target_entity_id, $$component)) {
- $pcpBlock[] = array(
+ $pcpBlock[] = [
'pageId' => $pcpBlockDao->target_entity_id,
'pageTitle' => $pageTitle,
'action' => $action,
- );
+ ];
}
}
- return array($pcpBlock, $pcpInfo);
+ return [$pcpBlock, $pcpInfo];
}
/**
@@ -231,7 +231,7 @@ public static function thermoMeter($pcpId) {
LEFT JOIN civicrm_contribution cc ON ( cs.contribution_id = cc.id)
WHERE pcp.id = %1 AND cc.contribution_status_id =1 AND cc.is_test = 0";
- $params = array(1 => array($pcpId, 'Integer'));
+ $params = [1 => [$pcpId, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -254,7 +254,7 @@ public static function honorRoll($pcpId) {
AND contribution_status_id = 1
AND is_test = 0";
$dao = CRM_Core_DAO::executeQuery($query);
- $honor = array();
+ $honor = [];
while ($dao->fetch()) {
$honor[$dao->id]['nickname'] = ucwords($dao->pcp_roll_nickname);
$honor[$dao->id]['total_amount'] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
@@ -273,61 +273,61 @@ public static function &pcpLinks() {
if (!(self::$_pcpLinks)) {
$deleteExtra = ts('Are you sure you want to delete this Personal Campaign Page?') . '\n' . ts('This action cannot be undone.');
- self::$_pcpLinks['add'] = array(
- CRM_Core_Action::ADD => array(
+ self::$_pcpLinks['add'] = [
+ CRM_Core_Action::ADD => [
'name' => ts('Create a Personal Campaign Page'),
'class' => 'no-popup',
'url' => 'civicrm/contribute/campaign',
'qs' => 'action=add&reset=1&pageId=%%pageId%%&component=%%pageComponent%%',
'title' => ts('Configure'),
- ),
- );
+ ],
+ ];
- self::$_pcpLinks['all'] = array(
- CRM_Core_Action::UPDATE => array(
+ self::$_pcpLinks['all'] = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Your Page'),
'url' => 'civicrm/pcp/info',
'qs' => 'action=update&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Configure'),
- ),
- CRM_Core_Action::DETACH => array(
+ ],
+ CRM_Core_Action::DETACH => [
'name' => ts('Tell Friends'),
'url' => 'civicrm/friend',
'qs' => 'eid=%%pcpId%%&blockId=%%pcpBlock%%&reset=1&pcomponent=pcp&component=%%pageComponent%%',
'title' => ts('Tell Friends'),
- ),
- CRM_Core_Action::VIEW => array(
+ ],
+ CRM_Core_Action::VIEW => [
'name' => ts('URL for this Page'),
'url' => 'civicrm/pcp/info',
'qs' => 'reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('URL for this Page'),
- ),
- CRM_Core_Action::BROWSE => array(
+ ],
+ CRM_Core_Action::BROWSE => [
'name' => ts('Update Contact Information'),
'url' => 'civicrm/pcp/info',
'qs' => 'action=browse&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Update Contact Information'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'url' => 'civicrm/pcp',
'qs' => 'action=enable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Enable'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'url' => 'civicrm/pcp',
'qs' => 'action=disable&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'title' => ts('Disable'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/pcp',
'qs' => 'action=delete&reset=1&id=%%pcpId%%&component=%%pageComponent%%',
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
'title' => ts('Delete'),
- ),
- );
+ ],
+ ];
}
return self::$_pcpLinks;
}
@@ -360,20 +360,20 @@ public static function deleteById($id) {
* Form object.
*/
public static function buildPCPForm($form) {
- $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"));
+ $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"]);
$form->addElement('checkbox', 'is_approval_needed', ts('Approval required'));
- $profile = array();
+ $profile = [];
$isUserRequired = NULL;
$config = CRM_Core_Config::singleton();
if ($config->userFramework != 'Standalone') {
$isUserRequired = 2;
}
- CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, array(
+ CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, [
'title',
'is_active',
- ));
+ ]);
if (!empty($profiles)) {
foreach ($profiles as $key => $value) {
if ($value['is_active']) {
@@ -383,15 +383,15 @@ public static function buildPCPForm($form) {
$form->assign('profile', $profile);
}
- $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), array('' => ts('- select -')) + $profile, TRUE);
+ $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), ['' => ts('- select -')] + $profile, TRUE);
//CRM-15821 - To add new option for PCP "Owner" notification
$ownerNotifications = CRM_Core_OptionGroup::values('pcp_owner_notify');
$form->addRadio('owner_notify_id', ts('Owner Email Notification'), $ownerNotifications, NULL, ' ', TRUE);
- $form->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), NULL, array('onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"));
+ $form->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), NULL, ['onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"]);
- $form->add('text',
+ $form->add('number',
'tellfriend_limit',
ts("'Tell a friend' maximum recipients limit"),
CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'tellfriend_limit')
@@ -407,28 +407,27 @@ public static function buildPCPForm($form) {
$form->add('text', 'notify_email', ts('Notify Email'), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'notify_email'));
}
-
/**
* Add PCP form elements to a form.
*
* @param int $pcpId
- * @param CRM_Core_Page $page
+ * @param CRM_Core_Form $page
* @param null $elements
*/
public static function buildPcp($pcpId, &$page, &$elements = NULL) {
- $prms = array('id' => $pcpId);
+ $prms = ['id' => $pcpId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($pcpId)) {
if ($pcpInfo['page_type'] == 'event') {
- $pcp_supporter_text = ts('This event registration is being made thanks to the efforts of %1, who supports our campaign. ', array(1 => $pcpSupporter));
+ $pcp_supporter_text = ts('This event registration is being made thanks to the efforts of %1, who supports our campaign. ', [1 => $pcpSupporter]);
$text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'event');
if (!empty($text)) {
$pcp_supporter_text .= "You can support it as well - once you complete the registration, you will be able to create your own Personal Campaign Page!";
}
}
else {
- $pcp_supporter_text = ts('This contribution is being made thanks to the efforts of %1, who supports our campaign. ', array(1 => $pcpSupporter));
+ $pcp_supporter_text = ts('This contribution is being made thanks to the efforts of %1, who supports our campaign. ', [1 => $pcpSupporter]);
$text = CRM_PCP_BAO_PCP::getPcpBlockStatus($pcpInfo['page_id'], 'contribute');
if (!empty($text)) {
$pcp_supporter_text .= "You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!";
@@ -443,17 +442,17 @@ public static function buildPcp($pcpId, &$page, &$elements = NULL) {
if ($pcpInfo['is_honor_roll']) {
$page->assign('is_honor_roll', TRUE);
$page->add('checkbox', 'pcp_display_in_roll', ts('Show my support in the public honor roll'), NULL, NULL,
- array('onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );")
+ ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
);
- $extraOption = array('onclick' => "return pcpAnonymous( );");
- $elements = array();
+ $extraOption = ['onclick' => "return pcpAnonymous( );"];
+ $elements = [];
$elements[] = &$page->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
$elements[] = &$page->createElement('radio', NULL, '', ts('List my support anonymously'), 1, $extraOption);
$page->addGroup($elements, 'pcp_is_anonymous', NULL, ' ');
$page->_defaults['pcp_is_anonymous'] = 0;
- $page->add('text', 'pcp_roll_nickname', ts('Name'), array('maxlength' => 30));
- $page->add('textarea', "pcp_personal_note", ts('Personal Note'), array('style' => 'height: 3em; width: 40em;'));
+ $page->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
+ $page->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
}
else {
$page->assign('is_honor_roll', FALSE);
@@ -477,17 +476,16 @@ public static function handlePcp($pcpId, $component, $entity) {
return FALSE;
}
- $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
+ $pcpStatus = CRM_Core_PseudoConstant::get('CRM_PCP_BAO_PCP', 'status_id');
+ $approvedId = array_search('Approved', $pcpStatus);
- $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
-
- $params = array('id' => $pcpId);
+ $params = ['id' => $pcpId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
- $params = array('id' => $pcpInfo['pcp_block_id']);
+ $params = ['id' => $pcpInfo['pcp_block_id']];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlock);
- $params = array('id' => $pcpInfo['page_id']);
+ $params = ['id' => $pcpInfo['page_id']];
$now = time();
if ($component == 'event') {
@@ -507,13 +505,14 @@ public static function handlePcp($pcpId, $component, $entity) {
// define redirect url back to contrib page or event if needed
$url = CRM_Utils_System::url($urlBase, "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE);
+ $currentPCPStatus = CRM_Core_PseudoConstant::getName('CRM_PCP_BAO_PCP', 'status_id', $pcpInfo['status_id']);
if ($pcpBlock['target_entity_id'] != $entity['id']) {
$statusMessage = ts('This page is not related to the Personal Campaign Page you have just visited. However you can still make a contribution here.');
CRM_Core_Error::statusBounce($statusMessage, $url);
}
- elseif ($pcpInfo['status_id'] != $approvedId) {
- $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign here.', array(1 => $pcpStatus[$pcpInfo['status_id']]));
+ elseif ($currentPCPStatus !== 'Approved') {
+ $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign here.', [1 => $pcpStatus[$pcpInfo['status_id']]]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
elseif (empty($pcpBlock['is_active'])) {
@@ -530,12 +529,12 @@ public static function handlePcp($pcpId, $component, $entity) {
$customEndDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $entity));
if ($startDate && $endDate) {
$statusMessage = ts('The Personal Campaign Page you have just visited is only active from %1 to %2. However you can still support the campaign here.',
- array(1 => $customStartDate, 2 => $customEndDate)
+ [1 => $customStartDate, 2 => $customEndDate]
);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
elseif ($startDate) {
- $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign here.', array(1 => $customStartDate));
+ $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign here.', [1 => $customStartDate]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
elseif ($endDate) {
@@ -545,21 +544,21 @@ public static function handlePcp($pcpId, $component, $entity) {
"reset=1&id={$pcpBlock['entity_id']}",
FALSE, NULL, FALSE, TRUE
);
- $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', array(1 => $customEndDate));
+ $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', [1 => $customEndDate]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
else {
- $statusMessage = ts('The Personal Campaign Page you have just visited is no longer active (as of %1). However you can still support the campaign here.', array(1 => $customEndDate));
+ $statusMessage = ts('The Personal Campaign Page you have just visited is no longer active (as of %1). However you can still support the campaign here.', [1 => $customEndDate]);
CRM_Core_Error::statusBounce($statusMessage, $url);
}
}
}
- return array(
+ return [
'pcpId' => $pcpId,
'pcpBlock' => $pcpBlock,
'pcpInfo' => $pcpInfo,
- );
+ ];
}
/**
@@ -589,10 +588,10 @@ public static function setIsActive($id, $is_active) {
$pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
$pcpStatus = $pcpStatus[$is_active];
- CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", array(
+ CRM_Core_Session::setStatus(ts("%1 status has been updated to %2.", [
1 => $pcpTitle,
2 => $pcpStatus,
- )), 'Status Updated', 'success');
+ ]), 'Status Updated', 'success');
// send status change mail
$result = self::sendStatusUpdate($id, $is_active, FALSE, $pcpPageType);
@@ -636,30 +635,30 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
// used in subject templates
$contribPageTitle = self::getPcpPageTitle($pcpId, $component);
- $tplParams = array(
+ $tplParams = [
'loginUrl' => $loginURL,
'contribPageTitle' => $contribPageTitle,
'pcpId' => $pcpId,
- );
+ ];
//get the default domain email address.
list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
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]));
}
$receiptFrom = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
// get recipient (supporter) name and email
- $params = array('id' => $pcpId);
+ $params = ['id' => $pcpId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($pcpInfo['contact_id']);
// get pcp block info
list($blockId, $eid) = self::getPcpBlockEntityId($pcpId, $component);
- $params = array('id' => $blockId);
+ $params = ['id' => $blockId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlockInfo);
// assign urls required in email template
@@ -689,7 +688,7 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
$tplName = $isInitial ? 'pcp_supporter_notify' : 'pcp_status_change';
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => $tplName,
'contactId' => $pcpInfo['contact_id'],
@@ -697,7 +696,7 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
'from' => $receiptFrom,
'toName' => $name,
'toEmail' => $address,
- )
+ ]
);
return $sent;
}
@@ -709,7 +708,9 @@ public static function sendStatusUpdate($pcpId, $newStatus, $isInitial = FALSE,
* Campaign page id.
*
* @param bool $is_active
- * @return null
+ *
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setDisable($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_PCP_DAO_PCP', $id, 'is_active', $is_active);
@@ -733,7 +734,7 @@ public static function getStatus($pcpId, $component) {
$entity_table = self::getPcpEntityTable($component);
- $params = array(1 => array($pcpId, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$pcpId, 'Integer'], 2 => [$entity_table, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -755,7 +756,7 @@ public static function getPcpBlockStatus($pageId, $component) {
$entity_table = self::getPcpEntityTable($component);
- $params = array(1 => array($pageId, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$pageId, 'Integer'], 2 => [$entity_table, 'String']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -773,7 +774,7 @@ public static function getPcpBlockInUse($id) {
FROM civicrm_pcp pcp
WHERE pcp.pcp_block_id = %1";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$result = CRM_Core_DAO::singleValueQuery($query, $params);
return $result > 0;
}
@@ -792,7 +793,7 @@ public static function checkEmailProfile($profileId) {
FROM civicrm_uf_field
WHERE field_name like 'email%' And is_active = 1 And uf_group_id = %1";
- $params = array(1 => array($profileId, 'Integer'));
+ $params = [1 => [$profileId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if (!$dao->fetch()) {
return TRUE;
@@ -824,7 +825,7 @@ public static function getPcpPageTitle($pcpId, $component) {
WHERE pcp.id = %1";
}
- $params = array(1 => array($pcpId, 'Integer'));
+ $params = [1 => [$pcpId, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $params);
}
@@ -845,13 +846,13 @@ public static function getPcpBlockEntityId($pcpId, $component) {
LEFT JOIN civicrm_pcp_block pb ON ( pb.entity_id = pcp.page_id AND pb.entity_table = %2 )
WHERE pcp.id = %1";
- $params = array(1 => array($pcpId, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$pcpId, 'Integer'], 2 => [$entity_table, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
- return array($dao->pcpBlockId, $dao->entity_id);
+ return [$dao->pcpBlockId, $dao->entity_id];
}
- return array();
+ return [];
}
/**
@@ -862,12 +863,12 @@ public static function getPcpBlockEntityId($pcpId, $component) {
* @return string
*/
public static function getPcpEntityTable($component) {
- $entity_table_map = array(
+ $entity_table_map = [
'event' => 'civicrm_event',
'civicrm_event' => 'civicrm_event',
'contribute' => 'civicrm_contribution_page',
'civicrm_contribution_page' => 'civicrm_contribution_page',
- );
+ ];
return isset($entity_table_map[$component]) ? $entity_table_map[$component] : FALSE;
}
@@ -891,7 +892,7 @@ public static function getSupporterProfileId($component_id, $component = 'contri
AND pcp.entity_table = %2
AND ufgroup.is_active = 1";
- $params = array(1 => array($component_id, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$component_id, 'Integer'], 2 => [$entity_table, 'String']];
if (!$supporterProfileId = CRM_Core_DAO::singleValueQuery($query, $params)) {
CRM_Core_Error::fatal(ts('Supporter profile is not set for this Personal Campaign Page or the profile is disabled. Please contact the site administrator if you need assistance.'));
}
@@ -914,7 +915,7 @@ public static function getOwnerNotificationId($component_id, $component = 'contr
SELECT pb.owner_notify_id
FROM civicrm_pcp_block pb
WHERE pb.entity_id = %1 AND pb.entity_table = %2";
- $params = array(1 => array($component_id, 'Integer'), 2 => array($entity_table, 'String'));
+ $params = [1 => [$component_id, 'Integer'], 2 => [$entity_table, 'String']];
if (!$ownerNotificationId = CRM_Core_DAO::singleValueQuery($query, $params)) {
CRM_Core_Error::fatal(ts('Owner Notification is not set for this Personal Campaign Page. Please contact the site administrator if you need assistance.'));
}
diff --git a/CRM/PCP/BAO/PCPBlock.php b/CRM/PCP/BAO/PCPBlock.php
index c30976e8b907..653d01005b55 100644
--- a/CRM/PCP/BAO/PCPBlock.php
+++ b/CRM/PCP/BAO/PCPBlock.php
@@ -1,9 +1,9 @@
__table = 'civicrm_pcp';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'pcp_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'pcp_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Personal Campaign Page ID') ,
- 'description' => 'Personal Campaign Page ID',
- 'required' => true,
+ 'title' => ts('Personal Campaign Page ID'),
+ 'description' => ts('Personal Campaign Page ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- ) ,
- 'pcp_contact_id' => array(
+ ],
+ 'pcp_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'FK to Contact ID',
- 'required' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('FK to Contact ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.contact_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'status_id' => array(
+ ],
+ ],
+ 'status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Personal Campaign Page Status') ,
- 'required' => true,
+ 'title' => ts('Personal Campaign Page Status'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.status_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'pcp_status',
'optionEditPath' => 'civicrm/admin/options/pcp_status',
- )
- ) ,
- 'title' => array(
+ ]
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Personal Campaign Page Title') ,
+ 'title' => ts('Personal Campaign Page Title'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp.title',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'intro_text' => array(
+ ],
+ ],
+ 'intro_text' => [
'name' => 'intro_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Intro Text') ,
+ 'title' => ts('Intro Text'),
+ 'where' => 'civicrm_pcp.intro_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'page_text' => array(
+ ],
+ ],
+ 'page_text' => [
'name' => 'page_text',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Page Text') ,
+ 'title' => ts('Page Text'),
+ 'where' => 'civicrm_pcp.page_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'donate_link_text' => array(
+ ],
+ ],
+ 'donate_link_text' => [
'name' => 'donate_link_text',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Donate Link Text') ,
+ 'title' => ts('Donate Link Text'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp.donate_link_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'page_id' => array(
+ ],
+ ],
+ 'page_id' => [
'name' => 'page_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution Page') ,
- 'description' => 'The Contribution or Event Page which triggered this pcp',
- 'required' => true,
+ 'title' => ts('Contribution Page'),
+ 'description' => ts('The Contribution or Event Page which triggered this pcp'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.page_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- ) ,
- 'page_type' => array(
+ ],
+ 'page_type' => [
'name' => 'page_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('PCP Page Type') ,
- 'description' => 'The type of PCP this is: contribute or event',
+ 'title' => ts('PCP Page Type'),
+ 'description' => ts('The type of PCP this is: contribute or event'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pcp.page_type',
'default' => 'contribute',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'pcp_block_id' => array(
+ ],
+ ],
+ 'pcp_block_id' => [
'name' => 'pcp_block_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('PCP Block') ,
- 'description' => 'The pcp block that this pcp page was created from',
- 'required' => true,
+ 'title' => ts('PCP Block'),
+ 'description' => ts('The pcp block that this pcp page was created from'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp.pcp_block_id',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- ) ,
- 'is_thermometer' => array(
+ ],
+ 'is_thermometer' => [
'name' => 'is_thermometer',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Use Thermometer?') ,
+ 'title' => ts('Use Thermometer?'),
+ 'where' => 'civicrm_pcp.is_thermometer',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_honor_roll' => array(
+ ],
+ ],
+ 'is_honor_roll' => [
'name' => 'is_honor_roll',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Show Honor Roll?') ,
+ 'title' => ts('Show Honor Roll?'),
+ 'where' => 'civicrm_pcp.is_honor_roll',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'goal_amount' => array(
+ ],
+ ],
+ 'goal_amount' => [
'name' => 'goal_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Goal Amount') ,
- 'description' => 'Goal amount of this Personal Campaign Page.',
- 'precision' => array(
+ 'title' => ts('Goal Amount'),
+ 'description' => ts('Goal amount of this Personal Campaign Page.'),
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_pcp.goal_amount',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_pcp.currency',
'default' => 'NULL',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'is_active' => array(
+ ]
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
- 'description' => 'Is Personal Campaign Page enabled/active?',
+ 'title' => ts('Enabled?'),
+ 'description' => ts('Is Personal Campaign Page enabled/active?'),
+ 'where' => 'civicrm_pcp.is_active',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_notify' => array(
+ ],
+ ],
+ 'is_notify' => [
'name' => 'is_notify',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Notify Owner?') ,
- 'description' => 'Notify owner via email when someone donates to page?',
+ 'title' => ts('Notify Owner?'),
+ 'description' => ts('Notify owner via email when someone donates to page?'),
+ 'where' => 'civicrm_pcp.is_notify',
+ 'default' => '0',
'table_name' => 'civicrm_pcp',
'entity' => 'PCP',
'bao' => 'CRM_PCP_BAO_PCP',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -434,10 +447,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -445,15 +459,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/PCP/DAO/PCPBlock.php b/CRM/PCP/DAO/PCPBlock.php
index f3a4f7a7c24e..2d93ff55c85f 100644
--- a/CRM/PCP/DAO/PCPBlock.php
+++ b/CRM/PCP/DAO/PCPBlock.php
@@ -1,353 +1,363 @@
__table = 'civicrm_pcp_block';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'supporter_profile_id', 'civicrm_uf_group', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'target_entity_id', NULL, 'id', 'target_entity_type');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'supporter_profile_id', 'civicrm_uf_group', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'target_entity_id', NULL, 'id', 'target_entity_type');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('PCP Block ID') ,
- 'description' => 'PCP block Id',
- 'required' => true,
+ 'title' => ts('PCP Block ID'),
+ 'description' => ts('PCP block Id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp_block.id',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
+ 'title' => ts('Entity Table'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pcp_block.entity_table',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity') ,
- 'description' => 'FK to civicrm_contribution_page.id OR civicrm_event.id',
- 'required' => true,
+ 'title' => ts('Entity'),
+ 'description' => ts('FK to civicrm_contribution_page.id OR civicrm_event.id'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp_block.entity_id',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'target_entity_type' => array(
+ ],
+ 'target_entity_type' => [
'name' => 'target_entity_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Target Entity') ,
- 'description' => 'The type of entity that this pcp targets',
- 'required' => true,
+ 'title' => ts('Target Entity'),
+ 'description' => ts('The type of entity that this pcp targets'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp_block.target_entity_type',
'default' => 'contribute',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'target_entity_id' => array(
+ ],
+ 'target_entity_id' => [
'name' => 'target_entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Target Entity ID') ,
- 'description' => 'The entity that this pcp targets',
- 'required' => true,
+ 'title' => ts('Target Entity ID'),
+ 'description' => ts('The entity that this pcp targets'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pcp_block.target_entity_id',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'supporter_profile_id' => array(
+ ],
+ 'supporter_profile_id' => [
'name' => 'supporter_profile_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Supporter Profile') ,
- 'description' => 'FK to civicrm_uf_group.id. Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?',
+ 'title' => ts('Supporter Profile'),
+ 'description' => ts('FK to civicrm_uf_group.id. Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?'),
+ 'where' => 'civicrm_pcp_block.supporter_profile_id',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_UFGroup',
- ) ,
- 'owner_notify_id' => array(
+ ],
+ 'owner_notify_id' => [
'name' => 'owner_notify_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Owner Notification') ,
- 'description' => 'FK to civicrm_option_group with name = PCP owner notifications',
+ 'title' => ts('Owner Notification'),
+ 'description' => ts('FK to civicrm_option_group with name = PCP owner notifications'),
+ 'where' => 'civicrm_pcp_block.owner_notify_id',
+ 'default' => '0',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Radio',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'pcp_owner_notify',
'optionEditPath' => 'civicrm/admin/options/pcp_owner_notify',
- )
- ) ,
- 'is_approval_needed' => array(
+ ]
+ ],
+ 'is_approval_needed' => [
'name' => 'is_approval_needed',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Approval Required?') ,
- 'description' => 'Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?',
+ 'title' => ts('Approval Required?'),
+ 'description' => ts('Does Personal Campaign Page require manual activation by administrator? (is inactive by default after setup)?'),
+ 'where' => 'civicrm_pcp_block.is_approval_needed',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'is_tellfriend_enabled' => array(
+ ],
+ 'is_tellfriend_enabled' => [
'name' => 'is_tellfriend_enabled',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Tell a Friend Enabled?') ,
- 'description' => 'Does Personal Campaign Page allow using tell a friend?',
+ 'title' => ts('Tell a Friend Enabled?'),
+ 'description' => ts('Does Personal Campaign Page allow using tell a friend?'),
+ 'where' => 'civicrm_pcp_block.is_tellfriend_enabled',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'tellfriend_limit' => array(
+ ],
+ 'tellfriend_limit' => [
'name' => 'tellfriend_limit',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Tell A Friend Limit') ,
- 'description' => 'Maximum recipient fields allowed in tell a friend',
+ 'title' => ts('Tell A Friend Limit'),
+ 'description' => ts('Maximum recipient fields allowed in tell a friend'),
+ 'where' => 'civicrm_pcp_block.tellfriend_limit',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'link_text' => array(
+ ],
+ 'link_text' => [
'name' => 'link_text',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Link Text') ,
- 'description' => 'Link text for PCP.',
+ 'title' => ts('Link Text'),
+ 'description' => ts('Link text for PCP.'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp_block.link_text',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 1,
- ) ,
- 'is_active' => array(
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Enabled?') ,
- 'description' => 'Is Personal Campaign Page Block enabled/active?',
+ 'title' => ts('Enabled?'),
+ 'description' => ts('Is Personal Campaign Page Block enabled/active?'),
+ 'where' => 'civicrm_pcp_block.is_active',
'default' => '1',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- 'notify_email' => array(
+ ],
+ 'notify_email' => [
'name' => 'notify_email',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Notification Email') ,
- 'description' => 'If set, notification is automatically emailed to this email-address on create/update Personal Campaign Page',
+ 'title' => ts('Notification Email'),
+ 'description' => ts('If set, notification is automatically emailed to this email-address on create/update Personal Campaign Page'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pcp_block.notify_email',
'default' => 'NULL',
'table_name' => 'civicrm_pcp_block',
'entity' => 'PCPBlock',
'bao' => 'CRM_PCP_BAO_PCPBlock',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -355,10 +365,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp_block', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pcp_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -366,15 +377,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp_block', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pcp_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/PCP/Form/Campaign.php b/CRM/PCP/Form/Campaign.php
index 4245978bfdd5..fe2bb9880fa9 100644
--- a/CRM/PCP/Form/Campaign.php
+++ b/CRM/PCP/Form/Campaign.php
@@ -1,9 +1,9 @@
_component = CRM_Utils_Request::retrieve('component', 'String', $this);
$this->assign('component', $this->_component);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('context', $this->_context);
$this->_pageId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
@@ -71,7 +71,7 @@ public function preProcess() {
* Default values for the form.
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$dao = new CRM_PCP_DAO_PCP();
if ($this->_pageId) {
@@ -110,21 +110,21 @@ public function buildQuickForm() {
$this->add('text', 'goal_amount', ts('Your Goal'), NULL, TRUE);
$this->addRule('goal_amount', ts('Goal Amount should be a numeric value'), 'money');
- $attributes = array();
+ $attributes = [];
if ($this->_component == 'event') {
if ($this->get('action') & CRM_Core_Action::ADD) {
- $attributes = array('value' => ts('Join Us'), 'onClick' => 'select();');
+ $attributes = ['value' => ts('Join Us'), 'onClick' => 'select();'];
}
$this->add('text', 'donate_link_text', ts('Sign up Button'), $attributes);
}
else {
if ($this->get('action') & CRM_Core_Action::ADD) {
- $attributes = array('value' => ts('Donate Now'), 'onClick' => 'select();');
+ $attributes = ['value' => ts('Donate Now'), 'onClick' => 'select();'];
}
$this->add('text', 'donate_link_text', ts('Donation Button'), $attributes);
}
- $attrib = array('rows' => 8, 'cols' => 60);
+ $attrib = ['rows' => 8, 'cols' => 60];
$this->add('textarea', 'page_text', ts('Your Message'), NULL, FALSE);
$maxAttachments = 1;
@@ -133,14 +133,14 @@ public function buildQuickForm() {
$this->addElement('checkbox', 'is_thermometer', ts('Progress Bar'));
$this->addElement('checkbox', 'is_honor_roll', ts('Honor Roll'), NULL);
if ($this->_pageId) {
- $params = array('id' => $this->_pageId);
+ $params = ['id' => $this->_pageId];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
- $owner_notification_option = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
+ $owner_notification_option = CRM_Core_DAO::getFieldValue('CRM_PCP_BAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
}
else {
$owner_notification_option = CRM_PCP_BAO_PCP::getOwnerNotificationId($this->controller->get('component_page_id'), $this->_component ? $this->_component : 'contribute');
}
- if ($owner_notification_option == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name')) {
+ if ($owner_notification_option == CRM_Core_PseudoConstant::getKey('CRM_PCP_BAO_PCPBlock', 'owner_notify_id', 'owner_chooses')) {
$this->assign('owner_notification_option', TRUE);
$this->addElement('checkbox', 'is_notify', ts('Notify me via email when someone donates to my page'), NULL);
}
@@ -151,19 +151,19 @@ public function buildQuickForm() {
}
$this->addButtons(
- array(
- array(
+ [
+ [
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
+ ],
+ ]
);
- $this->addFormRule(array('CRM_PCP_Form_Campaign', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_Campaign', 'formRule'], $this);
}
/**
@@ -180,7 +180,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($fields['goal_amount'] <= 0) {
$errors['goal_amount'] = ts('Goal Amount should be a numeric value greater than zero.');
}
@@ -195,7 +195,7 @@ public static function formRule($fields, $files, $self) {
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
- $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active', 'is_notify');
+ $checkBoxes = ['is_thermometer', 'is_honor_roll', 'is_active', 'is_notify'];
foreach ($checkBoxes as $key) {
if (!isset($params[$key])) {
@@ -215,7 +215,7 @@ public function postProcess() {
// since we are allowing html input from the user
// we also need to purify it, so lets clean it up
- $htmlFields = array('intro_text', 'page_text', 'title');
+ $htmlFields = ['intro_text', 'page_text', 'title'];
foreach ($htmlFields as $field) {
if (!empty($params[$field])) {
$params[$field] = CRM_Utils_String::purifyHTML($params[$field]);
@@ -256,10 +256,10 @@ public function postProcess() {
$statusId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp->id, 'status_id');
//send notification of PCP create/update.
- $pcpParams = array('entity_table' => $entity_table, 'entity_id' => $pcp->page_id);
- $notifyParams = array();
+ $pcpParams = ['entity_table' => $entity_table, 'entity_id' => $pcp->page_id];
+ $notifyParams = [];
$notifyStatus = "";
- CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email'));
+ CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, ['notify_email']);
if ($emails = $pcpBlock->notify_email) {
$this->assign('pcpTitle', $pcp->title);
@@ -307,7 +307,7 @@ public function postProcess() {
$managePCPUrl = CRM_Utils_System::url('civicrm/admin/pcp',
"reset=1",
TRUE, NULL, FALSE,
- FALSE
+ FALSE, TRUE
);
$this->assign('managePCPUrl', $managePCPUrl);
@@ -316,7 +316,7 @@ public function postProcess() {
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]));
}
//if more than one email present for PCP notification ,
@@ -329,14 +329,14 @@ public function postProcess() {
$cc = implode(',', $emailArray);
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
- array(
+ [
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'pcp_notify',
'contactId' => $contactID,
'from' => "$domainEmailName <$domainEmailAddress>",
'toEmail' => $to,
'cc' => $cc,
- )
+ ]
);
if ($sent) {
@@ -361,7 +361,7 @@ public function postProcess() {
}
CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3",
- array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus)
+ [1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus]
), '', 'info');
if (!$this->_pageId) {
$session->pushUserContext(CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}"));
diff --git a/CRM/PCP/Form/Contribute.php b/CRM/PCP/Form/Contribute.php
index 4a5dd93ddf62..4a09ff4cda2e 100644
--- a/CRM/PCP/Form/Contribute.php
+++ b/CRM/PCP/Form/Contribute.php
@@ -1,9 +1,9 @@
_id)) {
- $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_contribution_page');
+ $params = ['entity_id' => $this->_id, 'entity_table' => 'civicrm_contribution_page'];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $defaults);
$defaults['pcp_active'] = CRM_Utils_Array::value('is_active', $defaults);
// Assign contribution page ID to pageId for referencing in PCP.hlp - since $id is overwritten there. dgg
@@ -92,10 +92,10 @@ public function buildQuickForm() {
$this->_last = TRUE;
CRM_PCP_BAO_PCP::buildPCPForm($this);
- $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this contribution page)'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"));
+ $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this contribution page)'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"]);
parent::buildQuickForm();
- $this->addFormRule(array('CRM_PCP_Form_Contribute', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_Contribute', 'formRule'], $this);
}
/**
@@ -111,7 +111,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($params['is_active'])) {
if (!empty($params['is_tellfriend_enabled']) &&
diff --git a/CRM/PCP/Form/Event.php b/CRM/PCP/Form/Event.php
index 2059006add5a..da7802382bd5 100644
--- a/CRM/PCP/Form/Event.php
+++ b/CRM/PCP/Form/Event.php
@@ -1,9 +1,9 @@
assign('selectedChild', 'pcp');
}
/**
* Set default values for the form.
*
- *
- * @return void
+ * @return array
*/
public function setDefaultValues() {
- $defaults = array();
-
- $defaults = array();
+ $defaults = [];
if (isset($this->_id)) {
$title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'title');
- CRM_Utils_System::setTitle(ts('Personal Campaign Page Settings (%1)', array(1 => $title)));
+ CRM_Utils_System::setTitle(ts('Personal Campaign Page Settings (%1)', [1 => $title]));
- $params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
+ $params = ['entity_id' => $this->_id, 'entity_table' => 'civicrm_event'];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $defaults);
$defaults['pcp_active'] = CRM_Utils_Array::value('is_active', $defaults);
// Assign contribution page ID to pageId for referencing in PCP.hlp - since $id is overwritten there. dgg
@@ -97,18 +94,18 @@ public function setDefaultValues() {
public function buildQuickForm() {
CRM_PCP_BAO_PCP::buildPCPForm($this);
- $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this event)'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"));
+ $this->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages? (for this event)'), NULL, ['onclick' => "return showHideByValue('pcp_active',true,'pcpFields','table-row','radio',false);"]);
$this->add('select', 'target_entity_type', ts('Campaign Type'),
- array('' => ts('- select -'), 'event' => ts('Event'), 'contribute' => ts('Contribution')),
- NULL, array('onchange' => "return showHideByValue('target_entity_type','contribute','pcpDetailFields','block','select',false);")
+ ['' => ts('- select -'), 'event' => ts('Event'), 'contribute' => ts('Contribution')],
+ NULL, ['onchange' => "return showHideByValue('target_entity_type','contribute','pcpDetailFields','block','select',false);"]
);
$this->add('select', 'target_entity_id',
ts('Online Contribution Page'),
- array(
+ [
'' => ts('- select -'),
- ) +
+ ] +
CRM_Contribute_PseudoConstant::contributionPage()
);
@@ -121,15 +118,15 @@ public function buildQuickForm() {
$pcpBlock->find(TRUE);
if (!empty($pcpBlock->id) && CRM_PCP_BAO_PCP::getPcpBlockInUse($pcpBlock->id)) {
- foreach (array(
- 'target_entity_type',
- 'target_entity_id',
- ) as $element_name) {
+ foreach ([
+ 'target_entity_type',
+ 'target_entity_id',
+ ] as $element_name) {
$element = $this->getElement($element_name);
$element->freeze();
}
}
- $this->addFormRule(array('CRM_PCP_Form_Event', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_Event', 'formRule'], $this);
}
/**
@@ -145,7 +142,7 @@ public function buildQuickForm() {
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
- $errors = array();
+ $errors = [];
if (!empty($params['is_active'])) {
if (!empty($params['is_tellfriend_enabled']) &&
@@ -177,7 +174,6 @@ public static function formRule($params, $files, $self) {
/**
* Process the form submission.
*
- *
* @return void
*/
public function postProcess() {
diff --git a/CRM/PCP/Form/PCP.php b/CRM/PCP/Form/PCP.php
index 89a0caaecb53..ff39071278fb 100644
--- a/CRM/PCP/Form/PCP.php
+++ b/CRM/PCP/Form/PCP.php
@@ -1,9 +1,9 @@
_context)) {
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
}
$this->assign('context', $this->_context);
@@ -92,19 +92,19 @@ public function preProcess() {
case CRM_Core_Action::DELETE:
case 'delete':
CRM_PCP_BAO_PCP::deleteById($this->_id);
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", array(1 => $this->_title)), ts('Page Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", [1 => $this->_title]), ts('Page Deleted'), 'success');
break;
case CRM_Core_Action::DISABLE:
case 'disable':
CRM_PCP_BAO_PCP::setDisable($this->_id, '0');
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been disabled.", array(1 => $this->_title)), ts('Page Disabled'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been disabled.", [1 => $this->_title]), ts('Page Disabled'), 'success');
break;
case CRM_Core_Action::ENABLE:
case 'enable':
CRM_PCP_BAO_PCP::setDisable($this->_id, '1');
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been enabled.", array(1 => $this->_title)), ts('Page Enabled'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been enabled.", [1 => $this->_title]), ts('Page Enabled'), 'success');
break;
}
@@ -122,7 +122,7 @@ public function preProcess() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$pageType = CRM_Utils_Request::retrieve('page_type', 'String', $this);
$defaults['page_type'] = !empty($pageType) ? $pageType : '';
@@ -135,43 +135,41 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Campaign'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
else {
- $status = array('' => ts('- select -')) + CRM_Core_OptionGroup::values("pcp_status");
- $types = array(
+ $status = ['' => ts('- select -')] + CRM_Core_OptionGroup::values("pcp_status");
+ $types = [
'' => ts('- select -'),
'contribute' => ts('Contribution'),
'event' => ts('Event'),
- );
- $contribPages = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionPage();
- $eventPages = array('' => ts('- select -')) + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
+ ];
+ $contribPages = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::contributionPage();
+ $eventPages = ['' => ts('- select -')] + CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
$this->addElement('select', 'status_id', ts('Status'), $status);
$this->addElement('select', 'page_type', ts('Source Type'), $types);
$this->addElement('select', 'page_id', ts('Contribution Page'), $contribPages);
$this->addElement('select', 'event_id', ts('Event Page'), $eventPages);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'refresh',
'name' => ts('Search'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
parent::buildQuickForm();
}
}
@@ -197,14 +195,14 @@ public static function formRule($fields, $files, $form) {
public function postProcess() {
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_PCP_BAO_PCP::deleteById($this->_id);
- CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", array(1 => $this->_title)), ts('Page Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The Campaign Page '%1' has been deleted.", [1 => $this->_title]), ts('Page Deleted'), 'success');
}
else {
$params = $this->controller->exportValues($this->_name);
$parent = $this->controller->getParent();
if (!empty($params)) {
- $fields = array('status_id', 'page_id');
+ $fields = ['status_id', 'page_id'];
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
diff --git a/CRM/PCP/Form/PCPAccount.php b/CRM/PCP/Form/PCPAccount.php
index d62abf8640f0..ccac09cf5496 100644
--- a/CRM/PCP/Form/PCPAccount.php
+++ b/CRM/PCP/Form/PCPAccount.php
@@ -1,9 +1,9 @@
_defaults = array();
+ $this->_defaults = [];
if ($this->_contactID) {
foreach ($this->_fields as $name => $dontcare) {
$fields[$name] = 1;
@@ -143,7 +144,7 @@ public function buildQuickForm() {
if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $this->_contactID)) {
$fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD);
}
- $this->addFormRule(array('CRM_PCP_Form_PCPAccount', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_PCPAccount', 'formRule'], $this);
}
else {
CRM_Core_BAO_CMSUser::buildForm($this, $id, TRUE);
@@ -183,28 +184,28 @@ public function buildQuickForm() {
}
if ($this->_single) {
- $button = array(
- array(
+ $button = [
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- );
+ ],
+ ];
}
else {
- $button[] = array(
+ $button[] = [
'type' => 'next',
'name' => ts('Continue'),
'spacing' => ' ',
'isDefault' => TRUE,
- );
+ ];
}
- $this->addFormRule(array('CRM_PCP_Form_PCPAccount', 'formRule'), $this);
+ $this->addFormRule(['CRM_PCP_Form_PCPAccount', 'formRule'], $this);
$this->addButtons($button);
}
@@ -222,7 +223,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
foreach ($fields as $key => $value) {
if (strpos($key, 'email-') !== FALSE && !empty($value)) {
$ufContactId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFMatch', $value, 'contact_id', 'uf_name');
@@ -257,7 +258,7 @@ public function postProcess() {
$isPrimary = 1;
}
- $params['email'] = array();
+ $params['email'] = [];
$params['email'][1]['email'] = $value;
$params['email'][1]['location_type_id'] = $locTypeId;
$params['email'][1]['is_primary'] = $isPrimary;
@@ -265,7 +266,7 @@ public function postProcess() {
}
}
- $this->_contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', array(), FALSE);
+ $this->_contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', [], FALSE);
$contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_contactID);
$this->set('contactID', $contactID);
diff --git a/CRM/PCP/Page/PCP.php b/CRM/PCP/Page/PCP.php
index e3512ee7c353..58768df2e0ad 100644
--- a/CRM/PCP/Page/PCP.php
+++ b/CRM/PCP/Page/PCP.php
@@ -1,9 +1,9 @@
$this->_id);
+ $prms = ['id' => $this->_id];
CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
$this->_component = $pcpInfo['page_type'];
@@ -77,13 +77,13 @@ public function run() {
$this->assign('pcp', $pcpInfo);
$pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
- $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
+ $approvedId = CRM_Core_PseudoConstant::getKey('CRM_PCP_BAO_PCP', 'status_id', 'Approved');
// check if PCP is created by anonymous user
$anonymousPCP = CRM_Utils_Request::retrieve('ap', 'Boolean', $this);
if ($anonymousPCP) {
$loginURL = $config->userSystem->getLoginURL();
- $anonMessage = ts('Once you\'ve received your new account welcome email, you can click here to login and promote your campaign page.', array(1 => $loginURL));
+ $anonMessage = ts('Once you\'ve received your new account welcome email, you can click here to login and promote your campaign page.', [1 => $loginURL]);
CRM_Core_Session::setStatus($anonMessage, ts('Success'), 'success');
}
else {
@@ -122,7 +122,7 @@ public function run() {
}
}
- $default = array();
+ $default = [];
if ($pcpBlock->target_entity_type == 'contribute') {
$urlBase = 'civicrm/contribute/transact';
@@ -135,19 +135,19 @@ public function run() {
$page_class = 'CRM_Event_DAO_Event';
$this->assign('pageName', CRM_Event_PseudoConstant::event($pcpInfo['page_id']));
CRM_Core_DAO::commonRetrieveAll($page_class, 'id',
- $pcpInfo['page_id'], $default, array(
+ $pcpInfo['page_id'], $default, [
'start_date',
'end_date',
'registration_start_date',
'registration_end_date',
- )
+ ]
);
}
elseif ($pcpBlock->entity_table == 'civicrm_contribution_page') {
$page_class = 'CRM_Contribute_DAO_ContributionPage';
$this->assign('pageName', CRM_Contribute_PseudoConstant::contributionPage($pcpInfo['page_id'], TRUE));
CRM_Core_DAO::commonRetrieveAll($page_class, 'id',
- $pcpInfo['page_id'], $default, array('start_date', 'end_date')
+ $pcpInfo['page_id'], $default, ['start_date', 'end_date']
);
}
@@ -161,7 +161,7 @@ public function run() {
$link = CRM_PCP_BAO_PCP::pcpLinks();
- $hints = array(
+ $hints = [
CRM_Core_Action::UPDATE => ts('Change the content and appearance of your page'),
CRM_Core_Action::DETACH => ts('Send emails inviting your friends to support your campaign!'),
CRM_Core_Action::VIEW => ts('Copy this link to share directly with your network!'),
@@ -169,13 +169,13 @@ public function run() {
CRM_Core_Action::DISABLE => ts('De-activate the page (you can re-activate it later)'),
CRM_Core_Action::ENABLE => ts('Activate the page (you can de-activate it later)'),
CRM_Core_Action::DELETE => ts('Remove the page (this cannot be undone!)'),
- );
+ ];
- $replace = array(
+ $replace = [
'id' => $this->_id,
'block' => $pcpBlock->id,
'pageComponent' => $this->_component,
- );
+ ];
if (!$pcpBlock->is_tellfriend_enabled || CRM_Utils_Array::value('status_id', $pcpInfo) != $approvedId) {
unset($link['all'][CRM_Core_Action::DETACH]);
@@ -202,8 +202,9 @@ public function run() {
if (!empty($entityFile)) {
$fileInfo = reset($entityFile);
$fileId = $fileInfo['fileID'];
+ $fileHash = CRM_Core_BAO_File::generateFileHash($this->_id, $fileId);
$image = '_id}"
+ "reset=1&id=$fileId&eid={$this->_id}&fcs={$fileHash}"
) . '" />';
$this->assign('image', $image);
}
diff --git a/CRM/PCP/StateMachine/PCP.php b/CRM/PCP/StateMachine/PCP.php
index 34f81e92c27a..a1040ffe45a8 100644
--- a/CRM/PCP/StateMachine/PCP.php
+++ b/CRM/PCP/StateMachine/PCP.php
@@ -1,9 +1,9 @@
set('singleForm', FALSE);
- $this->_pages = array(
+ $this->_pages = [
'CRM_PCP_Form_PCPAccount' => NULL,
'CRM_PCP_Form_Campaign' => NULL,
- );
+ ];
$this->addSequentialPages($this->_pages, $action);
}
diff --git a/CRM/Pledge/BAO/Pledge.php b/CRM/Pledge/BAO/Pledge.php
index 540b659fa17b..62b4dfa74043 100644
--- a/CRM/Pledge/BAO/Pledge.php
+++ b/CRM/Pledge/BAO/Pledge.php
@@ -1,9 +1,9 @@
$value) {
+ if (!empty($date) && !CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
+ return $date;
+ }
+ if (empty($date)) {
+ $date = $value;
+ }
+ switch ($field) {
+ case 'contribution_date':
+ if (empty($date)) {
+ $date = date('Ymd');
+ }
+ break;
- case 'calendar_date':
- $date = date('Ymd', strtotime($date));
- break;
+ case 'calendar_date':
+ $date = date('Ymd', strtotime($date));
+ break;
- case 'calendar_month':
- $date = self::getPaymentDate($date);
- $date = date('Ymd', strtotime($date));
- break;
+ case 'calendar_month':
+ $date = self::getPaymentDate($date);
+ $date = date('Ymd', strtotime($date));
+ break;
- default:
- break;
+ default:
+ break;
+ }
}
return $date;
}
diff --git a/CRM/Pledge/BAO/PledgeBlock.php b/CRM/Pledge/BAO/PledgeBlock.php
index 4ca50a57e1b9..732a61a450e5 100644
--- a/CRM/Pledge/BAO/PledgeBlock.php
+++ b/CRM/Pledge/BAO/PledgeBlock.php
@@ -1,9 +1,9 @@
_values['pledge_id'], $allPayments, $returnProperties
@@ -282,11 +281,11 @@ public static function buildPledgeBlock($form) {
$form->addRadio('is_pledge', ts('Pledge Frequency Interval'), $pledgeOptions,
NULL, array(' ')
);
- $form->addElement('text', 'pledge_installments', ts('Installments'), array('size' => 3));
+ $form->addElement('text', 'pledge_installments', ts('Installments'), ['size' => 3, 'aria-label' => ts('Installments')]);
if (!empty($pledgeBlock['is_pledge_interval'])) {
$form->assign('is_pledge_interval', CRM_Utils_Array::value('is_pledge_interval', $pledgeBlock));
- $form->addElement('text', 'pledge_frequency_interval', NULL, array('size' => 3));
+ $form->addElement('text', 'pledge_frequency_interval', NULL, ['size' => 3, 'aria-label' => ts('Frequency Intervals')]);
}
else {
$form->add('hidden', 'pledge_frequency_interval', 1);
@@ -300,47 +299,48 @@ public static function buildPledgeBlock($form) {
$freqUnits[$val] = !empty($pledgeBlock['is_pledge_interval']) ? "{$frequencyUnits[$val]}(s)" : $frequencyUnits[$val];
}
}
- $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits);
+ $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits, ['aria-label' => ts('Frequency Units')]);
// CRM-18854
if (CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)) {
if (CRM_Utils_Array::value('pledge_start_date', $pledgeBlock)) {
$defaults = array();
$date = (array) json_decode($pledgeBlock['pledge_start_date']);
- list($field, $value) = each($date);
- switch ($field) {
- case 'contribution_date':
- $form->addDate('start_date', ts('First installment payment'));
- $paymentDate = $value = date('m/d/Y');
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(NULL);
- $form->assign('is_date', TRUE);
- break;
-
- case 'calendar_date':
- $form->addDate('start_date', ts('First installment payment'));
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
- $form->assign('is_date', TRUE);
- $paymentDate = $value;
- break;
-
- case 'calendar_month':
- $month = CRM_Utils_Date::getCalendarDayOfMonth();
- $form->add('select', 'start_date', ts('Day of month installments paid'), $month);
- $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value);
- list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($paymentDate);
- break;
-
- default:
- break;
+ foreach ($date as $field => $value) {
+ switch ($field) {
+ case 'contribution_date':
+ $form->add('datepicker', 'start_date', ts('First installment payment'), [], FALSE, ['time' => FALSE]);
+ $paymentDate = $value = date('Y-m-d');
+ $defaults['start_date'] = $value;
+ $form->assign('is_date', TRUE);
+ break;
+
+ case 'calendar_date':
+ $form->add('datepicker', 'start_date', ts('First installment payment'), [], FALSE, ['time' => FALSE]);
+ $defaults['start_date'] = $value;
+ $form->assign('is_date', TRUE);
+ $paymentDate = $value;
+ break;
+
+ case 'calendar_month':
+ $month = CRM_Utils_Date::getCalendarDayOfMonth();
+ $form->add('select', 'start_date', ts('Day of month installments paid'), $month);
+ $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value);
+ $defaults['start_date'] = $paymentDate;
+ break;
+
+ default:
+ break;
- }
- $form->setDefaults($defaults);
- $form->assign('start_date_display', $paymentDate);
- $form->assign('start_date_editable', FALSE);
- if (CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
- $form->assign('start_date_editable', TRUE);
- if ($field == 'calendar_month') {
- $form->assign('is_date', FALSE);
- $form->setDefaults(array('start_date' => $value));
+ }
+ $form->setDefaults($defaults);
+ $form->assign('start_date_display', $paymentDate);
+ $form->assign('start_date_editable', FALSE);
+ if (CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
+ $form->assign('start_date_editable', TRUE);
+ if ($field == 'calendar_month') {
+ $form->assign('is_date', FALSE);
+ $form->setDefaults(array('start_date' => $value));
+ }
}
}
}
diff --git a/CRM/Pledge/BAO/PledgePayment.php b/CRM/Pledge/BAO/PledgePayment.php
index ed1900f8ac03..ec637d58b70b 100644
--- a/CRM/Pledge/BAO/PledgePayment.php
+++ b/CRM/Pledge/BAO/PledgePayment.php
@@ -1,9 +1,9 @@
fetch()) {
$paymentDetails[$payment->id]['scheduled_amount'] = $payment->scheduled_amount;
$paymentDetails[$payment->id]['scheduled_date'] = $payment->scheduled_date;
@@ -103,7 +103,7 @@ public static function create($params) {
//calculate the scheduled date for every installment
$now = date('Ymd') . '000000';
- $statues = $prevScheduledDate = array();
+ $statues = $prevScheduledDate = [];
$prevScheduledDate[1] = CRM_Utils_Date::processDate($params['scheduled_date']);
if (CRM_Utils_Date::overdue($prevScheduledDate[1], $now)) {
@@ -418,12 +418,12 @@ public static function updatePledgePaymentStatus(
$ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit,
$pledgeFrequencyInterval, $newDate
));
- $pledgeParams = array(
+ $pledgeParams = [
'status_id' => array_search('Pending', $allStatus),
'pledge_id' => $pledgeID,
'scheduled_amount' => ($pledgeScheduledAmount - $actualAmount),
'scheduled_date' => $ScheduledDate,
- );
+ ];
$payment = self::add($pledgeParams);
// while editing schedule, after adding a new pledge payemnt update the scheduled amount of the current payment
if (!$paymentContributionId) {
@@ -451,7 +451,7 @@ public static function updatePledgePaymentStatus(
WHERE civicrm_pledge_payment.pledge_id = %1
AND civicrm_pledge_payment.status_id = 1
";
- $totalPaidParams = array(1 => array($pledgeID, 'Integer'));
+ $totalPaidParams = [1 => [$pledgeID, 'Integer']];
$totalPaidAmount = CRM_Core_DAO::singleValueQuery($balanceQuery, $totalPaidParams);
$remainingTotalAmount = ($actualPledgeAmount - $totalPaidAmount);
if (($pledgeStatusId && $pledgeStatusId == array_search('Completed', $allStatus)) && (($actualAmount > $remainingTotalAmount) || ($actualAmount >= $actualPledgeAmount))) {
@@ -490,10 +490,10 @@ public static function updatePledgePaymentStatus(
WHERE civicrm_pledge.id = %2
";
- $params = array(
- 1 => array($pledgeStatusID, 'Integer'),
- 2 => array($pledgeID, 'Integer'),
- );
+ $params = [
+ 1 => [$pledgeStatusID, 'Integer'],
+ 2 => [$pledgeID, 'Integer'],
+ ];
CRM_Core_DAO::executeQuery($query, $params);
@@ -512,7 +512,7 @@ public static function updatePledgePaymentStatus(
* Next scheduled date as an array
*/
public static function calculateBaseScheduleDate(&$params) {
- $date = array();
+ $date = [];
$scheduled_date = CRM_Utils_Date::processDate($params['scheduled_date']);
$date['year'] = (int) substr($scheduled_date, 0, 4);
$date['month'] = (int) substr($scheduled_date, 4, 2);
@@ -568,20 +568,20 @@ public static function calculateNextScheduledDate(&$params, $paymentNo, $basePay
}
//CRM-18316 - change $basePaymentDate for the end dates of the month eg: 29, 30 or 31.
- if ($params['frequency_unit'] == 'month' && in_array($params['frequency_day'], array(29, 30, 31))) {
+ if ($params['frequency_unit'] == 'month' && in_array($params['frequency_day'], [29, 30, 31])) {
$frequency = $params['frequency_day'];
extract(date_parse($basePaymentDate));
$lastDayOfMonth = date('t', mktime($hour, $minute, $second, $month + $interval, 1, $year));
// Take the last day in case the current month is Feb or frequency_day is set to 31.
- if (in_array($lastDayOfMonth, array(28, 29)) || $frequency == 31) {
+ if (in_array($lastDayOfMonth, [28, 29]) || $frequency == 31) {
$frequency = 0;
$interval++;
}
- $basePaymentDate = array(
+ $basePaymentDate = [
'M' => $month,
'd' => $frequency,
'Y' => $year,
- );
+ ];
}
return CRM_Utils_Date::format(
@@ -613,8 +613,8 @@ public static function calculatePledgeStatus($pledgeId) {
}
// retrieve all pledge payments for this particular pledge
- $allPledgePayments = $allStatus = array();
- $returnProperties = array('status_id');
+ $allPledgePayments = $allStatus = [];
+ $returnProperties = ['status_id'];
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $pledgeId, $allPledgePayments, $returnProperties);
// build pledge payment statuses
@@ -689,7 +689,7 @@ public static function updatePledgePayments(
{$paymentClause}
";
- CRM_Core_DAO::executeQuery($query, array(1 => array($pledgeId, 'Integer')));
+ CRM_Core_DAO::executeQuery($query, [1 => [$pledgeId, 'Integer']]);
}
/**
@@ -741,20 +741,20 @@ public static function getOldestPledgePayment($pledgeID, $limit = 1) {
LIMIT 0, %2
";
- $params[1] = array($pledgeID, 'Integer');
- $params[2] = array($limit, 'Integer');
+ $params[1] = [$pledgeID, 'Integer'];
+ $params[2] = [$limit, 'Integer'];
$payment = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
- $paymentDetails = array();
+ $paymentDetails = [];
while ($payment->fetch()) {
- $paymentDetails[] = array(
+ $paymentDetails[] = [
'id' => $payment->id,
'amount' => $payment->amount,
'currency' => $payment->currency,
'schedule_date' => $payment->scheduled_date,
'financial_type_id' => $payment->financial_type_id,
'count' => $count,
- );
+ ];
$count++;
}
return end($paymentDetails);
@@ -778,7 +778,7 @@ public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeSche
WHERE civicrm_pledge_payment.contribution_id = {$paymentContributionId}
";
$paymentsAffected = CRM_Core_DAO::executeQuery($query);
- $paymentIDs = array();
+ $paymentIDs = [];
while ($paymentsAffected->fetch()) {
$paymentIDs[] = $paymentsAffected->id;
}
@@ -814,12 +814,12 @@ public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeSche
$date['day'] = (int) substr($scheduled_date, 6, 2);
$newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit, $pledgeFrequencyInterval, $newDate));
- $pledgeParams = array(
+ $pledgeParams = [
'status_id' => array_search('Pending', $allStatus),
'pledge_id' => $pledgeID,
'scheduled_amount' => $pledgeScheduledAmount,
'scheduled_date' => $ScheduledDate,
- );
+ ];
$payment = self::add($pledgeParams);
}
else {
@@ -854,7 +854,7 @@ public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeSche
elseif (($actualAmount > $pledgeScheduledAmount) && (($actualAmount - $pledgeScheduledAmount) >= $nextPledgeInstallmentDue['amount'])) {
// here the actual amount is greater than expected and also greater than the next installment amount, so update the next installment as complete and again add it to next subsequent pending payment
// set the actual amount of the next pending to '0', set contribution Id to current contribution Id and status as completed
- $paymentId = array($nextPledgeInstallmentDue['id']);
+ $paymentId = [$nextPledgeInstallmentDue['id']];
self::updatePledgePayments($pledgeID, array_search('Completed', $allStatus), $paymentId, 0, $paymentContributionId);
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $nextPledgeInstallmentDue['id'], 'scheduled_amount', 0, 'id');
if (!$paymentContributionId) {
@@ -892,11 +892,11 @@ public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeSche
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
$result = parent::buildOptions($fieldName, $context, $props);
if ($fieldName == 'status_id') {
$result = CRM_Pledge_BAO_Pledge::buildOptions($fieldName, $context, $props);
- $result = array_diff($result, array('Failed', 'In Progress'));
+ $result = array_diff($result, ['Failed', 'In Progress']);
}
return $result;
}
diff --git a/CRM/Pledge/BAO/Query.php b/CRM/Pledge/BAO/Query.php
index 9cf75496aa5d..902872d1c1b3 100644
--- a/CRM/Pledge/BAO/Query.php
+++ b/CRM/Pledge/BAO/Query.php
@@ -1,9 +1,9 @@
_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
+ if (!empty($query->_returnProperties['pledge_original_installment_amount'])) {
+ $query->_select['pledge_original_installment_amount'] = 'civicrm_pledge.original_installment_amount as pledge_original_installment_amount';
+ $query->_element['pledge_original_installment_amount'] = 1;
+ $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
+ }
+
+ if (!empty($query->_returnProperties['installments'])) {
+ $query->_select['installments'] = 'civicrm_pledge.installments as installments';
+ $query->_element['installments'] = 1;
+ $query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
+ }
+
if (!empty($query->_returnProperties['pledge_create_date'])) {
$query->_select['pledge_create_date'] = 'civicrm_pledge.create_date as pledge_create_date';
$query->_element['pledge_create_date'] = 1;
@@ -310,7 +323,7 @@ public static function whereClauseSingle(&$values, &$query) {
}
$name = 'status_id';
if (!empty($value) && is_array($value) && !in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
- $value = array('IN' => $value);
+ $value = ['IN' => $value];
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name",
@@ -319,7 +332,7 @@ public static function whereClauseSingle(&$values, &$query) {
'Integer'
);
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($qillDAO, $qillField, $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]);
return;
case 'pledge_test':
@@ -345,7 +358,7 @@ public static function whereClauseSingle(&$values, &$query) {
$value,
'Integer'
);
- $query->_qill[$grouping][] = ts('Financial Type - %1', array(1 => $type));
+ $query->_qill[$grouping][] = ts('Financial Type - %1', [1 => $type]);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
@@ -356,7 +369,7 @@ public static function whereClauseSingle(&$values, &$query) {
$value,
'Integer'
);
- $query->_qill[$grouping][] = ts('Financial Page - %1', array(1 => $page));
+ $query->_qill[$grouping][] = ts('Financial Page - %1', [1 => $page]);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
@@ -385,7 +398,7 @@ public static function whereClauseSingle(&$values, &$query) {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_pledge.$name", $op, $value, 'Integer');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Pledge_DAO_Pledge', $name, $value, $op);
$label = ($name == 'campaign_id') ? 'Campaign' : 'Contact ID';
- $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $op, 3 => $value));
+ $query->_qill[$grouping][] = ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
}
@@ -449,7 +462,7 @@ public static function defaultReturnProperties(
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_PLEDGE) {
- $properties = array(
+ $properties = [
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
@@ -470,7 +483,7 @@ public static function defaultReturnProperties(
'pledge_frequency_unit' => 1,
'pledge_currency' => 1,
'pledge_campaign_id' => 1,
- );
+ ];
}
return $properties;
}
@@ -486,7 +499,7 @@ public static function extraReturnProperties($mode) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_PLEDGE) {
- $properties = array(
+ $properties = [
'pledge_balance_amount' => 1,
'pledge_payment_id' => 1,
'pledge_payment_scheduled_amount' => 1,
@@ -497,7 +510,7 @@ public static function extraReturnProperties($mode) {
'pledge_payment_reminder_count' => 1,
'pledge_payment_status_id' => 1,
'pledge_payment_status' => 1,
- );
+ ];
// also get all the custom pledge properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Pledge');
@@ -523,61 +536,61 @@ public static function buildSearchForm(&$form) {
CRM_Core_Form_Date::buildDateRange($form, 'pledge_payment_date', 1, '_low', '_high', ts('From'), FALSE);
$form->addYesNo('pledge_test', ts('Pledge is a Test?'), TRUE);
- $form->add('text', 'pledge_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
- $form->addRule('pledge_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
+ $form->add('text', 'pledge_amount_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
+ $form->addRule('pledge_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money');
- $form->add('text', 'pledge_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
- $form->addRule('pledge_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+ $form->add('text', 'pledge_amount_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
+ $form->addRule('pledge_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money');
$form->add('select', 'pledge_status_id',
ts('Pledge Status'), CRM_Pledge_BAO_Pledge::buildOptions('status_id'),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
);
$form->addYesNo('pledge_acknowledge_date_is_not_null', ts('Acknowledgement sent?'), TRUE);
- $form->add('text', 'pledge_installments_low', ts('From'), array('size' => 8, 'maxlength' => 8));
+ $form->add('text', 'pledge_installments_low', ts('From'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('pledge_installments_low', ts('Please enter a number'), 'integer');
- $form->add('text', 'pledge_installments_high', ts('To'), array('size' => 8, 'maxlength' => 8));
+ $form->add('text', 'pledge_installments_high', ts('To'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('pledge_installments_high', ts('Please enter number.'), 'integer');
$form->add('select', 'pledge_payment_status_id',
ts('Pledge Payment Status'), CRM_Pledge_BAO_PledgePayment::buildOptions('status_id'),
- FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')
+ FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']
);
$form->add('select', 'pledge_financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
- FALSE, array('class' => 'crm-select2')
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType(),
+ FALSE, ['class' => 'crm-select2']
);
$form->add('select', 'pledge_contribution_page_id',
ts('Contribution Page'),
- array('' => ts('- any -')) + CRM_Contribute_PseudoConstant::contributionPage(),
- FALSE, array('class' => 'crm-select2')
+ ['' => ts('- any -')] + CRM_Contribute_PseudoConstant::contributionPage(),
+ FALSE, ['class' => 'crm-select2']
);
// add fields for pledge frequency
- $form->add('text', 'pledge_frequency_interval', ts('Every'), array('size' => 8, 'maxlength' => 8));
+ $form->add('text', 'pledge_frequency_interval', ts('Every'), ['size' => 8, 'maxlength' => 8]);
$form->addRule('pledge_frequency_interval', ts('Please enter valid Pledge Frequency Interval'), 'integer');
$frequencies = CRM_Core_OptionGroup::values('recur_frequency_units');
foreach ($frequencies as $val => $label) {
- $freqUnitsDisplay["'{$val}'"] = ts('%1(s)', array(1 => $label));
+ $freqUnitsDisplay["'{$val}'"] = ts('%1(s)', [1 => $label]);
}
$form->add('select', 'pledge_frequency_unit',
ts('Pledge Frequency'),
- array('' => ts('- any -')) + $freqUnitsDisplay
+ ['' => ts('- any -')] + $freqUnitsDisplay
);
- self::addCustomFormFields($form, array('Pledge'));
+ self::addCustomFormFields($form, ['Pledge']);
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'pledge_campaign_id');
$form->assign('validCiviPledge', TRUE);
- $form->setDefaults(array('pledge_test' => 0));
+ $form->setDefaults(['pledge_test' => 0]);
}
/**
@@ -586,7 +599,7 @@ public static function buildSearchForm(&$form) {
public static function tableNames(&$tables) {
// add status table
if (!empty($tables['pledge_status']) || !empty($tables['civicrm_pledge_payment'])) {
- $tables = array_merge(array('civicrm_pledge' => 1), $tables);
+ $tables = array_merge(['civicrm_pledge' => 1], $tables);
}
}
diff --git a/CRM/Pledge/Controller/Search.php b/CRM/Pledge/Controller/Search.php
index c7c6a582a190..f95d94db590c 100644
--- a/CRM/Pledge/Controller/Search.php
+++ b/CRM/Pledge/Controller/Search.php
@@ -1,9 +1,9 @@
__table = 'civicrm_pledge';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_page_id', 'civicrm_contribution_page', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contact_id', 'civicrm_contact', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_page_id', 'civicrm_contribution_page', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'pledge_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'pledge_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge ID') ,
- 'description' => 'Pledge ID',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Pledge ID'),
+ 'description' => ts('Pledge ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- ) ,
- 'pledge_contact_id' => array(
+ ],
+ 'pledge_contact_id' => [
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contact ID') ,
- 'description' => 'Foreign key to civicrm_contact.id .',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Contact ID'),
+ 'description' => ts('Foreign key to civicrm_contact.id .'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge.contact_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
- 'html' => array(
+ 'html' => [
'type' => 'EntityRef',
- ) ,
- ) ,
- 'pledge_financial_type_id' => array(
+ ],
+ ],
+ 'pledge_financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Type') ,
- 'description' => 'FK to Financial Type',
+ 'title' => ts('Type'),
+ 'description' => ts('FK to Financial Type'),
+ 'where' => 'civicrm_pledge.financial_type_id',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'pledge_contribution_page_id' => array(
+ ]
+ ],
+ 'pledge_contribution_page_id' => [
'name' => 'contribution_page_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Contribution Page') ,
- 'description' => 'The Contribution Page which triggered this contribution',
+ 'title' => ts('Pledge Contribution Page'),
+ 'description' => ts('The Contribution Page which triggered this contribution'),
+ 'where' => 'civicrm_pledge.contribution_page_id',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
- ) ,
- 'pledge_amount' => array(
+ ],
+ 'pledge_amount' => [
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Total Pledged') ,
- 'description' => 'Total pledged amount.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Total Pledged'),
+ 'description' => ts('Total pledged amount.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge.amount',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'pledge_original_installment_amount' => array(
+ ],
+ ],
+ 'pledge_original_installment_amount' => [
'name' => 'original_installment_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Original Installment Amount') ,
- 'description' => 'Original amount for each of the installments.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Original Installment Amount'),
+ 'description' => ts('Original amount for each of the installments.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_pledge.original_installment_amount',
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'currency' => array(
+ ],
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Pledge Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_pledge.currency',
'default' => 'NULL',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'pledge_frequency_unit' => array(
+ ]
+ ],
+ 'pledge_frequency_unit' => [
'name' => 'frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Frequency Unit') ,
- 'description' => 'Time units for recurrence of pledge payments.',
+ 'title' => ts('Pledge Frequency Unit'),
+ 'description' => ts('Time units for recurrence of pledge payments.'),
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
+ 'where' => 'civicrm_pledge.frequency_unit',
'default' => 'month',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'recur_frequency_units',
'keyColumn' => 'name',
'optionEditPath' => 'civicrm/admin/options/recur_frequency_units',
- )
- ) ,
- 'pledge_frequency_interval' => array(
+ ]
+ ],
+ 'pledge_frequency_interval' => [
'name' => 'frequency_interval',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Frequency Interval') ,
- 'description' => 'Number of time units for recurrence of pledge payments.',
- 'required' => true,
+ 'title' => ts('Pledge Frequency Interval'),
+ 'description' => ts('Number of time units for recurrence of pledge payments.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge.frequency_interval',
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'frequency_day' => array(
+ ],
+ ],
+ 'frequency_day' => [
'name' => 'frequency_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge day') ,
- 'description' => 'Day in the period when the pledge payment is due e.g. 1st of month, 15th etc. Use this to set the scheduled dates for pledge payments.',
- 'required' => true,
+ 'title' => ts('Pledge day'),
+ 'description' => ts('Day in the period when the pledge payment is due e.g. 1st of month, 15th etc. Use this to set the scheduled dates for pledge payments.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge.frequency_day',
'default' => '3',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'installments' => array(
+ ],
+ ],
+ 'installments' => [
'name' => 'installments',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Number of Installments') ,
- 'description' => 'Total number of payments to be made.',
+ 'title' => ts('Pledge Number of Installments'),
+ 'description' => ts('Total number of payments to be made.'),
+ 'where' => 'civicrm_pledge.installments',
+ 'export' => TRUE,
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'start_date' => array(
+ ],
+ ],
+ 'start_date' => [
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Start Date') ,
- 'description' => 'The date the first scheduled pledge occurs.',
- 'required' => true,
+ 'title' => ts('Pledge Start Date'),
+ 'description' => ts('The date the first scheduled pledge occurs.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge.start_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'pledge_create_date' => array(
+ ],
+ ],
+ 'pledge_create_date' => [
'name' => 'create_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Made') ,
- 'description' => 'When this pledge record was created.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Pledge Made'),
+ 'description' => ts('When this pledge record was created.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge.create_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'acknowledge_date' => array(
+ ],
+ ],
+ 'acknowledge_date' => [
'name' => 'acknowledge_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Acknowledged') ,
- 'description' => 'When a pledge acknowledgement message was sent to the contributor.',
+ 'title' => ts('Pledge Acknowledged'),
+ 'description' => ts('When a pledge acknowledgement message was sent to the contributor.'),
+ 'where' => 'civicrm_pledge.acknowledge_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'modified_date' => array(
+ ],
+ ],
+ 'modified_date' => [
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Modified Date') ,
- 'description' => 'Last updated date for this pledge record.',
+ 'title' => ts('Pledge Modified Date'),
+ 'description' => ts('Last updated date for this pledge record.'),
+ 'where' => 'civicrm_pledge.modified_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- ) ,
- 'cancel_date' => array(
+ ],
+ 'cancel_date' => [
'name' => 'cancel_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge Cancelled Date') ,
- 'description' => 'Date this pledge was cancelled by contributor.',
+ 'title' => ts('Pledge Cancelled Date'),
+ 'description' => ts('Date this pledge was cancelled by contributor.'),
+ 'where' => 'civicrm_pledge.cancel_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'end_date' => array(
+ ],
+ ],
+ 'end_date' => [
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Pledge End Date') ,
- 'description' => 'Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).',
+ 'title' => ts('Pledge End Date'),
+ 'description' => ts('Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).'),
+ 'where' => 'civicrm_pledge.end_date',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'max_reminders' => array(
+ ],
+ ],
+ 'max_reminders' => [
'name' => 'max_reminders',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum Number of Reminders') ,
- 'description' => 'The maximum number of payment reminders to send for any given payment.',
+ 'title' => ts('Maximum Number of Reminders'),
+ 'description' => ts('The maximum number of payment reminders to send for any given payment.'),
+ 'where' => 'civicrm_pledge.max_reminders',
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'initial_reminder_day' => array(
+ ],
+ ],
+ 'initial_reminder_day' => [
'name' => 'initial_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Initial Reminder Day') ,
- 'description' => 'Send initial reminder this many days prior to the payment due date.',
+ 'title' => ts('Initial Reminder Day'),
+ 'description' => ts('Send initial reminder this many days prior to the payment due date.'),
+ 'where' => 'civicrm_pledge.initial_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'additional_reminder_day' => array(
+ ],
+ ],
+ 'additional_reminder_day' => [
'name' => 'additional_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Additional Reminder Days') ,
- 'description' => 'Send additional reminder this many days after last one sent, up to maximum number of reminders.',
+ 'title' => ts('Additional Reminder Days'),
+ 'description' => ts('Send additional reminder this many days after last one sent, up to maximum number of reminders.'),
+ 'where' => 'civicrm_pledge.additional_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'pledge_status_id' => array(
+ ],
+ ],
+ 'pledge_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Status Id') ,
- 'description' => 'Implicit foreign key to civicrm_option_values in the pledge_status option group.',
- 'import' => true,
+ 'title' => ts('Pledge Status Id'),
+ 'description' => ts('Implicit foreign key to civicrm_option_values in the pledge_status option group.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'pledge_status',
'optionEditPath' => 'civicrm/admin/options/pledge_status',
- )
- ) ,
- 'pledge_is_test' => array(
+ ]
+ ],
+ 'pledge_is_test' => [
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Test') ,
- 'import' => true,
+ 'title' => ts('Test'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge.is_test',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'pledge_campaign_id' => array(
+ ],
+ ],
+ 'pledge_campaign_id' => [
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Campaign') ,
- 'description' => 'The campaign for which this pledge has been initiated.',
- 'import' => true,
+ 'title' => ts('Campaign'),
+ 'description' => ts('The campaign for which this pledge has been initiated.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge.campaign_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -637,10 +648,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -648,24 +660,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_status' => array(
+ $indices = [
+ 'index_status' => [
'name' => 'index_status',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge::0::status_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Pledge/DAO/PledgeBlock.php b/CRM/Pledge/DAO/PledgeBlock.php
index a8b3fa840587..e319da634e73 100644
--- a/CRM/Pledge/DAO/PledgeBlock.php
+++ b/CRM/Pledge/DAO/PledgeBlock.php
@@ -1,306 +1,316 @@
__table = 'civicrm_pledge_block';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge Block ID') ,
- 'description' => 'Pledge ID',
- 'required' => true,
+ 'title' => ts('Pledge Block ID'),
+ 'description' => ts('Pledge ID'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.id',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'physical tablename for entity being joined to pledge, e.g. civicrm_contact',
+ 'title' => ts('Entity Table'),
+ 'description' => ts('physical tablename for entity being joined to pledge, e.g. civicrm_contact'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pledge_block.entity_table',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity Id') ,
- 'description' => 'FK to entity table specified in entity_table column.',
- 'required' => true,
+ 'title' => ts('Entity Id'),
+ 'description' => ts('FK to entity table specified in entity_table column.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.entity_id',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'pledge_frequency_unit' => array(
+ ],
+ 'pledge_frequency_unit' => [
'name' => 'pledge_frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Frequency Unit') ,
- 'description' => 'Delimited list of supported frequency units',
+ 'title' => ts('Pledge Frequency Unit'),
+ 'description' => ts('Delimited list of supported frequency units'),
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_pledge_block.pledge_frequency_unit',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'is_pledge_interval' => array(
+ 'serialize' => self::SERIALIZE_SEPARATOR_TRIMMED,
+ ],
+ 'is_pledge_interval' => [
'name' => 'is_pledge_interval',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Expose Frequency Interval?') ,
- 'description' => 'Is frequency interval exposed on the contribution form.',
+ 'title' => ts('Expose Frequency Interval?'),
+ 'description' => ts('Is frequency interval exposed on the contribution form.'),
+ 'where' => 'civicrm_pledge_block.is_pledge_interval',
+ 'default' => '0',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'max_reminders' => array(
+ ],
+ 'max_reminders' => [
'name' => 'max_reminders',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Maximum Number of Reminders') ,
- 'description' => 'The maximum number of payment reminders to send for any given payment.',
+ 'title' => ts('Maximum Number of Reminders'),
+ 'description' => ts('The maximum number of payment reminders to send for any given payment.'),
+ 'where' => 'civicrm_pledge_block.max_reminders',
'default' => '1',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'initial_reminder_day' => array(
+ ],
+ 'initial_reminder_day' => [
'name' => 'initial_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Initial Reminder Day') ,
- 'description' => 'Send initial reminder this many days prior to the payment due date.',
+ 'title' => ts('Initial Reminder Day'),
+ 'description' => ts('Send initial reminder this many days prior to the payment due date.'),
+ 'where' => 'civicrm_pledge_block.initial_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'additional_reminder_day' => array(
+ ],
+ 'additional_reminder_day' => [
'name' => 'additional_reminder_day',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Additional Reminder Days') ,
- 'description' => 'Send additional reminder this many days after last one sent, up to maximum number of reminders.',
+ 'title' => ts('Additional Reminder Days'),
+ 'description' => ts('Send additional reminder this many days after last one sent, up to maximum number of reminders.'),
+ 'where' => 'civicrm_pledge_block.additional_reminder_day',
'default' => '5',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'pledge_start_date' => array(
+ ],
+ 'pledge_start_date' => [
'name' => 'pledge_start_date',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Pledge Start Date') ,
- 'description' => 'The date the first scheduled pledge occurs.',
+ 'title' => ts('Pledge Start Date'),
+ 'description' => ts('The date the first scheduled pledge occurs.'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_pledge_block.pledge_start_date',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'is_pledge_start_date_visible' => array(
+ ],
+ 'is_pledge_start_date_visible' => [
'name' => 'is_pledge_start_date_visible',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Show Recurring Donation Start Date?') ,
- 'description' => 'If true - recurring start date is shown.',
- 'required' => true,
+ 'title' => ts('Show Recurring Donation Start Date?'),
+ 'description' => ts('If true - recurring start date is shown.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.is_pledge_start_date_visible',
+ 'default' => '0',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- 'is_pledge_start_date_editable' => array(
+ ],
+ 'is_pledge_start_date_editable' => [
'name' => 'is_pledge_start_date_editable',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Allow Edits to Recurring Donation Start Date?') ,
- 'description' => 'If true - recurring start date is editable.',
- 'required' => true,
+ 'title' => ts('Allow Edits to Recurring Donation Start Date?'),
+ 'description' => ts('If true - recurring start date is editable.'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_block.is_pledge_start_date_editable',
+ 'default' => '0',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -308,10 +318,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_block', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -319,25 +330,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_block', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_block', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_entity' => array(
+ $indices = [
+ 'index_entity' => [
'name' => 'index_entity',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge_block::0::entity_table::entity_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Pledge/DAO/PledgePayment.php b/CRM/Pledge/DAO/PledgePayment.php
index c51fc033dfe7..f3d80a9327e7 100644
--- a/CRM/Pledge/DAO/PledgePayment.php
+++ b/CRM/Pledge/DAO/PledgePayment.php
@@ -1,339 +1,325 @@
__table = 'civicrm_pledge_payment';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'pledge_id', 'civicrm_pledge', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'pledge_id', 'civicrm_pledge', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'pledge_payment_id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'pledge_payment_id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment ID') ,
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Payment ID'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_id' => array(
+ ],
+ 'pledge_id' => [
'name' => 'pledge_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Pledge') ,
- 'description' => 'FK to Pledge table',
- 'required' => true,
+ 'title' => ts('Pledge'),
+ 'description' => ts('FK to Pledge table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_pledge_payment.pledge_id',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'FKClassName' => 'CRM_Pledge_DAO_Pledge',
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Contribution') ,
- 'description' => 'FK to contribution table.',
+ 'title' => ts('Contribution'),
+ 'description' => ts('FK to contribution table.'),
+ 'where' => 'civicrm_pledge_payment.contribution_id',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- 'pledge_payment_scheduled_amount' => array(
+ ],
+ 'pledge_payment_scheduled_amount' => [
'name' => 'scheduled_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Scheduled Amount') ,
- 'description' => 'Pledged amount for this payment (the actual contribution amount might be different).',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Scheduled Amount'),
+ 'description' => ts('Pledged amount for this payment (the actual contribution amount might be different).'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.scheduled_amount',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_actual_amount' => array(
+ ],
+ 'pledge_payment_actual_amount' => [
'name' => 'actual_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Actual Amount') ,
- 'description' => 'Actual amount that is paid as the Pledged installment amount.',
- 'precision' => array(
+ 'title' => ts('Actual Amount'),
+ 'description' => ts('Actual amount that is paid as the Pledged installment amount.'),
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.actual_amount',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'currency' => array(
+ ],
+ 'currency' => [
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Currency') ,
- 'description' => '3 character string, value from config setting or input via user.',
+ 'title' => ts('Currency'),
+ 'description' => ts('3 character string, value from config setting or input via user.'),
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
+ 'where' => 'civicrm_pledge_payment.currency',
'default' => 'NULL',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
- )
- ) ,
- 'pledge_payment_scheduled_date' => array(
+ ]
+ ],
+ 'pledge_payment_scheduled_date' => [
'name' => 'scheduled_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Scheduled Date') ,
- 'description' => 'The date the pledge payment is supposed to happen.',
- 'required' => true,
- 'import' => true,
+ 'title' => ts('Scheduled Date'),
+ 'description' => ts('The date the pledge payment is supposed to happen.'),
+ 'required' => TRUE,
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.scheduled_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_reminder_date' => array(
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDate',
+ ],
+ ],
+ 'pledge_payment_reminder_date' => [
'name' => 'reminder_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Last Reminder') ,
- 'description' => 'The date that the most recent payment reminder was sent.',
- 'import' => true,
+ 'title' => ts('Last Reminder'),
+ 'description' => ts('The date that the most recent payment reminder was sent.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.reminder_date',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_reminder_count' => array(
+ ],
+ 'pledge_payment_reminder_count' => [
'name' => 'reminder_count',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Reminders Sent') ,
- 'description' => 'The number of payment reminders sent.',
- 'import' => true,
+ 'title' => ts('Reminders Sent'),
+ 'description' => ts('The number of payment reminders sent.'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.reminder_count',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => true,
+ 'export' => TRUE,
+ 'default' => '0',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- ) ,
- 'pledge_payment_status_id' => array(
+ ],
+ 'pledge_payment_status_id' => [
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Payment Status') ,
- 'import' => true,
+ 'title' => ts('Payment Status'),
+ 'import' => TRUE,
'where' => 'civicrm_pledge_payment.status_id',
- 'headerPattern' => '',
- 'dataPattern' => '',
- 'export' => false,
+ 'export' => FALSE,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
- 'pseudoconstant' => array(
+ 'pseudoconstant' => [
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -341,10 +327,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_payment', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -352,33 +339,39 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_payment', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_payment', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_contribution_pledge' => array(
+ $indices = [
+ 'index_contribution_pledge' => [
'name' => 'index_contribution_pledge',
- 'field' => array(
+ 'field' => [
0 => 'contribution_id',
1 => 'pledge_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge_payment::0::contribution_id::pledge_id',
- ) ,
- 'index_status' => array(
+ ],
+ 'index_status' => [
'name' => 'index_status',
- 'field' => array(
+ 'field' => [
0 => 'status_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_pledge_payment::0::status_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Pledge/Form/Payment.php b/CRM/Pledge/Form/Payment.php
index 71038395ec57..ea24635c075b 100644
--- a/CRM/Pledge/Form/Payment.php
+++ b/CRM/Pledge/Form/Payment.php
@@ -1,9 +1,9 @@
_id) {
$params['id'] = $this->_id;
CRM_Pledge_BAO_PledgePayment::retrieve($params, $defaults);
- list($defaults['scheduled_date']) = CRM_Utils_Date::setDateDefaults($defaults['scheduled_date']);
if (isset($defaults['contribution_id'])) {
$this->assign('pledgePayment', TRUE);
}
@@ -82,69 +95,63 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
// add various dates
- $this->addDate('scheduled_date', ts('Scheduled Date'), TRUE);
+ $this->addField('scheduled_date', [], TRUE, FALSE);
$this->addMoney('scheduled_amount',
ts('Scheduled Amount'), TRUE,
- array('readonly' => TRUE),
+ ['readonly' => TRUE],
TRUE,
'currency',
NULL,
TRUE
);
- $optionTypes = array(
+ $optionTypes = [
'1' => ts('Adjust Pledge Payment Schedule?'),
'2' => ts('Adjust Total Pledge Amount?'),
- );
+ ];
$element = $this->addRadio('option_type',
NULL,
$optionTypes,
- array(), ' '
+ [], ' '
);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
/**
* Process the form submission.
*/
public function postProcess() {
- // get the submitted form values.
$formValues = $this->controller->exportValues($this->_name);
- $params = array();
- $formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']);
- $params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']);
- $params['currency'] = CRM_Utils_Array::value('currency', $formValues);
- $now = date('Ymd');
+ $params = [
+ 'id' => $this->_id,
+ 'scheduled_date' => $formValues['scheduled_date'],
+ 'currency' => $formValues['currency'],
+ ];
- if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) {
+ if (CRM_Utils_Date::overdue($params['scheduled_date'])) {
$params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Overdue');
}
else {
$params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
}
- $params['id'] = $this->_id;
$pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'pledge_id');
CRM_Pledge_BAO_PledgePayment::add($params);
- $adjustTotalAmount = FALSE;
- if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
- $adjustTotalAmount = TRUE;
- }
+ $adjustTotalAmount = (CRM_Utils_Array::value('option_type', $formValues) == 2);
$pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$params['id'],
@@ -161,7 +168,7 @@ public function postProcess() {
}
// update pledge status
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
- array($params['id']),
+ [$params['id']],
$params['status_id'],
NULL,
$formValues['scheduled_amount'],
diff --git a/CRM/Pledge/Form/Pledge.php b/CRM/Pledge/Form/Pledge.php
index 612aac95b07d..e7478f8b1310 100644
--- a/CRM/Pledge/Form/Pledge.php
+++ b/CRM/Pledge/Form/Pledge.php
@@ -1,9 +1,9 @@
_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
// check for action permissions.
if (!CRM_Core_Permission::checkActionPermission('CiviPledge', $this->_action)) {
@@ -100,14 +103,14 @@ public function preProcess() {
// build custom data
CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id);
- $this->_values = array();
+ $this->_values = [];
// current pledge id
if ($this->_id) {
// get the contribution id
$this->_contributionID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$this->_id, 'contribution_id', 'pledge_id'
);
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Pledge_BAO_Pledge::getValues($params, $this->_values);
$this->_isPending = (CRM_Pledge_BAO_Pledge::pledgeHasFinancialTransactions($this->_id, CRM_Utils_Array::value('status_id', $this->_values))) ? FALSE : TRUE;
@@ -119,7 +122,6 @@ public function preProcess() {
$this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
}
-
/**
* Set default values for the form.
* The default values are retrieved from the database.
@@ -127,7 +129,6 @@ public function preProcess() {
public function setDefaultValues() {
$defaults = $this->_values;
- $fields = array();
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
@@ -137,25 +138,13 @@ public function setDefaultValues() {
}
if ($this->_id) {
- $startDate = CRM_Utils_Array::value('start_date', $this->_values);
- $createDate = CRM_Utils_Array::value('create_date', $this->_values);
- list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($startDate);
- list($defaults['create_date']) = CRM_Utils_Date::setDateDefaults($createDate);
-
- if ($ackDate = CRM_Utils_Array::value('acknowledge_date', $this->_values)) {
- list($defaults['acknowledge_date']) = CRM_Utils_Date::setDateDefaults($ackDate);
- }
-
// check is this pledge pending.
// fix the display of the monetary value, CRM-4038.
if ($this->_isPending) {
$defaults['eachPaymentAmount'] = $this->_values['amount'] / $this->_values['installments'];
$defaults['eachPaymentAmount'] = CRM_Utils_Money::format($defaults['eachPaymentAmount'], NULL, '%a');
}
- else {
- $this->assign('start_date', $startDate);
- $this->assign('create_date', $createDate);
- }
+
// fix the display of the monetary value, CRM-4038
if (isset($this->_values['amount'])) {
$defaults['amount'] = CRM_Utils_Money::format($this->_values['amount'], NULL, '%a');
@@ -165,9 +154,8 @@ public function setDefaultValues() {
}
else {
// default values.
- list($now) = CRM_Utils_Date::setDateDefaults();
- $defaults['create_date'] = $now;
- $defaults['start_date'] = $now;
+ $defaults['create_date'] = date('Y-m-d');
+ $defaults['start_date'] = date('Y-m-d');
$defaults['installments'] = 12;
$defaults['frequency_interval'] = 1;
$defaults['frequency_day'] = 1;
@@ -208,44 +196,43 @@ public function setDefaultValues() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
return;
}
if ($this->_context == 'standalone') {
- $this->addEntityRef('contact_id', ts('Contact'), array(
- 'create' => TRUE,
- 'api' => array('extra' => array('email')),
- ), TRUE);
+ $this->addEntityRef('contact_id', ts('Contact'), [
+ 'create' => TRUE,
+ 'api' => ['extra' => ['email']],
+ ], TRUE);
}
$showAdditionalInfo = FALSE;
$this->_formType = CRM_Utils_Array::value('formType', $_GET);
- $defaults = array();
+ $defaults = [];
- $paneNames = array(
+ $paneNames = [
'Payment Reminders' => 'PaymentReminders',
- );
+ ];
foreach ($paneNames as $name => $type) {
$urlParams = "snippet=4&formType={$type}";
- $allPanes[$name] = array(
+ $allPanes[$name] = [
'url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams),
'open' => 'false',
'id' => $type,
- );
+ ];
// see if we need to include this paneName in the current form
if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
CRM_Utils_Array::value("hidden_{$type}", $defaults)
@@ -272,85 +259,50 @@ public function buildQuickForm() {
$this->assign('isPending', $this->_isPending);
- $js = array(
+ $js = [
'onblur' => "calculatedPaymentAmount( );",
'onkeyup' => "calculatedPaymentAmount( );",
- );
-
- $currencyFreeze = FALSE;
- if ($this->_id &&
- !$this->_isPending
- ) {
- $currencyFreeze = TRUE;
- }
+ ];
- $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
+ $amount = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
array_merge($attributes['pledge_amount'], $js), TRUE,
- 'currency', NULL, $currencyFreeze
+ 'currency', NULL, $this->_id && !$this->_isPending
);
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
-
- $element = &$this->add('text', 'installments', ts('To be paid in'),
+ $installments = &$this->add('text', 'installments', ts('To be paid in'),
array_merge($attributes['installments'], $js), TRUE
);
$this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
- $element = &$this->add('text', 'frequency_interval', ts('every'),
+ $frequencyInterval = $this->add('number', 'frequency_interval', ts('every'),
$attributes['pledge_frequency_interval'], TRUE
);
$this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
// Fix frequency unit display for use with frequency_interval
- $freqUnitsDisplay = array();
+ $freqUnitsDisplay = [];
foreach ($this->_freqUnits as $val => $label) {
- $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
+ $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
}
- $element = &$this->add('select', 'frequency_unit',
+ $frequencyUnit = $this->add('select', 'frequency_unit',
ts('Frequency'),
- array('' => ts('- select -')) + $freqUnitsDisplay,
+ ['' => ts('- select -')] + $freqUnitsDisplay,
TRUE
);
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
-
- $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
+ $frequencyDay = $this->add('number', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
$this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
- if ($this->_id &&
- !$this->_isPending
- ) {
- $element->freeze();
- }
- $this->add('text', 'eachPaymentAmount', ts('each'), array(
- 'size' => 10,
- 'style' => "background-color:#EBECE4",
- 0 => 'READONLY', // WTF, preserved because its inexplicable
- ));
+ $this->add('text', 'eachPaymentAmount', ts('each'), [
+ 'size' => 10,
+ 'style' => "background-color:#EBECE4",
+ // WTF, preserved because its inexplicable
+ 0 => 'READONLY',
+ ]);
// add various dates
- if (!$this->_id || $this->_isPending) {
- $this->addDate('create_date', ts('Pledge Made'), TRUE);
- $this->addDate('start_date', ts('Payments Start'), TRUE);
- }
+ $createDate = $this->add('datepicker', 'create_date', ts('Pledge Made'), [], TRUE, ['time' => FALSE]);
+ $startDate = $this->add('datepicker', 'start_date', ts('Payments Start'), [], TRUE, ['time' => FALSE]);
if (!empty($this->_values['currency'])) {
$this->assign('currency', $this->_values['currency']);
@@ -359,12 +311,16 @@ public function buildQuickForm() {
$this->assign('currency', $this->_submitValues['currency']);
}
- if ($this->_id &&
- !$this->_isPending
- ) {
+ if ($this->_id && !$this->_isPending) {
+ $amount->freeze();
+ $installments->freeze();
+ $createDate->freeze();
+ $startDate->freeze();
+ $frequencyInterval->freeze();
+ $frequencyUnit->freeze();
+ $frequencyDay->freeze();
$eachPaymentAmount = $this->_values['original_installment_amount'];
$this->assign('eachPaymentAmount', $eachPaymentAmount);
- $this->assign('hideCalender', TRUE);
}
if (CRM_Utils_Array::value('status_id', $this->_values) !=
@@ -372,34 +328,34 @@ public function buildQuickForm() {
) {
$this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
- array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
+ ['onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );"]
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
}
- $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
+ $this->add('datepicker', 'acknowledge_date', ts('Acknowledgment Date'), [], FALSE, ['time' => FALSE]);
$this->add('select', 'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
+ ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::financialType(),
TRUE
);
// CRM-7362 --add campaigns.
CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
- $pageIds = array();
+ $pageIds = [];
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
- 'civicrm_contribution_page', $pageIds, array('entity_id')
+ 'civicrm_contribution_page', $pageIds, ['entity_id']
);
$pages = CRM_Contribute_PseudoConstant::contributionPage();
- $pledgePages = array();
+ $pledgePages = [];
foreach ($pageIds as $key => $value) {
$pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
}
- $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
- array('' => ts('- select -')) + $pledgePages
+ $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
+ ['' => ts('- select -')] + $pledgePages
);
$mailingInfo = Civi::settings()->get('mailing_backend');
@@ -410,27 +366,26 @@ public function buildQuickForm() {
// make this form an upload since we dont know if the custom data injected dynamically
// is of type file etc $uploadNames = $this->get( 'uploadNames' );
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'upload',
'name' => ts('Save'),
- 'js' => array('onclick' => "return verify( );"),
+ 'js' => ['onclick' => "return verify( );"],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'upload',
'name' => ts('Save and New'),
- 'js' => array('onclick' => "return verify( );"),
+ 'js' => ['onclick' => "return verify( );"],
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
- $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
+ $this->addFormRule(['CRM_Pledge_Form_Pledge', 'formRule'], $this);
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
@@ -451,7 +406,7 @@ public function buildQuickForm() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
- $errors = array();
+ $errors = [];
if ($fields['amount'] <= 0) {
$errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
@@ -492,7 +447,7 @@ public function postProcess() {
$session = CRM_Core_Session::singleton();
- $fields = array(
+ $fields = [
'frequency_unit',
'frequency_interval',
'frequency_day',
@@ -503,7 +458,7 @@ public function postProcess() {
'additional_reminder_day',
'contribution_page_id',
'campaign_id',
- );
+ ];
foreach ($fields as $f) {
$params[$f] = CRM_Utils_Array::value($f, $formValues);
}
@@ -513,7 +468,7 @@ public function postProcess() {
$params['currency'] = CRM_Utils_Array::value('currency', $formValues);
$params['original_installment_amount'] = ($params['amount'] / $params['installments']);
- $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
+ $dates = ['create_date', 'start_date', 'acknowledge_date', 'cancel_date'];
foreach ($dates as $d) {
if ($this->_id && (!$this->_isPending) && !empty($this->_values[$d])) {
if ($d == 'start_date') {
@@ -596,7 +551,7 @@ public function postProcess() {
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
}
- $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1. ", array(1 => $this->userEmail));
+ $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1. ", [1 => $this->userEmail]);
// build the payment urls.
if ($this->paymentId) {
@@ -610,13 +565,13 @@ public function postProcess() {
"billing_mode IN ( 1, 3 )"
);
if (count($processors) > 0) {
- $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge OR submit a credit card payment.", array(
- 1 => $contribURL,
- 2 => $creditURL,
- ));
+ $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge OR submit a credit card payment.", [
+ 1 => $contribURL,
+ 2 => $creditURL,
+ ]);
}
else {
- $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge.", array(1 => $contribURL));
+ $statusMsg .= ' ' . ts("If a payment is due now, you can record a check, EFT, or cash payment for this pledge.", [1 => $contribURL]);
}
}
}
diff --git a/CRM/Pledge/Form/PledgeView.php b/CRM/Pledge/Form/PledgeView.php
index 899c00a59f55..0509c6bd407b 100644
--- a/CRM/Pledge/Form/PledgeView.php
+++ b/CRM/Pledge/Form/PledgeView.php
@@ -1,9 +1,9 @@
$this->get('id'));
+ $values = $ids = [];
+ $params = ['id' => $this->get('id')];
CRM_Pledge_BAO_Pledge::getValues($params,
$values,
$ids
);
- $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit']));
+ $values['frequencyUnit'] = ts('%1(s)', [1 => $values['frequency_unit']]);
if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) {
$sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"];
@@ -80,7 +80,7 @@ public function preProcess() {
"action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
- $recentOther = array();
+ $recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
@@ -129,15 +129,14 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Done'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Form/Search.php b/CRM/Pledge/Form/Search.php
index e0e23cfa0618..e4a0354e0147 100644
--- a/CRM/Pledge/Form/Search.php
+++ b/CRM/Pledge/Form/Search.php
@@ -1,9 +1,9 @@
_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
- $this->defaults = array();
- // we allow the controller to set force/reset externally, useful when we are being
- // driven by the wizard framework
-
- $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
- $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
- $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
-
- $this->assign("context", $this->_context);
+ $this->loadStandardSearchOptionsFromUrl();
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
@@ -145,7 +137,7 @@ public function preProcess() {
*/
public function buildQuickForm() {
parent::buildQuickForm();
- $this->addSortNameField();
+ $this->addContactSearchFields();
CRM_Pledge_BAO_Query::buildSearchForm($this);
@@ -155,9 +147,7 @@ public function buildQuickForm() {
$this->addRowSelectors($rows);
}
- $permission = CRM_Core_Permission::getPermission();
-
- $this->addTaskMenu(CRM_Pledge_Task::permissionedTaskTitles($permission));
+ $this->addTaskMenu(CRM_Pledge_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission()));
}
}
@@ -184,6 +174,36 @@ protected function getSortNameLabelWithOutEmail() {
return ts('Pledger Name');
}
+ /**
+ * Get the label for the tag field.
+ *
+ * We do this in a function so the 'ts' wraps the whole string to allow
+ * better translation.
+ *
+ * @return string
+ */
+ protected function getTagLabel() {
+ return ts('Pledger Tag(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getGroupLabel() {
+ return ts('Pledger Group(s)');
+ }
+
+ /**
+ * Get the label for the group field.
+ *
+ * @return string
+ */
+ protected function getContactTypeLabel() {
+ return ts('Pledger Contact Type');
+ }
+
/**
* The post processing of the form gets done here.
*
@@ -212,7 +232,7 @@ public function postProcess() {
$this->_formValues["pledge_test"] = 0;
}
- foreach (array('pledge_amount_low', 'pledge_amount_high') as $f) {
+ foreach (['pledge_amount_low', 'pledge_amount_high'] as $f) {
if (isset($this->_formValues[$f])) {
$this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
}
@@ -291,25 +311,7 @@ public function postProcess() {
* @see valid_date
*/
public function addRules() {
- $this->addFormRule(array('CRM_Pledge_Form_Search', 'formRule'));
- }
-
- /**
- * Global validation rules for the form.
- *
- * @param array $fields
- * Posted values of the form.
- *
- * @return array|bool
- */
- public static function formRule($fields) {
- $errors = array();
-
- if (!empty($errors)) {
- return $errors;
- }
-
- return TRUE;
+ $this->addFormRule(['CRM_Pledge_Form_Search', 'formRule']);
}
/**
@@ -320,7 +322,7 @@ public static function formRule($fields) {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$defaults = $this->_formValues;
return $defaults;
}
@@ -333,8 +335,8 @@ public function fixFormValues() {
// set pledge payment related fields
$status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
- $this->_formValues['pledge_payment_status_id'] = array($status => 1);
- $this->_defaults['pledge_payment_status_id'] = array($status => 1);
+ $this->_formValues['pledge_payment_status_id'] = [$status => 1];
+ $this->_defaults['pledge_payment_status_id'] = [$status => 1];
}
$fromDate = CRM_Utils_Request::retrieve('start', 'Date');
@@ -360,7 +362,7 @@ public function fixFormValues() {
// we need set all statuses except Cancelled
unset($statusValues[$pledgeStatus]);
- $statuses = array();
+ $statuses = [];
foreach ($statusValues as $statusId => $value) {
$statuses[$statusId] = 1;
}
diff --git a/CRM/Pledge/Form/Task.php b/CRM/Pledge/Form/Task.php
index 218da6c3a8e3..ede0eb0caaf8 100644
--- a/CRM/Pledge/Form/Task.php
+++ b/CRM/Pledge/Form/Task.php
@@ -1,9 +1,9 @@
_pledgeIds = array();
+ public static function preProcessCommon(&$form) {
+ $form->_pledgeIds = [];
$values = $form->controller->exportValues('Search');
@@ -86,7 +65,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
$pledgeTasks = CRM_Pledge_Task::tasks();
$form->assign('taskName', $pledgeTasks[$form->_task]);
- $ids = array();
+ $ids = [];
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
@@ -135,7 +114,7 @@ public static function preProcessCommon(&$form, $useTable = FALSE) {
* since its used for things like send email
*/
public function setContactIDs() {
- $this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_pledgeIds,
+ $this->_contactIds = CRM_Core_DAO::getContactIDsFromComponent($this->_pledgeIds,
'civicrm_pledge'
);
}
@@ -151,18 +130,17 @@ public function setContactIDs() {
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => $backType,
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Form/Task/Delete.php b/CRM/Pledge/Form/Task/Delete.php
index 2c924ff17c96..deb28e3e3911 100644
--- a/CRM/Pledge/Form/Task/Delete.php
+++ b/CRM/Pledge/Form/Task/Delete.php
@@ -1,9 +1,9 @@
'%count pledges deleted.', 'count' => $deleted));
+ $msg = ts('%count pledge deleted.', ['plural' => '%count pledges deleted.', 'count' => $deleted]);
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
- CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
+ CRM_Core_Session::setStatus(ts('1 could not be deleted.', ['plural' => '%count could not be deleted.', 'count' => $failed]), ts('Error'), 'error');
}
}
diff --git a/CRM/Pledge/Form/Task/Print.php b/CRM/Pledge/Form/Task/Print.php
index 5dee67b7536f..5af5df8d0b6a 100644
--- a/CRM/Pledge/Form/Task/Print.php
+++ b/CRM/Pledge/Form/Task/Print.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Print Pledge List'),
- 'js' => array('onclick' => 'window.print()'),
+ 'js' => ['onclick' => 'window.print()'],
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'back',
'name' => ts('Done'),
- ),
- )
- );
+ ],
+ ]);
}
/**
diff --git a/CRM/Pledge/Form/Task/Result.php b/CRM/Pledge/Form/Task/Result.php
index 5e838317a6a2..385a151fa001 100644
--- a/CRM/Pledge/Form/Task/Result.php
+++ b/CRM/Pledge/Form/Task/Result.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Form/Task/SearchTaskHookSample.php b/CRM/Pledge/Form/Task/SearchTaskHookSample.php
index 9cc917aa5057..0c8576ece9ea 100644
--- a/CRM/Pledge/Form/Task/SearchTaskHookSample.php
+++ b/CRM/Pledge/Form/Task/SearchTaskHookSample.php
@@ -1,9 +1,9 @@
_pledgeIds);
@@ -56,11 +56,11 @@ public function preProcess() {
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
- $rows[] = array(
+ $rows[] = [
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'create_date' => CRM_Utils_Date::customFormat($dao->create_date),
- );
+ ];
}
$this->assign('rows', $rows);
}
@@ -69,14 +69,13 @@ public function preProcess() {
* Build the form object.
*/
public function buildQuickForm() {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- )
- );
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Info.php b/CRM/Pledge/Info.php
index 56f445a4edc7..3bbac1648b0d 100644
--- a/CRM/Pledge/Info.php
+++ b/CRM/Pledge/Info.php
@@ -1,9 +1,9 @@
'CiviPledge',
'translatedName' => ts('CiviPledge'),
'title' => ts('CiviCRM Pledge Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
- );
+ ];
}
-
/**
* @inheritDoc
* Provides permissions that are used by component.
@@ -76,20 +76,20 @@ public function getInfo() {
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
- $permissions = array(
- 'access CiviPledge' => array(
+ $permissions = [
+ 'access CiviPledge' => [
ts('access CiviPledge'),
ts('View pledges'),
- ),
- 'edit pledges' => array(
+ ],
+ 'edit pledges' => [
ts('edit pledges'),
ts('Create and update pledges'),
- ),
- 'delete in CiviPledge' => array(
+ ],
+ 'delete in CiviPledge' => [
ts('delete in CiviPledge'),
ts('Delete pledges'),
- ),
- );
+ ],
+ ];
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
@@ -110,13 +110,13 @@ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = F
* null if no element offered
*/
public function getUserDashboardElement() {
- return array(
+ return [
'name' => ts('Pledges'),
'title' => ts('Your Pledge(s)'),
// we need to check this permission since you can click on contribution page link for making payment
- 'perm' => array('make online contributions'),
+ 'perm' => ['make online contributions'],
'weight' => 15,
- );
+ ];
}
/**
@@ -129,11 +129,19 @@ public function getUserDashboardElement() {
* null if no element offered
*/
public function registerTab() {
- return array(
+ return [
'title' => ts('Pledges'),
'url' => 'pledge',
'weight' => 25,
- );
+ ];
+ }
+
+ /**
+ * @inheritDoc
+ * @return string
+ */
+ public function getIcon() {
+ return 'crm-i fa-paper-plane';
}
/**
@@ -146,10 +154,10 @@ public function registerTab() {
* null if no element offered
*/
public function registerAdvancedSearchPane() {
- return array(
+ return [
'title' => ts('Pledges'),
'weight' => 25,
- );
+ ];
}
/**
@@ -174,14 +182,14 @@ public function creatNewShortcut(&$shortCuts) {
if (CRM_Core_Permission::check('access CiviPledge') &&
CRM_Core_Permission::check('edit pledges')
) {
- $shortCuts = array_merge($shortCuts, array(
- array(
+ $shortCuts = array_merge($shortCuts, [
+ [
'path' => 'civicrm/pledge/add',
'query' => 'reset=1&action=add&context=standalone',
'ref' => 'new-pledge',
'title' => ts('Pledge'),
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Pledge/Page/AJAX.php b/CRM/Pledge/Page/AJAX.php
index 6a68cf132e01..fc3532cc57a6 100644
--- a/CRM/Pledge/Page/AJAX.php
+++ b/CRM/Pledge/Page/AJAX.php
@@ -1,9 +1,9 @@
get('fiscalYearStart');
- $year = array('Y' => date('Y'));
+ $year = ['Y' => date('Y')];
$this->assign('curYear', $year['Y']);
$yearDate = array_merge($year, $yearDate);
$yearDate = CRM_Utils_Date::format($yearDate);
diff --git a/CRM/Pledge/Page/Payment.php b/CRM/Pledge/Page/Payment.php
index 16f352b34955..4de246d4ea91 100644
--- a/CRM/Pledge/Page/Payment.php
+++ b/CRM/Pledge/Page/Payment.php
@@ -1,9 +1,9 @@
_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
- $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->assign('action', $this->_action);
$this->assign('context', $this->_context);
diff --git a/CRM/Pledge/Page/Tab.php b/CRM/Pledge/Page/Tab.php
index 601f61ec6b03..3c44c2344bcf 100644
--- a/CRM/Pledge/Page/Tab.php
+++ b/CRM/Pledge/Page/Tab.php
@@ -1,9 +1,9 @@
assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('pledge', $this->_contactId);
// Refresh other tabs with related data
- $this->ajaxResponse['updateTabs'] = array(
+ $this->ajaxResponse['updateTabs'] = [
'#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
- );
+ ];
}
}
@@ -94,7 +94,7 @@ public function edit() {
}
public function preProcess() {
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -156,7 +156,7 @@ public function run() {
* @param $form
*/
public static function setContext(&$form) {
- $context = CRM_Utils_Request::retrieve('context', 'String', $form, FALSE, 'search');
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form, FALSE, 'search');
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $form);
// validate the qfKey
diff --git a/CRM/Pledge/Page/UserDashboard.php b/CRM/Pledge/Page/UserDashboard.php
index 447286349dca..82a091391d66 100644
--- a/CRM/Pledge/Page/UserDashboard.php
+++ b/CRM/Pledge/Page/UserDashboard.php
@@ -1,9 +1,9 @@
run();
// add honor block.
- $honorParams = array();
+ $honorParams = [];
$honorParams = CRM_Pledge_BAO_Pledge::getHonorContacts($this->_contactId);
if (!empty($honorParams)) {
// assign vars to templates
diff --git a/CRM/Pledge/Selector/Search.php b/CRM/Pledge/Selector/Search.php
index e5f253180cac..94551d9544ae 100644
--- a/CRM/Pledge/Selector/Search.php
+++ b/CRM/Pledge/Selector/Search.php
@@ -1,9 +1,9 @@
array(
+ self::$_links = [
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=pledge' . $extraParams,
'title' => ts('View Pledge'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Pledge'),
- ),
- CRM_Core_Action::DETACH => array(
+ ],
+ CRM_Core_Action::DETACH => [
'name' => ts('Cancel'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=detach&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'extra' => 'onclick = "return confirm(\'' . $cancelExtra . '\');"',
'title' => ts('Cancel Pledge'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Pledge'),
- ),
- );
+ ],
+ ];
if (in_array('Cancel', $hideOption)) {
unset(self::$_links[CRM_Core_Action::DETACH]);
@@ -287,7 +287,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
);
// process the result of the query
- $rows = array();
+ $rows = [];
// get all pledge status
$pledgeStatuses = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
@@ -296,7 +296,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
// CRM-4418 check for view, edit and delete
- $permissions = array(CRM_Core_Permission::VIEW);
+ $permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('edit pledges')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
@@ -306,7 +306,7 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
- $row = array();
+ $row = [];
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
@@ -319,15 +319,17 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['campaign_id'] = $result->pledge_campaign_id;
// add pledge status name
- $row['pledge_status_name'] = CRM_Utils_Array::value($row['pledge_status_id'],
- $pledgeStatuses
- );
+ if (!empty($row['pledge_status_id'])) {
+ $row['pledge_status_name'] = CRM_Utils_Array::value($row['pledge_status_id'],
+ $pledgeStatuses
+ );
+ }
// append (test) to status label
if (!empty($row['pledge_is_test'])) {
- $row['pledge_status'] .= ' (test)';
+ $row['pledge_status'] = CRM_Core_TestEntity::appendTestText($row['pledge_status']);
}
- $hideOption = array();
+ $hideOption = [];
if (CRM_Utils_Array::key('Cancelled', $row) ||
CRM_Utils_Array::key('Completed', $row)
) {
@@ -338,11 +340,11 @@ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$row['action'] = CRM_Core_Action::formLink(self::links($hideOption, $this->_key),
$mask,
- array(
+ [
'id' => $result->pledge_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
- ),
+ ],
ts('more'),
FALSE,
'pledge.selector.row',
@@ -381,57 +383,57 @@ public function getQILL() {
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
- self::$_columnHeaders = array(
- array(
+ self::$_columnHeaders = [
+ [
'name' => ts('Pledged'),
'sort' => 'pledge_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Total Paid'),
'sort' => 'pledge_total_paid',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Balance'),
- ),
- array(
+ ],
+ [
'name' => ts('Pledged For'),
'sort' => 'pledge_financial_type',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Pledge Made'),
'sort' => 'pledge_create_date',
'direction' => CRM_Utils_Sort::DESCENDING,
- ),
- array(
+ ],
+ [
'name' => ts('Next Pay Date'),
'sort' => 'pledge_next_pay_date',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Next Amount'),
'sort' => 'pledge_next_pay_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array(
+ ],
+ [
'name' => ts('Status'),
'sort' => 'pledge_status',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- array('desc' => ts('Actions')),
- );
+ ],
+ ['desc' => ts('Actions')],
+ ];
if (!$this->_single) {
- $pre = array(
- array('desc' => ts('Contact ID')),
- array(
+ $pre = [
+ ['desc' => ts('Contact ID')],
+ [
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
- ),
- );
+ ],
+ ];
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
diff --git a/CRM/Pledge/StateMachine/Search.php b/CRM/Pledge/StateMachine/Search.php
index a809e91fd2e8..1bf31c5c09b4 100644
--- a/CRM/Pledge/StateMachine/Search.php
+++ b/CRM/Pledge/StateMachine/Search.php
@@ -1,9 +1,9 @@
_pages = array();
+ $this->_pages = [];
$this->_pages['CRM_Pledge_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
@@ -80,7 +80,7 @@ public function __construct($controller, $action = CRM_Core_Action::NONE) {
*
* @param string $formName
*
- * @return string
+ * @return array
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
diff --git a/CRM/Pledge/Task.php b/CRM/Pledge/Task.php
index feeaf1073449..39309019b676 100644
--- a/CRM/Pledge/Task.php
+++ b/CRM/Pledge/Task.php
@@ -1,9 +1,9 @@
array(
+ self::$_tasks = [
+ self::TASK_DELETE => [
'title' => ts('Delete pledges'),
'class' => 'CRM_Pledge_Form_Task_Delete',
'result' => FALSE,
- ),
- 2 => array(
+ ],
+ self::TASK_PRINT => [
'title' => ts('Print selected rows'),
'class' => 'CRM_Pledge_Form_Task_Print',
'result' => FALSE,
- ),
- 3 => array(
+ ],
+ self::TASK_EXPORT => [
'title' => ts('Export pledges'),
- 'class' => array(
+ 'class' => [
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
- ),
+ ],
'result' => FALSE,
- ),
- );
+ ],
+ ];
// CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviPledge')) {
- unset(self::$_tasks[1]);
+ unset(self::$_tasks[self::TASK_DELETE]);
}
- CRM_Utils_Hook::searchTasks('pledge', self::$_tasks);
- asort(self::$_tasks);
+ parent::tasks();
}
return self::$_tasks;
}
- /**
- * These tasks are the core set of task titles.
- *
- * @return array
- * the set of task titles
- */
- public static function &taskTitles() {
- self::tasks();
- $titles = array();
- foreach (self::$_tasks as $id => $value) {
- $titles[$id] = $value['title'];
- }
- return $titles;
- }
-
- /**
- * These tasks get added based on the context the user is in.
- *
- * @return array
- * the set of optional tasks for a group of contacts
- */
- public static function &optionalTaskTitle() {
- $tasks = array();
- return $tasks;
- }
-
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
+ * @param array $params
*
* @return array
* set of tasks that are valid for the user
*/
- public static function &permissionedTaskTitles($permission) {
- $tasks = array();
+ public static function permissionedTaskTitles($permission, $params = []) {
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit pledges')
) {
$tasks = self::taskTitles();
}
else {
- $tasks = array(
- 3 => self::$_tasks[3]['title'],
- );
+ $tasks = [
+ self::TASK_EXPORT => self::$_tasks[self::TASK_EXPORT]['title'],
+ ];
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviPledge')) {
- $tasks[1] = self::$_tasks[1]['title'];
+ $tasks[self::TASK_DELETE] = self::$_tasks[self::TASK_DELETE]['title'];
}
}
+
+ $tasks = parent::corePermissionedTaskTitles($tasks, $permission, $params);
return $tasks;
}
@@ -158,14 +120,12 @@ public static function &permissionedTaskTitles($permission) {
*/
public static function getTask($value) {
self::tasks();
- if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
- // make the print task by default
- $value = 2;
+
+ if (!CRM_Utils_Array::value($value, self::$_tasks)) {
+ // make it the print task by default
+ $value = self::TASK_PRINT;
}
- return array(
- self::$_tasks[$value]['class'],
- self::$_tasks[$value]['result'],
- );
+ return parent::getTask($value);
}
}
diff --git a/CRM/Price/BAO/LineItem.php b/CRM/Price/BAO/LineItem.php
index 2b782e48f804..4524376162f0 100644
--- a/CRM/Price/BAO/LineItem.php
+++ b/CRM/Price/BAO/LineItem.php
@@ -1,9 +1,9 @@
- * $Id$
+ * @copyright CiviCRM LLC (c) 2004-2019
*/
/**
@@ -70,6 +61,8 @@ public static function create(&$params) {
// unset entity table and entity id in $params
// we never update the entity table and entity id during update mode
if ($id) {
+ $entity_id = CRM_Utils_Array::value('entity_id', $params);
+ $entity_table = CRM_Utils_Array::value('entity_table', $params);
unset($params['entity_id'], $params['entity_table']);
}
else {
@@ -92,16 +85,19 @@ public static function create(&$params) {
$return = $lineItemBAO->save();
if ($lineItemBAO->entity_table == 'civicrm_membership' && $lineItemBAO->contribution_id && $lineItemBAO->entity_id) {
- $membershipPaymentParams = array(
+ $membershipPaymentParams = [
'membership_id' => $lineItemBAO->entity_id,
'contribution_id' => $lineItemBAO->contribution_id,
- );
+ ];
if (!civicrm_api3('MembershipPayment', 'getcount', $membershipPaymentParams)) {
civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
}
}
if ($id) {
+ // CRM-21281: Restore entity reference in case the post hook needs it
+ $lineItemBAO->entity_id = $entity_id;
+ $lineItemBAO->entity_table = $entity_table;
CRM_Utils_Hook::post('edit', 'LineItem', $id, $lineItemBAO);
}
else {
@@ -143,7 +139,7 @@ public static function retrieve(&$params, &$defaults) {
public static function getAPILineItemParams(&$params) {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types);
if ($types && empty($params['financial_type_id'])) {
- $params['financial_type_id'] = array('IN' => array_keys($types));
+ $params['financial_type_id'] = ['IN' => array_keys($types)];
}
elseif ($types) {
if (is_array($params['financial_type_id'])) {
@@ -153,7 +149,7 @@ public static function getAPILineItemParams(&$params) {
$invalidFts = $params['financial_type_id'];
}
if ($invalidFts) {
- $params['financial_type_id'] = array('NOT IN' => $invalidFts);
+ $params['financial_type_id'] = ['NOT IN' => $invalidFts];
}
}
else {
@@ -170,7 +166,7 @@ public static function getLineTotal($contributionId) {
$sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
FROM civicrm_line_item li
WHERE li.contribution_id = %1";
- $params = array(1 => array($contributionId, 'Integer'));
+ $params = [1 => [$contributionId, 'Integer']];
$lineItemTotal = CRM_Core_DAO::singleValueQuery($sqlLineItemTotal, $params);
return $lineItemTotal;
}
@@ -182,7 +178,7 @@ public static function getLineTotal($contributionId) {
* @return array
*/
public static function getLineItemsByContributionID($contributionID) {
- return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
+ return self::getLineItems($contributionID, 'contribution', NULL, TRUE, TRUE);
}
/**
@@ -257,16 +253,16 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
$whereClause .= " and li.qty != 0";
}
- $lineItems = array();
+ $lineItems = [];
if (!$entityId || !$entity || !$fromClause) {
return $lineItems;
}
- $params = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entity, 'Text'),
- );
+ $params = [
+ 1 => [$entityId, 'Integer'],
+ 2 => [$entity, 'Text'],
+ ];
$getTaxDetails = FALSE;
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
@@ -277,7 +273,7 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
if (!$dao->id) {
continue;
}
- $lineItems[$dao->id] = array(
+ $lineItems[$dao->id] = [
'qty' => (float) $dao->qty,
'label' => $dao->label,
'unit_price' => $dao->unit_price,
@@ -297,7 +293,7 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
'membership_num_terms' => $dao->membership_num_terms,
'tax_amount' => $dao->tax_amount,
'price_set_id' => $dao->price_set_id,
- );
+ ];
$taxRates = CRM_Core_PseudoConstant::getTaxRates();
if (isset($lineItems[$dao->id]['financial_type_id']) && array_key_exists($lineItems[$dao->id]['financial_type_id'], $taxRates)) {
// Cast to float so trailing zero decimals are removed for display.
@@ -313,6 +309,7 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
}
}
if ($invoicing) {
+ // @todo - this is an inappropriate place to be doing form level assignments.
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
$smarty = CRM_Core_Smarty::singleton();
$smarty->assign('taxTerm', $taxTerm);
@@ -336,6 +333,11 @@ public static function getLineItems($entityId, $entity = 'participant', $isQuick
* this is
* lineItem array)
* @param string $amount_override
+ * Amount override must be in format 1000.00 - ie no thousand separator & if
+ * a decimal point is used it should be a decimal
+ *
+ * @todo - this parameter is only used for partial payments. It's unclear why a partial
+ * payment would change the line item price.
*/
public static function format($fid, $params, $fields, &$values, $amount_override = NULL) {
if (empty($params["price_{$fid}"])) {
@@ -344,7 +346,7 @@ public static function format($fid, $params, $fields, &$values, $amount_override
//lets first check in fun parameter,
//since user might modified w/ hooks.
- $options = array();
+ $options = [];
if (array_key_exists('options', $fields)) {
$options = $fields['options'];
}
@@ -359,13 +361,9 @@ public static function format($fid, $params, $fields, &$values, $amount_override
foreach ($params["price_{$fid}"] as $oid => $qty) {
$price = $amount_override === NULL ? $options[$oid]['amount'] : $amount_override;
- // lets clean the price in case it is not yet cleant
- // CRM-10974
- $price = CRM_Utils_Rule::cleanMoney($price);
-
$participantsPerField = CRM_Utils_Array::value('count', $options[$oid], 0);
- $values[$oid] = array(
+ $values[$oid] = [
'price_field_id' => $fid,
'price_field_value_id' => $oid,
'label' => CRM_Utils_Array::value('label', $options[$oid]),
@@ -383,7 +381,7 @@ public static function format($fid, $params, $fields, &$values, $amount_override
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $options[$oid]),
- );
+ ];
if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
$values[$oid]['auto_renew'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $values[$oid]['membership_type_id'], 'auto_renew');
@@ -405,7 +403,7 @@ public static function deleteLineItems($entityId, $entityTable) {
}
if ($entityId && !is_array($entityId)) {
- $entityId = array($entityId);
+ $entityId = [$entityId];
}
$query = "DELETE FROM civicrm_line_item where entity_id IN ('" . implode("','", $entityId) . "') AND entity_table = '$entityTable'";
@@ -457,8 +455,11 @@ public static function processPriceSet($entityId, $lineItem, $contributionDetail
// CRM-19094: entity_table is set to civicrm_membership then ensure
// the entityId is set to membership ID not contribution by default
elseif ($line['entity_table'] == 'civicrm_membership' && !empty($line['entity_id']) && $line['entity_id'] == $contributionDetails->id) {
- $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', 'contribution_id', $line['entity_id'], 'membership_id');
- $line['entity_id'] = $membershipId ? $membershipId : $line['entity_id'];
+ $membershipId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $contributionDetails->id, 'membership_id', 'contribution_id');
+ if ($membershipId && (int) $membershipId !== (int) $line['entity_id']) {
+ $line['entity_id'] = $membershipId;
+ Civi::log()->warning('Per https://lab.civicrm.org/dev/core/issues/15 this data fix should not be required. Please log a ticket at https://lab.civicrm.org/dev/core with steps to get this.', ['civi.tag' => 'deprecated']);
+ }
}
}
@@ -503,16 +504,16 @@ public static function syncLineItems($entityId, $entityTable = 'civicrm_contribu
$where = " li.entity_id = %1 AND
li.entity_table = %2 ";
- $params = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entityTable, 'String'),
- 3 => array($amount, 'Float'),
- );
+ $params = [
+ 1 => [$entityId, 'Integer'],
+ 2 => [$entityTable, 'String'],
+ 3 => [$amount, 'Float'],
+ ];
if ($entityTable == 'civicrm_contribution') {
$entityName = 'default_contribution_amount';
$where .= " AND ps.name = %4 ";
- $params[4] = array($entityName, 'String');
+ $params[4] = [$entityName, 'String'];
}
elseif ($entityTable == 'civicrm_participant') {
$from .= "
@@ -522,10 +523,10 @@ public static function syncLineItems($entityId, $entityTable = 'civicrm_contribu
li.price_field_value_id = cpfv.id ";
$where .= " AND cpse.entity_table = 'civicrm_event' AND cpse.entity_id = %5 ";
$amount = empty($amount) ? 0 : $amount;
- $params += array(
- 4 => array($otherParams['fee_label'], 'String'),
- 5 => array($otherParams['event_id'], 'String'),
- );
+ $params += [
+ 4 => [$otherParams['fee_label'], 'String'],
+ 5 => [$otherParams['event_id'], 'String'],
+ ];
}
$query = "
@@ -566,7 +567,7 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
}
$financialType = $values['financial_type_id'];
}
- $params['line_item'][$values['setID']][$values['priceFieldID']] = array(
+ $params['line_item'][$values['setID']][$values['priceFieldID']] = [
'price_field_id' => $values['priceFieldID'],
'price_field_value_id' => $values['priceFieldValueID'],
'label' => $values['label'],
@@ -575,7 +576,7 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
'line_total' => $totalAmount,
'financial_type_id' => $financialType,
'membership_type_id' => $values['membership_type_id'],
- );
+ ];
break;
}
}
@@ -604,6 +605,56 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
}
}
+ /**
+ * Build the line items for the submitted price field.
+ *
+ * This is when first building them - not an update where an entityId is already present
+ * as this is intended as a subfunction of that. Ideally getLineItemArray would call this
+ * (resolving to the same format regardless of what type of price set is being used first).
+ *
+ * @param array $priceParams
+ * These are per the way the form processes them - ie
+ * ['price_1' => 1, 'price_2' => 8]
+ * This would mean price field id 1, option 1 (or 1 unit if using is_enter_qty).
+ * @param float|NULL $overrideAmount
+ * Optional override of the amount.
+ *
+ * @param int|NULL $financialTypeID
+ * Financial type ID is the type should be overridden.
+ *
+ * @return array
+ * Line items formatted for processing. These will look like
+ * [4] => ['price_field_id' => 4, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
+ * [5] => ['price_field_id' => 5, 'price_field_value_id' => x, 'label....qty...unit_price...line_total...financial_type_id]
+ *
+ */
+ public static function buildLineItemsForSubmittedPriceField($priceParams, $overrideAmount = NULL, $financialTypeID = NULL) {
+ $lineItems = [];
+ foreach ($priceParams as $key => $value) {
+ $priceField = self::getPriceFieldMetaData($key);
+
+ if ($priceField['html_type'] === 'Text') {
+ $valueSpec = reset($priceField['values']);
+ }
+ else {
+ $valueSpec = $priceField['values'][$value];
+ }
+ $qty = $priceField['is_enter_qty'] ? $value : 1;
+ $lineItems[$priceField['id']] = [
+ 'price_field_id' => $priceField['id'],
+ 'price_field_value_id' => $valueSpec['id'],
+ 'label' => $valueSpec['label'],
+ 'qty' => $qty,
+ 'unit_price' => $overrideAmount ?: $valueSpec['amount'],
+ 'line_total' => $qty * ($overrideAmount ?: $valueSpec['amount']),
+ 'financial_type_id' => $financialTypeID ?: $valueSpec['financial_type_id'],
+ 'membership_type_id' => $valueSpec['membership_type_id'],
+ 'price_set_id' => $priceField['price_set_id'],
+ ];
+ }
+ return $lineItems;
+ }
+
/**
* Function to update related contribution of a entity and
* add/update/cancel financial records
@@ -614,7 +665,6 @@ public static function getLineItemArray(&$params, $entityId = NULL, $entityTable
* @param int $contributionId
* @param $feeBlock
* @param array $lineItems
- * @param $paidAmount
*
*/
public static function changeFeeSelections(
@@ -623,8 +673,7 @@ public static function changeFeeSelections(
$entity,
$contributionId,
$feeBlock,
- $lineItems,
- $paidAmount
+ $lineItems
) {
$entityTable = "civicrm_" . $entity;
CRM_Price_BAO_PriceSet::processAmount($feeBlock,
@@ -634,67 +683,48 @@ public static function changeFeeSelections(
$lineItemObj = new CRM_Price_BAO_LineItem();
// fetch submitted LineItems from input params and feeBlock information
- $submittedLineItems = $lineItemObj->_getSubmittedLineItems($params, $feeBlock);
-
- // retrieve the submitted price field value IDs from $submittedLineItems array keys
- $submittedPriceFieldValueIDs = empty($submittedLineItems) ? array() : array_keys($submittedLineItems);
+ $submittedLineItems = $lineItemObj->getSubmittedLineItems($params, $feeBlock);
- // get lineItems need to be updated and added to record changed fee
- list($lineItemsToAdd, $lineItemsToUpdate) = $lineItemObj->_getLineItemsToAddAndUpdate($submittedLineItems, $entityID, $entity);
-
- // cancel previous line item
- $additionalWhereClause = empty($submittedPriceFieldValueIDs) ? NULL : sprintf("price_field_value_id NOT IN (%s)", implode(', ', $submittedPriceFieldValueIDs));
- $lineItemObj->_cancelLineItems($entityID, $entityTable, $additionalWhereClause);
+ $requiredChanges = $lineItemObj->getLineItemsToAlter($submittedLineItems, $entityID, $entity);
// get financial information that need to be recorded on basis on submitted price field value IDs
- $financialItemsArray = $lineItemObj->_getFinancialItemsToRecord(
- $entityID,
- $entityTable,
- $contributionId,
- $submittedPriceFieldValueIDs
- );
+ if (!empty($requiredChanges['line_items_to_cancel']) || !empty($requiredChanges['line_items_to_update'])) {
+ // @todo - this IF is to get this through PR merge but I suspect that it should not
+ // be necessary & is masking something else.
+ $financialItemsArray = $lineItemObj->getAdjustedFinancialItemsToRecord(
+ $entityID,
+ $entityTable,
+ $contributionId,
+ array_keys($requiredChanges['line_items_to_cancel']),
+ $requiredChanges['line_items_to_update']
+ );
+ }
// update line item with changed line total and other information
$totalParticipant = $participantCount = 0;
- $amountLevel = array();
- if (!empty($lineItemsToUpdate)) {
- foreach ($lineItemsToUpdate as $priceFieldValueID => $value) {
- $taxAmount = "NULL";
- if (isset($value['tax_amount'])) {
- $taxAmount = $value['tax_amount'];
- }
+ $amountLevel = [];
+ if (!empty($requiredChanges['line_items_to_update'])) {
+ foreach ($requiredChanges['line_items_to_update'] as $priceFieldValueID => $value) {
$amountLevel[] = $value['label'] . ' - ' . (float) $value['qty'];
if ($entity == 'participant' && isset($value['participant_count'])) {
- $participantCount = $value['participant_count'];
$totalParticipant += $value['participant_count'];
}
- $updateLineItemSQL = "
- UPDATE civicrm_line_item li
- SET li.qty = {$value['qty']},
- li.line_total = {$value['line_total']},
- li.tax_amount = {$taxAmount},
- li.unit_price = {$value['unit_price']},
- li.participant_count = {$participantCount},
- li.label = %1
- WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID}) AND
- (price_field_value_id = {$priceFieldValueID}) ";
-
- CRM_Core_DAO::executeQuery($updateLineItemSQL, array(1 => array($value['label'], 'String')));
}
}
- // insert new 'adjusted amount' transaction entry and update contribution entry.
- // ensure entity_financial_trxn table has a linking of it.
- // insert new line items
- $lineItemObj->_addLineItemOnChangeFeeSelection($lineItemsToAdd, $entityID, $entityTable, $contributionId);
+ foreach (array_merge($requiredChanges['line_items_to_resurrect'], $requiredChanges['line_items_to_cancel'], $requiredChanges['line_items_to_update']) as $lineItemToAlter) {
+ // Must use BAO rather than api because a bad line it in the api which we want to avoid.
+ CRM_Price_BAO_LineItem::create($lineItemToAlter);
+ }
+
+ $lineItemObj->addLineItemOnChangeFeeSelection($requiredChanges['line_items_to_add'], $entityID, $entityTable, $contributionId);
- // the recordAdjustedAmt code would execute over here
$count = 0;
if ($entity == 'participant') {
$count = count(CRM_Event_BAO_Participant::getParticipantIds($contributionId));
}
else {
- $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', array('contribution_id' => $contributionId)));
+ $count = CRM_Utils_Array::value('count', civicrm_api3('MembershipPayment', 'getcount', ['contribution_id' => $contributionId]));
}
if ($count > 1) {
$updatedAmount = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
@@ -716,162 +746,125 @@ public static function changeFeeSelections(
if (!empty($amountLevel)) {
$updateAmountLevel = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amountLevel) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
}
- $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount, $updateAmountLevel);
+ $trxn = $lineItemObj->_recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount, $updateAmountLevel);
+ $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_DAO_Contribution', 'contribution_status_id', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'));
- $contributionCompletedStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed');
if (!empty($financialItemsArray)) {
foreach ($financialItemsArray as $updateFinancialItemInfoValues) {
$newFinancialItem = CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
// record reverse transaction only if Contribution is Completed because for pending refund or
// partially paid we are already recording the surplus owed or refund amount
- if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionCompletedStatusID ==
- CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id'))
- ) {
- $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], array(
+ if (!empty($updateFinancialItemInfoValues['financialTrxn']) && ($contributionStatus == 'Completed')) {
+ $updateFinancialItemInfoValues = array_merge($updateFinancialItemInfoValues['financialTrxn'], [
'entity_id' => $newFinancialItem->id,
'entity_table' => 'civicrm_financial_item',
- ));
+ ]);
$reverseTrxn = CRM_Core_BAO_FinancialTrxn::create($updateFinancialItemInfoValues);
// record reverse entity financial trxn linked to membership's related contribution
- civicrm_api3('EntityFinancialTrxn', 'create', array(
+ civicrm_api3('EntityFinancialTrxn', 'create', [
'entity_table' => "civicrm_contribution",
'entity_id' => $contributionId,
'financial_trxn_id' => $reverseTrxn->id,
'amount' => $reverseTrxn->total_amount,
- ));
+ ]);
unset($updateFinancialItemInfoValues['financialTrxn']);
}
- if (!empty($updateFinancialItemInfoValues['tax'])) {
- $updateFinancialItemInfoValues['tax']['amount'] = $updateFinancialItemInfoValues['amount'];
- $updateFinancialItemInfoValues['tax']['description'] = $updateFinancialItemInfoValues['description'];
- if (!empty($updateFinancialItemInfoValues['financial_account_id'])) {
- $updateFinancialItemInfoValues['financial_account_id'] = $updateFinancialItemInfoValues['tax']['financial_account_id'];
- }
- CRM_Financial_BAO_FinancialItem::create($updateFinancialItemInfoValues);
+ elseif (!empty($updateFinancialItemInfoValues['link-financial-trxn']) && $newFinancialItem->amount != 0) {
+ civicrm_api3('EntityFinancialTrxn', 'create', [
+ 'entity_id' => $newFinancialItem->id,
+ 'entity_table' => 'civicrm_financial_item',
+ 'financial_trxn_id' => $trxn->id,
+ 'amount' => $newFinancialItem->amount,
+ ]);
+ unset($updateFinancialItemInfoValues['link-financial-trxn']);
}
}
}
- $trxnId = array();
- if (!empty($trxn->id)) {
- $trxnId['id'] = $trxn->id;
- }
- $lineItemObj->_addLineItemOnChangeFeeSelection($lineItemsToAdd, $entityID, $entityTable, $contributionId, $trxnId, TRUE);
+ // @todo - it may be that trxn_id is always empty - flush out scenarios. Add tests.
+ $trxnId = !empty($trxn->id) ? ['id' => $trxn->id] : [];
+ $lineItemObj->addFinancialItemsOnLineItemsChange(array_merge($requiredChanges['line_items_to_add'], $requiredChanges['line_items_to_resurrect']), $entityID, $entityTable, $contributionId, $trxnId);
// update participant fee_amount column
- $lineItemObj->_updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
+ $lineItemObj->updateEntityRecordOnChangeFeeSelection($params, $entityID, $entity);
}
/**
- * Function to cancel Lineitem whose corrosponding price field option is
- * unselected on membership or participant backoffice form
- *
- * @param int $entityID
- * @param string $entityTable
- * @param string $additionalWhereClause
- *
- */
- protected function _cancelLineItems($entityID, $entityTable, $additionalWhereClause = NULL) {
- $whereClauses = array(
- "li.entity_id = %1",
- "li.entity_table = %2",
- );
- if ($additionalWhereClause) {
- $whereClauses[] = $additionalWhereClause;
- }
-
- $where = implode(' AND ', $whereClauses);
- $sql = "
- UPDATE civicrm_line_item li
- INNER JOIN civicrm_financial_item fi ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
- SET li.qty = 0,
- li.line_total = 0.00,
- li.tax_amount = NULL,
- li.participant_count = 0,
- li.non_deductible_amount = 0.00
- WHERE {$where} ";
-
- CRM_Core_DAO::executeQuery($sql, array(
- 1 => array($entityID, 'Integer'),
- 2 => array($entityTable, 'String'),
- ));
- }
-
- /**
- * Function to retrieve formatted financial items that need to be recorded as result of changed fee
+ * Function to retrieve financial items that need to be recorded as result of changed fee
*
* @param int $entityID
* @param string $entityTable
* @param int $contributionID
- * @param array $submittedPriceFieldValueIDs
+ * @param array $priceFieldValueIDsToCancel
+ * @param array $lineItemsToUpdate
*
* @return array
- * List of formatted Financial Items to be recorded
+ * List of formatted reverse Financial Items to be recorded
*/
- protected function _getFinancialItemsToRecord($entityID, $entityTable, $contributionID, $submittedPriceFieldValueIDs) {
+ protected function getAdjustedFinancialItemsToRecord($entityID, $entityTable, $contributionID, $priceFieldValueIDsToCancel, $lineItemsToUpdate) {
$previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, str_replace('civicrm_', '', $entityTable));
- $financialItemsArray = array();
-
- if (empty($submittedPriceFieldValueIDs)) {
- return $financialItemsArray;
- }
-
- // gathering necessary info to record negative (deselected) financial_item
- $updateFinancialItem = "
- SELECT fi.*, SUM(fi.amount) as differenceAmt, price_field_value_id, financial_type_id, tax_amount
- FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
- WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
- GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
- ";
- $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
-
- $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
- $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
- $updateFinancialItemInfoValues = array();
- while ($updateFinancialItemInfoDAO->fetch()) {
- $updateFinancialItemInfoValues = (array) $updateFinancialItemInfoDAO;
+ $financialItemsArray = [];
+ $financialItemResult = $this->getNonCancelledFinancialItems($entityID, $entityTable);
+ foreach ($financialItemResult as $updateFinancialItemInfoValues) {
$updateFinancialItemInfoValues['transaction_date'] = date('YmdHis');
- // the below params are not needed
+
+ // the below params are not needed as we are creating new financial item
$previousFinancialItemID = $updateFinancialItemInfoValues['id'];
+ $totalFinancialAmount = $this->checkFinancialItemTotalAmountByLineItemID($updateFinancialItemInfoValues['entity_id']);
unset($updateFinancialItemInfoValues['id']);
unset($updateFinancialItemInfoValues['created_date']);
+
// if not submitted and difference is not 0 make it negative
- if (!in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedPriceFieldValueIDs) && $updateFinancialItemInfoValues['differenceAmt'] != 0) {
+ if ((empty($lineItemsToUpdate) || (in_array($updateFinancialItemInfoValues['price_field_value_id'], $priceFieldValueIDsToCancel) &&
+ $totalFinancialAmount == $updateFinancialItemInfoValues['amount'])
+ ) && $updateFinancialItemInfoValues['amount'] > 0
+ ) {
// INSERT negative financial_items
$updateFinancialItemInfoValues['amount'] = -$updateFinancialItemInfoValues['amount'];
// reverse the related financial trxn too
- $updateFinancialItemInfoValues['financialTrxn'] = $this->_getRelatedCancelFinancialTrxn($previousFinancialItemID);
+ $updateFinancialItemInfoValues['financialTrxn'] = $this->getRelatedCancelFinancialTrxn($previousFinancialItemID);
if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
$updateFinancialItemInfoValues['tax']['amount'] = -($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']);
- $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
- if ($updateFinancialItemInfoValues['financial_type_id']) {
- $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($updateFinancialItemInfoValues['financial_type_id']);
- }
+ $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
}
// INSERT negative financial_items for tax amount
- $financialItemsArray[] = $updateFinancialItemInfoValues;
+ $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
}
- // if submitted and difference is 0 add a positive entry again
- elseif (in_array($updateFinancialItemInfoValues['price_field_value_id'], $submittedPriceFieldValueIDs) && $updateFinancialItemInfoValues['differenceAmt'] == 0) {
- $updateFinancialItemInfoValues['amount'] = $updateFinancialItemInfoValues['amount'];
- // INSERT financial_items for tax amount
- if ($updateFinancialItemInfoValues['entity_id'] == $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['id'] &&
- isset($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'])
- ) {
- $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['tax_amount'];
- $updateFinancialItemInfoValues['tax']['description'] = $taxTerm;
- if ($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']) {
- $updateFinancialItemInfoValues['tax']['financial_account_id'] = CRM_Contribute_BAO_Contribution::getFinancialAccountId($lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['financial_type_id']);
- }
+ // INSERT a financial item to record surplus/lesser amount when a text price fee is changed
+ elseif (!empty($lineItemsToUpdate) &&
+ $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['html_type'] == 'Text' &&
+ $updateFinancialItemInfoValues['amount'] > 0
+ ) {
+ // calculate the amount difference, considered as financial item amount
+ $updateFinancialItemInfoValues['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['price_field_value_id']]['line_total'] - $totalFinancialAmount;
+ // add a flag, later used to link financial trxn and this new financial item
+ $updateFinancialItemInfoValues['link-financial-trxn'] = TRUE;
+ if ($previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount']) {
+ $updateFinancialItemInfoValues['tax']['amount'] = $lineItemsToUpdate[$updateFinancialItemInfoValues['entity_id']]['tax_amount'] - $previousLineItems[$updateFinancialItemInfoValues['entity_id']]['tax_amount'];
+ $updateFinancialItemInfoValues['tax']['description'] = $this->getSalesTaxTerm();
}
- $financialItemsArray[] = $updateFinancialItemInfoValues;
+ $financialItemsArray[$updateFinancialItemInfoValues['entity_id']] = $updateFinancialItemInfoValues;
}
}
return $financialItemsArray;
}
+ /**
+ * Helper function to return sum of financial item's amount related to a line-item
+ * @param array $lineItemID
+ *
+ * @return float $financialItem
+ */
+ protected function checkFinancialItemTotalAmountByLineItemID($lineItemID) {
+ return CRM_Core_DAO::singleValueQuery("
+ SELECT SUM(amount)
+ FROM civicrm_financial_item
+ WHERE entity_table = 'civicrm_line_item' AND entity_id = {$lineItemID}
+ ");
+ }
+
/**
* Helper function to retrieve submitted line items from form values $inputParams and used $feeBlock
*
@@ -879,10 +872,10 @@ protected function _getFinancialItemsToRecord($entityID, $entityTable, $contribu
* @param array $feeBlock
*
* @return array
- * List of submitted line items
+ * List of submitted line items
*/
- protected function _getSubmittedLineItems($inputParams, $feeBlock) {
- $submittedLineItems = array();
+ protected function getSubmittedLineItems($inputParams, $feeBlock) {
+ $submittedLineItems = [];
foreach ($feeBlock as $id => $values) {
CRM_Price_BAO_LineItem::format($id, $inputParams, $values, $submittedLineItems);
}
@@ -891,66 +884,116 @@ protected function _getSubmittedLineItems($inputParams, $feeBlock) {
}
/**
- * Helper function to retrieve formatted lineitems need to be added and/or updated
+ * Helper function to retrieve line items that need to be altered.
+ *
+ * We iterate through the previous line items for the given entity to determine
+ * what alterations to line items need to be made to reflect the new line items.
+ *
+ * There are 4 possible changes required - per the keys in the return array.
*
* @param array $submittedLineItems
* @param int $entityID
* @param string $entity
*
* @return array
- * Array of formatted lineitems
+ * Array of line items to alter with the following keys
+ * - line_items_to_add. If the line items required are new radio options that
+ * have not previously been set then we should add line items for them
+ * - line_items_to_update. If we have already been an active option and a change has
+ * happened then it should be in this array.
+ * - line_items_to_cancel. Line items currently selected but not selected in the new selection.
+ * These need to be zero'd out.
+ * - line_items_to_resurrect. Line items previously selected and then deselected. These need to be
+ * re-enabled rather than a new one added.
*/
- protected function _getLineItemsToAddAndUpdate($submittedLineItems, $entityID, $entity) {
+ protected function getLineItemsToAlter($submittedLineItems, $entityID, $entity) {
$previousLineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entity);
$lineItemsToAdd = $submittedLineItems;
- $lineItemsToUpdate = array();
+ $lineItemsToUpdate = [];
$submittedPriceFieldValueIDs = array_keys($submittedLineItems);
+ $lineItemsToCancel = $lineItemsToResurrect = [];
foreach ($previousLineItems as $id => $previousLineItem) {
- // check through the submitted items if the previousItem exists,
- // if found in submitted items, do not use it for new item creations
if (in_array($previousLineItem['price_field_value_id'], $submittedPriceFieldValueIDs)) {
- // if submitted line items are existing don't fire INSERT query
- if ($previousLineItem['line_total'] != 0) {
+ $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
+ if (CRM_Utils_Array::value('html_type', $lineItemsToAdd[$previousLineItem['price_field_value_id']]) == 'Text') {
+ // If a 'Text' price field was updated by changing qty value, then we are not adding new line-item but updating the existing one,
+ // because unlike other kind of price-field, it's related price-field-value-id isn't changed and thats why we need to make an
+ // exception here by adding financial item for updated line-item and will reverse any previous financial item entries.
+ $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = array_merge($submittedLineItem, ['id' => $id]);
unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
}
else {
- $lineItemsToAdd[$previousLineItem['price_field_value_id']]['skip'] = TRUE;
+ $submittedLineItem = $submittedLineItems[$previousLineItem['price_field_value_id']];
+ // for updating the line items i.e. use-case - once deselect-option selecting again
+ if (($previousLineItem['line_total'] != $submittedLineItem['line_total'])
+ || (
+ // This would be a $0 line item - but why it should be catered to
+ // other than when the above condition is unclear.
+ $submittedLineItem['line_total'] == 0 && $submittedLineItem['qty'] == 1
+ )
+ || (
+ $previousLineItem['qty'] != $submittedLineItem['qty']
+ )
+ ) {
+ $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItem;
+ $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
+ // Format is actually '0.00'
+ if ($previousLineItem['line_total'] == 0) {
+ $lineItemsToAdd[$previousLineItem['price_field_value_id']]['id'] = $id;
+ $lineItemsToResurrect[] = $lineItemsToAdd[$previousLineItem['price_field_value_id']];
+ }
+ }
+ // If there was previously a submitted line item for the same option value then there is
+ // either no change or a qty adjustment. In either case we are not doing an add + reversal.
+ unset($lineItemsToAdd[$previousLineItem['price_field_value_id']]);
+ unset($lineItemsToCancel[$previousLineItem['price_field_value_id']]);
}
- // for updating the line items i.e. use-case - once deselect-option selecting again
- if (($previousLineItem['line_total'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['line_total']) ||
- ($submittedLineItems[$previousLineItem['price_field_value_id']]['line_total'] == 0 && $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'] == 1) ||
- ($previousLineItem['qty'] != $submittedLineItems[$previousLineItem['price_field_value_id']]['qty'])
- ) {
- $lineItemsToUpdate[$previousLineItem['price_field_value_id']] = $submittedLineItems[$previousLineItem['price_field_value_id']];
- $lineItemsToUpdate[$previousLineItem['price_field_value_id']]['id'] = $id;
+ }
+ else {
+ if (!$this->isCancelled($previousLineItem)) {
+ $cancelParams = ['qty' => 0, 'line_total' => 0, 'tax_amount' => 0, 'participant_count' => 0, 'non_deductible_amount' => 0, 'id' => $id];
+ $lineItemsToCancel[$previousLineItem['price_field_value_id']] = array_merge($previousLineItem, $cancelParams);
+
}
}
}
- return array($lineItemsToAdd, $lineItemsToUpdate);
+ return [
+ 'line_items_to_add' => $lineItemsToAdd,
+ 'line_items_to_update' => $lineItemsToUpdate,
+ 'line_items_to_cancel' => $lineItemsToCancel,
+ 'line_items_to_resurrect' => $lineItemsToResurrect,
+ ];
+ }
+
+ /**
+ * Check if a line item has already been cancelled.
+ *
+ * @param array $lineItem
+ *
+ * @return bool
+ */
+ protected function isCancelled($lineItem) {
+ if ($lineItem['qty'] == 0 && $lineItem['line_total'] == 0) {
+ return TRUE;
+ }
}
/**
- * Helper function to add lineitems or financial item related to it, to as result of fee change
+ * Add line Items as result of fee change.
*
* @param array $lineItemsToAdd
* @param int $entityID
* @param string $entityTable
* @param int $contributionID
- * @param array $adjustedFinancialTrxnID
- * @param bool $addFinancialItemOnly
- *
- * @return void
*/
- protected function _addLineItemOnChangeFeeSelection(
+ protected function addLineItemOnChangeFeeSelection(
$lineItemsToAdd,
$entityID,
$entityTable,
- $contributionID,
- $adjustedFinancialTrxnID = NULL,
- $addFinancialItemOnly = FALSE
+ $contributionID
) {
// if there is no line item to add, do not proceed
if (empty($lineItemsToAdd)) {
@@ -958,55 +1001,16 @@ protected function _addLineItemOnChangeFeeSelection(
}
$changedFinancialTypeID = NULL;
- $fetchCon = array('id' => $contributionID);
- $updatedContribution = CRM_Contribute_BAO_Contribution::retrieve($fetchCon, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
+ $updatedContribution = new CRM_Contribute_BAO_Contribution();
+ $updatedContribution->id = (int) $contributionID;
// insert financial items
foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
- $tempFinancialTrxnID = $adjustedFinancialTrxnID;
- $lineParams = array_merge($lineParams, array(
+ $lineParams = array_merge($lineParams, [
'entity_table' => $entityTable,
'entity_id' => $entityID,
'contribution_id' => $contributionID,
- ));
- if ($addFinancialItemOnly) {
- // don't add financial item for cancelled line item
- if ($lineParams['qty'] == 0) {
- continue;
- }
- elseif (empty($adjustedFinancialTrxnID)) {
- // add financial item if ONLY financial type is changed
- if ($lineParams['financial_type_id'] != $updatedContribution->financial_type_id) {
- $changedFinancialTypeID = $lineParams['financial_type_id'];
- $adjustedTrxnValues = array(
- 'from_financial_account_id' => NULL,
- 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($updatedContribution->payment_instrument_id),
- 'total_amount' => $lineParams['line_total'],
- 'net_amount' => $lineParams['line_total'],
- 'status_id' => $updatedContribution->contribution_status_id,
- 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
- 'contribution_id' => $updatedContribution->id,
- 'is_payment' => TRUE, // since balance is 0, which means contribution is completed
- 'trxn_date' => date('YmdHis'),
- 'currency' => $updatedContribution->currency,
- );
- $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
- $tempFinancialTrxnID = array('id' => $adjustedTrxn->id);
- }
- // don't add financial item if line_total and financial type aren't changed,
- // which is identified by empty $adjustedFinancialTrxnID
- else {
- continue;
- }
- }
- $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
- // insert financial items
- // ensure entity_financial_trxn table has a linking of it.
- CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $tempFinancialTrxnID);
- if (isset($lineObj->tax_amount)) {
- CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $tempFinancialTrxnID);
- }
- }
- elseif (!array_key_exists('skip', $lineParams)) {
+ ]);
+ if (!array_key_exists('skip', $lineParams)) {
self::create($lineParams);
}
}
@@ -1017,6 +1021,31 @@ protected function _addLineItemOnChangeFeeSelection(
}
}
+ /**
+ * Add financial transactions when an array of line items is changed.
+ *
+ * @param array $lineItemsToAdd
+ * @param int $entityID
+ * @param string $entityTable
+ * @param int $contributionID
+ * @param bool $isCreateAdditionalFinancialTrxn
+ * Is there a change to the total balance requiring additional transactions to be created.
+ */
+ protected function addFinancialItemsOnLineItemsChange($lineItemsToAdd, $entityID, $entityTable, $contributionID, $isCreateAdditionalFinancialTrxn) {
+ $updatedContribution = new CRM_Contribute_BAO_Contribution();
+ $updatedContribution->id = $contributionID;
+ $updatedContribution->find(TRUE);
+
+ foreach ($lineItemsToAdd as $priceFieldValueID => $lineParams) {
+ $lineParams = array_merge($lineParams, [
+ 'entity_table' => $entityTable,
+ 'entity_id' => $entityID,
+ 'contribution_id' => $contributionID,
+ ]);
+ $this->addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution);
+ }
+ }
+
/**
* Helper function to update entity record on change fee selection
*
@@ -1025,16 +1054,16 @@ protected function _addLineItemOnChangeFeeSelection(
* @param string $entity
*
*/
- protected function _updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
+ protected function updateEntityRecordOnChangeFeeSelection($inputParams, $entityID, $entity) {
$entityTable = "civicrm_{$entity}";
if ($entity == 'participant') {
- $partUpdateFeeAmt = array('id' => $entityID);
+ $partUpdateFeeAmt = ['id' => $entityID];
$getUpdatedLineItems = "SELECT *
FROM civicrm_line_item
WHERE (entity_table = '{$entityTable}' AND entity_id = {$entityID} AND qty > 0)";
$getUpdatedLineItemsDAO = CRM_Core_DAO::executeQuery($getUpdatedLineItems);
- $line = array();
+ $line = [];
while ($getUpdatedLineItemsDAO->fetch()) {
$line[$getUpdatedLineItemsDAO->price_field_value_id] = $getUpdatedLineItemsDAO->label . ' - ' . (float) $getUpdatedLineItemsDAO->qty;
}
@@ -1048,6 +1077,53 @@ protected function _updateEntityRecordOnChangeFeeSelection($inputParams, $entity
}
}
+ /**
+ * Get the metadata for a price field.
+ *
+ * @param string|int $key
+ * Price field id. Either as an integer or as 'price_4' where 4 is the id
+ *
+ * @return array
+ * Metadata for the price field with a values key for option values.
+ */
+ protected static function getPriceFieldMetaData($key) {
+ $priceFieldID = str_replace('price_', '', $key);
+ if (!isset(Civi::$statics[__CLASS__]['price_fields'][$priceFieldID])) {
+ $values = civicrm_api3('PriceFieldValue', 'get', [
+ 'price_field_id' => $priceFieldID,
+ 'return' => [
+ 'id',
+ 'amount',
+ 'financial_type_id',
+ 'membership_type_id',
+ 'label',
+ 'price_field_id',
+ 'price_field_id.price_set_id',
+ 'price_field_id.html_type',
+ 'is_enter_qty',
+ ],
+ ]);
+ $firstValue = reset($values['values']);
+ $values = $values['values'];
+ foreach ($values as $index => $value) {
+ // Let's be nice to calling functions & ensure membership_type_id is set
+ // so they don't have to handle notices on it. Handle one place not many.
+ if (!isset($value['membership_type_id'])) {
+ $values[$index]['membership_type_id'] = NULL;
+ }
+ }
+
+ Civi::$statics[__CLASS__]['price_fields'][$priceFieldID] = [
+ 'price_set_id' => $firstValue['price_field_id.price_set_id'],
+ 'id' => $firstValue['price_field_id'],
+ 'html_type' => $firstValue['price_field_id.html_type'],
+ 'is_enter_qty' => !empty($firstValue['is_enter_qty']),
+ 'values' => $values,
+ ];
+ }
+ return Civi::$statics[__CLASS__]['price_fields'][$priceFieldID];
+ }
+
/**
* Helper function to retrieve financial trxn parameters to reverse
* for given financial item identified by $financialItemID
@@ -1058,25 +1134,30 @@ protected function _updateEntityRecordOnChangeFeeSelection($inputParams, $entity
*
*/
protected function _getRelatedCancelFinancialTrxn($financialItemID) {
- $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', array(
- 'entity_table' => 'civicrm_financial_item',
- 'entity_id' => $financialItemID,
- 'options' => array(
- 'sort' => 'id DESC',
- 'limit' => 1,
- ),
- 'api.FinancialTrxn.getsingle' => array(
- 'id' => "\$value.financial_trxn_id",
- ),
- ));
-
- $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], array(
+ try {
+ $financialTrxn = civicrm_api3('EntityFinancialTrxn', 'getsingle', [
+ 'entity_table' => 'civicrm_financial_item',
+ 'entity_id' => $financialItemID,
+ 'options' => [
+ 'sort' => 'id DESC',
+ 'limit' => 1,
+ ],
+ 'api.FinancialTrxn.getsingle' => [
+ 'id' => "\$value.financial_trxn_id",
+ ],
+ ]);
+ }
+ catch (CiviCRM_API3_Exception $e) {
+ return [];
+ }
+
+ $financialTrxn = array_merge($financialTrxn['api.FinancialTrxn.getsingle'], [
'trxn_date' => date('YmdHis'),
'total_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['total_amount'],
'net_amount' => -$financialTrxn['api.FinancialTrxn.getsingle']['net_amount'],
'entity_table' => 'civicrm_financial_item',
'entity_id' => $financialItemID,
- ));
+ ]);
unset($financialTrxn['id']);
return $financialTrxn;
@@ -1086,21 +1167,15 @@ protected function _getRelatedCancelFinancialTrxn($financialItemID) {
* Record adjusted amount.
*
* @param int $updatedAmount
- * @param int $paidAmount
* @param int $contributionId
- *
* @param int $taxAmount
* @param bool $updateAmountLevel
*
* @return bool|\CRM_Core_BAO_FinancialTrxn
*/
- protected function _recordAdjustedAmt($updatedAmount, $paidAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
- $pendingAmount = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
- $pendingAmount = CRM_Utils_Array::value('total_amount', $pendingAmount, 0);
+ protected function _recordAdjustedAmt($updatedAmount, $contributionId, $taxAmount = NULL, $updateAmountLevel = NULL) {
+ $paidAmount = CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId);
$balanceAmt = $updatedAmount - $paidAmount;
- if ($paidAmount != $pendingAmount) {
- $balanceAmt -= $pendingAmount;
- }
$contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$partiallyPaidStatusId = array_search('Partially paid', $contributionStatuses);
@@ -1137,12 +1212,12 @@ protected function _recordAdjustedAmt($updatedAmount, $paidAmount, $contribution
$updatedContributionDAO->save();
// adjusted amount financial_trxn creation
$updatedContribution = CRM_Contribute_BAO_Contribution::getValues(
- array('id' => $contributionId),
+ ['id' => $contributionId],
CRM_Core_DAO::$_nullArray,
CRM_Core_DAO::$_nullArray
);
$toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($updatedContribution->financial_type_id, 'Accounts Receivable Account is');
- $adjustedTrxnValues = array(
+ $adjustedTrxnValues = [
'from_financial_account_id' => NULL,
'to_financial_account_id' => $toFinancialAccount,
'total_amount' => $balanceAmt,
@@ -1152,10 +1227,115 @@ protected function _recordAdjustedAmt($updatedAmount, $paidAmount, $contribution
'contribution_id' => $updatedContribution->id,
'trxn_date' => date('YmdHis'),
'currency' => $updatedContribution->currency,
- );
+ ];
$adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
}
+ // CRM-17151: Update the contribution status to completed if balance is zero,
+ // because due to sucessive fee change will leave the related contribution status incorrect
+ else {
+ CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
+ }
+
return $adjustedTrxn;
}
+ /**
+ * Add financial items to reflect line item change.
+ *
+ * @param bool $isCreateAdditionalFinancialTrxn
+ * @param array $lineParams
+ * @param \CRM_Contribute_BAO_Contribution $updatedContribution
+ */
+ protected function addFinancialItemsOnLineItemChange($isCreateAdditionalFinancialTrxn, $lineParams, $updatedContribution) {
+ $tempFinancialTrxnID = NULL;
+ // don't add financial item for cancelled line item
+ if ($lineParams['qty'] == 0) {
+ return;
+ }
+ elseif ($isCreateAdditionalFinancialTrxn) {
+ // This routine & the return below is super uncomfortable.
+ // I have refactored to here but don't understand how this would be hit
+ // and it is how it would be a good thing, given the odd return below which
+ // does not seem consistent with what is going on.
+ // I'm tempted to add an e-deprecated into it to confirm my suspicion it only exists to
+ // cause mental anguish.
+ // original comment : add financial item if ONLY financial type is changed
+ if ($lineParams['financial_type_id'] != $updatedContribution->financial_type_id) {
+ $changedFinancialTypeID = (int) $lineParams['financial_type_id'];
+ $adjustedTrxnValues = [
+ 'from_financial_account_id' => NULL,
+ 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($updatedContribution->payment_instrument_id),
+ 'total_amount' => $lineParams['line_total'],
+ 'net_amount' => $lineParams['line_total'],
+ 'status_id' => $updatedContribution->contribution_status_id,
+ 'payment_instrument_id' => $updatedContribution->payment_instrument_id,
+ 'contribution_id' => $updatedContribution->id,
+ 'is_payment' => TRUE,
+ // since balance is 0, which means contribution is completed
+ 'trxn_date' => date('YmdHis'),
+ 'currency' => $updatedContribution->currency,
+ ];
+ $adjustedTrxn = CRM_Core_BAO_FinancialTrxn::create($adjustedTrxnValues);
+ $tempFinancialTrxnID = ['id' => $adjustedTrxn->id];
+ }
+ }
+ $lineObj = CRM_Price_BAO_LineItem::retrieve($lineParams, CRM_Core_DAO::$_nullArray);
+ // insert financial items
+ // ensure entity_financial_trxn table has a linking of it.
+ CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, NULL, $tempFinancialTrxnID);
+ if (isset($lineObj->tax_amount)) {
+ CRM_Financial_BAO_FinancialItem::add($lineObj, $updatedContribution, TRUE, $tempFinancialTrxnID);
+ }
+ }
+
+ /**
+ * Get Financial items, culling out any that have already been reversed.
+ *
+ * @param int $entityID
+ * @param string $entityTable
+ *
+ * @return array
+ * Array of financial items that have not be reversed.
+ */
+ protected function getNonCancelledFinancialItems($entityID, $entityTable) {
+ // gathering necessary info to record negative (deselected) financial_item
+ $updateFinancialItem = "
+ SELECT fi.*, price_field_value_id, financial_type_id, tax_amount
+ FROM civicrm_financial_item fi LEFT JOIN civicrm_line_item li ON (li.id = fi.entity_id AND fi.entity_table = 'civicrm_line_item')
+ WHERE (li.entity_table = '{$entityTable}' AND li.entity_id = {$entityID})
+ GROUP BY li.entity_table, li.entity_id, price_field_value_id, fi.id
+ ";
+ $updateFinancialItemInfoDAO = CRM_Core_DAO::executeQuery($updateFinancialItem);
+
+ $financialItemResult = $updateFinancialItemInfoDAO->fetchAll();
+ $items = [];
+ foreach ($financialItemResult as $index => $financialItem) {
+ $items[$financialItem['price_field_value_id']][$index] = $financialItem['amount'];
+
+ if (!empty($items[$financialItem['price_field_value_id']])) {
+ foreach ($items[$financialItem['price_field_value_id']] as $existingItemID => $existingAmount) {
+ if ($financialItem['amount'] + $existingAmount == 0) {
+ // Filter both rows as they cancel each other out.
+ unset($financialItemResult[$index]);
+ unset($financialItemResult[$existingItemID]);
+ unset($items['price_field_value_id'][$existingItemID]);
+ unset($items[$financialItem['price_field_value_id']][$index]);
+ }
+ }
+
+ }
+
+ }
+ return $financialItemResult;
+ }
+
+ /**
+ * Get the string used to describe the sales tax (eg. VAT, GST).
+ *
+ * @return string
+ */
+ protected function getSalesTaxTerm() {
+ return CRM_Contribute_BAO_Contribution::checkContributeSettings('tax_term');
+ }
+
}
diff --git a/CRM/Price/BAO/PriceField.php b/CRM/Price/BAO/PriceField.php
index 025f62e3ee64..0085d6ec89d1 100644
--- a/CRM/Price/BAO/PriceField.php
+++ b/CRM/Price/BAO/PriceField.php
@@ -1,9 +1,9 @@
html_type)) {
$priceField->html_type = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
}
- $optionsIds = array();
+ $optionsIds = [];
$maxIndex = CRM_Price_Form_Field::NUM_OPTION;
if ($priceField->html_type == 'Text') {
$maxIndex = 1;
- $fieldOptions = civicrm_api3('price_field_value', 'get', array(
+ $fieldOptions = civicrm_api3('price_field_value', 'get', [
'price_field_id' => $priceField->id,
'sequential' => 1,
- ));
+ ]);
foreach ($fieldOptions['values'] as $option) {
$optionsIds['id'] = $option['id'];
// CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
@@ -119,7 +119,7 @@ public static function create(&$params) {
}
}
}
- $defaultArray = array();
+ $defaultArray = [];
//html type would be empty in update scenario not sure what would happen ...
if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
$tempArray = array_keys($params['default_checkbox_option']);
@@ -141,11 +141,11 @@ public static function create(&$params) {
(CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
!CRM_Utils_System::isNull($params['option_amount'][$index])
) {
- $options = array(
+ $options = [
'price_field_id' => $priceField->id,
'label' => trim($params['option_label'][$index]),
'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
- 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
+ 'amount' => trim($params['option_amount'][$index]),
'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
@@ -156,7 +156,7 @@ public static function create(&$params) {
'membership_num_terms' => NULL,
'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $params),
'visibility_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_visibility_id', $params), self::getVisibilityOptionID('public')),
- );
+ ];
if ($options['membership_type_id']) {
$options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
@@ -186,7 +186,7 @@ public static function create(&$params) {
}
}
elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
- $optionsLoad = civicrm_api3('price_field_value', 'get', array('id' => $optionsIds['id']));
+ $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
$options = $optionsLoad['values'][$optionsIds['id']];
$options['is_active'] = CRM_Utils_Array::value('is_active', $params, 1);
try {
@@ -225,8 +225,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) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
@@ -288,7 +288,7 @@ public static function addQuickFormElement(
$useRequired = TRUE,
$label = NULL,
$fieldOptions = NULL,
- $freezeOptions = array()
+ $freezeOptions = []
) {
$field = new CRM_Price_DAO_PriceField();
@@ -348,13 +348,13 @@ public static function addQuickFormElement(
$qf->assign('taxTerm', $taxTerm);
$qf->assign('invoicing', $invoicing);
}
- $priceVal = implode($seperator, array(
+ $priceVal = implode($seperator, [
$customOption[$optionKey][$valueFieldName] + $taxAmount,
$count,
$max_value,
- ));
+ ]);
- $extra = array();
+ $extra = [];
if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
$useRequired = 0;
}
@@ -364,21 +364,21 @@ public static function addQuickFormElement(
if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
$label .= ' ' . $currencySymbol;
$qf->assign('priceset', $elementName);
- $extra = array('onclick' => 'useAmountOther();');
+ $extra = ['onclick' => 'useAmountOther();'];
}
}
$element = &$qf->add('text', $elementName, $label,
array_merge($extra,
- array(
- 'price' => json_encode(array($optionKey, $priceVal)),
+ [
+ 'price' => json_encode([$optionKey, $priceVal]),
'size' => '4',
- )
+ ]
),
$useRequired && $field->is_required
);
if ($is_pay_later) {
- $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
+ $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
}
// CRM-6902 - Add "max" option for a price set field
@@ -394,7 +394,7 @@ public static function addQuickFormElement(
$type = 'money';
}
else {
- $message = ts('%1 must be a number (with or without decimal point).', array(1 => $label));
+ $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
$type = 'numeric';
}
// integers will have numeric rule applied to them.
@@ -402,7 +402,7 @@ public static function addQuickFormElement(
break;
case 'Radio':
- $choice = array();
+ $choice = [];
if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
$qf->assign('contriPriceset', $elementName);
@@ -413,10 +413,10 @@ public static function addQuickFormElement(
if ($field->is_display_amounts) {
$opt['label'] = !empty($opt['label']) ? $opt['label'] . ' - ' : '';
$preHelpText = $postHelpText = '';
- if (isset($opt['help_pre'])) {
+ if (!empty($opt['help_pre'])) {
$preHelpText = '' . $opt['help_pre'] . ': ';
}
- if (isset($opt['help_post'])) {
+ if (!empty($opt['help_post'])) {
$postHelpText = ': ' . $opt['help_post'] . '';
}
if (isset($taxAmount) && $invoicing) {
@@ -439,34 +439,34 @@ public static function addQuickFormElement(
}
$count = CRM_Utils_Array::value('count', $opt, '');
$max_value = CRM_Utils_Array::value('max_value', $opt, '');
- $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
+ $priceVal = implode($seperator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
if (isset($opt['visibility_id'])) {
$visibility_id = $opt['visibility_id'];
}
else {
$visibility_id = self::getVisibilityOptionID('public');
}
- $extra = array(
- 'price' => json_encode(array($elementName, $priceVal)),
+ $extra = [
+ 'price' => json_encode([$elementName, $priceVal]),
'data-amount' => $opt[$valueFieldName],
'data-currency' => $currencyName,
'data-price-field-values' => json_encode($customOption),
'visibility' => $visibility_id,
- );
+ ];
if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
- $extra += array('onclick' => 'clearAmountOther();');
+ $extra += ['onclick' => 'clearAmountOther();'];
}
- elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
- $extra += array(
+ if ($field->name == 'membership_amount') {
+ $extra += [
'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
'membership-type' => $opt['membership_type_id'],
- );
+ ];
$qf->assign('membershipFieldID', $field->id);
}
$choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
if ($is_pay_later) {
- $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
+ $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
}
// CRM-6902 - Add "max" option for a price set field
@@ -478,11 +478,11 @@ public static function addQuickFormElement(
}
if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
$choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
- array(
- 'price' => json_encode(array($elementName, '0|0')),
+ [
+ 'price' => json_encode([$elementName, '0|0']),
'data-currency' => $currencyName,
'onclick' => 'clearAmountOther();',
- )
+ ]
);
}
@@ -499,7 +499,7 @@ public static function addQuickFormElement(
}
$choice[] = $qf->createElement('radio', NULL, '', $none, '0',
- array('price' => json_encode(array($elementName, '0')))
+ ['price' => json_encode([$elementName, '0'])]
);
}
@@ -513,12 +513,12 @@ public static function addQuickFormElement(
}
if ($useRequired && $field->is_required) {
- $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
}
break;
case 'Select':
- $selectOption = $allowedOptions = $priceVal = array();
+ $selectOption = $allowedOptions = $priceVal = [];
foreach ($customOption as $opt) {
$taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
@@ -535,7 +535,7 @@ public static function addQuickFormElement(
}
}
- $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
+ $priceVal[$opt['id']] = implode($seperator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
if (!in_array($opt['id'], $freezeOptions)) {
$allowedOptions[] = $opt['id'];
@@ -549,7 +549,7 @@ public static function addQuickFormElement(
$selectOption[$opt['id']] = $opt['label'];
if ($is_pay_later) {
- $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
+ $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
}
}
if (isset($opt['visibility_id'])) {
@@ -559,11 +559,11 @@ public static function addQuickFormElement(
$visibility_id = self::getVisibilityOptionID('public');
}
$element = &$qf->add('select', $elementName, $label,
- array(
+ [
'' => ts('- select -'),
- ) + $selectOption,
+ ] + $selectOption,
$useRequired && $field->is_required,
- array('price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption))
+ ['price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption)]
);
// CRM-6902 - Add "max" option for a price set field
@@ -575,7 +575,7 @@ public static function addQuickFormElement(
case 'CheckBox':
- $check = array();
+ $check = [];
foreach ($customOption as $opId => $opt) {
$taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
$count = CRM_Utils_Array::value('count', $opt, '');
@@ -598,17 +598,17 @@ public static function addQuickFormElement(
}
$opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
}
- $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
+ $priceVal = implode($seperator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
$check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
- array(
- 'price' => json_encode(array($opt['id'], $priceVal)),
+ [
+ 'price' => json_encode([$opt['id'], $priceVal]),
'data-amount' => $opt[$valueFieldName],
'data-currency' => $currencyName,
'visibility' => $opt['visibility_id'],
- )
+ ]
);
if ($is_pay_later) {
- $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], array('size' => '4'));
+ $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
$qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
}
// CRM-6902 - Add "max" option for a price set field
@@ -620,7 +620,7 @@ public static function addQuickFormElement(
}
$element = &$qf->addGroup($check, $elementName, $label);
if ($useRequired && $field->is_required) {
- $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
+ $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
}
break;
}
@@ -645,17 +645,16 @@ public static function addQuickFormElement(
* array of options
*/
public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
- static $options = array();
- if ($reset) {
- $options = array();
+ if ($reset || !isset(Civi::$statics[__CLASS__]['priceOptions'])) {
+ Civi::$statics[__CLASS__]['priceOptions'] = [];
// This would happen if the function was only called to clear the cache.
if (empty($fieldId)) {
- return array();
+ return [];
}
}
- if (empty($options[$fieldId])) {
- $values = array();
+ if (empty(Civi::$statics[__CLASS__]['priceOptions'][$fieldId])) {
+ $values = $options = [];
CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
$options[$fieldId] = $values;
$taxRates = CRM_Core_PseudoConstant::getTaxRates();
@@ -669,9 +668,10 @@ public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FA
$options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
}
}
+ Civi::$statics[__CLASS__]['priceOptions'][$fieldId] = $options[$fieldId];
}
- return $options[$fieldId];
+ return Civi::$statics[__CLASS__]['priceOptions'][$fieldId];
}
/**
@@ -698,10 +698,10 @@ public static function getOptionId($optionLabel, $fid) {
AND option_group.id = option_value.option_group_id
AND option_value.label = %2";
- $dao = CRM_Core_DAO::executeQuery($query, array(
- 1 => array($optionGroupName, 'String'),
- 2 => array($optionLabel, 'String'),
- ));
+ $dao = CRM_Core_DAO::executeQuery($query, [
+ 1 => [$optionGroupName, 'String'],
+ 2 => [$optionLabel, 'String'],
+ ]);
while ($dao->fetch()) {
return $dao->id;
@@ -726,7 +726,7 @@ public static function deleteField($id) {
CRM_Price_BAO_PriceFieldValue::deleteValues($id);
// reorder the weight before delete
- $fieldValues = array('price_set_id' => $field->price_set_id);
+ $fieldValues = ['price_set_id' => $field->price_set_id];
CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
@@ -743,12 +743,12 @@ public static function deleteField($id) {
public static function &htmlTypes() {
static $htmlTypes = NULL;
if (!$htmlTypes) {
- $htmlTypes = array(
+ $htmlTypes = [
'Text' => ts('Text / Numeric Quantity'),
'Select' => ts('Select'),
'Radio' => ts('Radio'),
'CheckBox' => ts('CheckBox'),
- );
+ ];
}
return $htmlTypes;
}
@@ -773,10 +773,10 @@ public static function priceSetValidation($priceSetId, $fields, &$error, $allowN
$priceField->price_set_id = $priceSetId;
$priceField->find();
- $priceFields = array();
+ $priceFields = [];
if ($allowNoneSelection) {
- $noneSelectedPriceFields = array();
+ $noneSelectedPriceFields = [];
}
while ($priceField->fetch()) {
@@ -802,15 +802,15 @@ public static function priceSetValidation($priceSetId, $fields, &$error, $allowN
FROM civicrm_price_field
WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
$fieldDAO = CRM_Core_DAO::executeQuery($sql);
- $htmlTypes = array();
+ $htmlTypes = [];
while ($fieldDAO->fetch()) {
$htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
}
- $selectedAmounts = array();
+ $selectedAmounts = [];
foreach ($htmlTypes as $fieldId => $type) {
- $options = array();
+ $options = [];
CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
if (empty($options)) {
@@ -836,8 +836,17 @@ public static function priceSetValidation($priceSetId, $fields, &$error, $allowN
list($componentName) = explode(':', $fields['_qf_default']);
// now we have all selected amount in hand.
$totalAmount = array_sum($selectedAmounts);
+ // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
+ $totalPaymentAmountEnteredOnForm = CRM_Utils_Array::value('partial_payment_total', $fields, CRM_Utils_Array::value('total_amount', $fields));
if ($totalAmount < 0) {
- $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
+ $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
+ }
+ elseif ($totalAmount > 0 &&
+ // if total amount is equal to all selected amount in hand
+ $totalPaymentAmountEnteredOnForm >= $totalAmount &&
+ (CRM_Utils_Array::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
+ ) {
+ $error['total_amount'] = ts('You have specified the status Partially Paid but have entered an amount that equals or exceeds the amount due. Please adjust the status of the payment or the amount');
}
}
else {
@@ -895,10 +904,10 @@ public static function getVisibilityOptionID($visibilityName) {
self::$visibilityOptionsKeys = CRM_Price_BAO_PriceField::buildOptions(
'visibility_id',
NULL,
- array(
+ [
'labelColumn' => 'name',
'flip' => TRUE,
- )
+ ]
);
}
diff --git a/CRM/Price/BAO/PriceFieldValue.php b/CRM/Price/BAO/PriceFieldValue.php
index 186c4326c895..071d879aa36b 100644
--- a/CRM/Price/BAO/PriceFieldValue.php
+++ b/CRM/Price/BAO/PriceFieldValue.php
@@ -1,9 +1,9 @@
copyValues($params);
@@ -66,7 +66,7 @@ public static function add(&$params, $ids = array()) {
}
if (!empty($params['is_default'])) {
$query = 'UPDATE civicrm_price_field_value SET is_default = 0 WHERE price_field_id = %1';
- $p = array(1 => array($params['price_field_id'], 'Integer'));
+ $p = [1 => [$params['price_field_id'], 'Integer']];
CRM_Core_DAO::executeQuery($query, $p);
}
@@ -86,7 +86,7 @@ public static function add(&$params, $ids = array()) {
*
* @return CRM_Price_DAO_PriceFieldValue
*/
- public static function create(&$params, $ids = array()) {
+ public static function create(&$params, $ids = []) {
$id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('id', $ids));
if (!is_array($params) || empty($params)) {
return NULL;
@@ -104,7 +104,7 @@ public static function create(&$params, $ids = array()) {
if ($id) {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'weight', 'id');
}
- $fieldValues = array('price_field_id' => CRM_Utils_Array::value('price_field_id', $params, 0));
+ $fieldValues = ['price_field_id' => CRM_Utils_Array::value('price_field_id', $params, 0)];
$params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceFieldValue', $oldWeight, $params['weight'], $fieldValues);
}
else {
@@ -132,10 +132,10 @@ public static function create(&$params, $ids = array()) {
* @return array
*/
public static function getDefaults() {
- return array(
+ return [
'is_active' => 1,
'weight' => 1,
- );
+ ];
}
@@ -223,9 +223,8 @@ public static function getOptionLabel($id) {
* @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) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $id, 'is_active', $is_active);
@@ -284,11 +283,11 @@ public static function updateFinancialType($entityId, $entityTable, $financialTy
if (!$entityId || !$entityTable || !$financialTypeID) {
return;
}
- $params = array(
- 1 => array($entityId, 'Integer'),
- 2 => array($entityTable, 'String'),
- 3 => array($financialTypeID, 'Integer'),
- );
+ $params = [
+ 1 => [$entityId, 'Integer'],
+ 2 => [$entityTable, 'String'],
+ 3 => [$financialTypeID, 'Integer'],
+ ];
// for event discount
$join = $where = '';
if ($entityTable == 'civicrm_event') {
@@ -331,10 +330,10 @@ public static function updateAmountAndFeeLevel($id, $prevLabel, $newLabel) {
CRM_Price_BAO_LineItem::create($lineItemParams);
// update amount and fee level in civicrm_contribution and civicrm_participant
- $params = array(
- 1 => array(CRM_Core_DAO::VALUE_SEPARATOR . $prevLabel . ' -', 'String'),
- 2 => array(CRM_Core_DAO::VALUE_SEPARATOR . $newLabel . ' -', 'String'),
- );
+ $params = [
+ 1 => [CRM_Core_DAO::VALUE_SEPARATOR . $prevLabel . ' -', 'String'],
+ 2 => [CRM_Core_DAO::VALUE_SEPARATOR . $newLabel . ' -', 'String'],
+ ];
// Update contribution
if (!empty($lineItem->contribution_id)) {
CRM_Core_DAO::executeQuery("UPDATE `civicrm_contribution` SET `amount_level` = REPLACE(amount_level, %1, %2) WHERE id = {$lineItem->contribution_id}", $params);
diff --git a/CRM/Price/BAO/PriceSet.php b/CRM/Price/BAO/PriceSet.php
index e1dabf52027e..69e1f7fcd69f 100644
--- a/CRM/Price/BAO/PriceSet.php
+++ b/CRM/Price/BAO/PriceSet.php
@@ -1,9 +1,9 @@
fetch()) {
- self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
+ self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = [
'setID' => $dao->setID,
'priceFieldID' => $dao->priceFieldID,
'name' => $dao->name,
@@ -153,7 +151,7 @@ public static function getDefaultPriceSet($entity = 'contribution') {
'membership_type_id' => $dao->membership_type_id,
'amount' => $dao->amount,
'financial_type_id' => $dao->financial_type_id,
- );
+ ];
}
return self::$_defaultPriceSet[$entity];
@@ -183,7 +181,7 @@ public static function getTitle($id) {
* @return array
*/
public static function getUsedBy($id, $simpleReturn = FALSE) {
- $usedBy = array();
+ $usedBy = [];
$forms = self::getFormsUsingPriceSet($id);
$tables = array_keys($forms);
// @todo - this is really clumsy overloading the signature like this. Instead
@@ -199,7 +197,7 @@ public static function getUsedBy($id, $simpleReturn = FALSE) {
FROM civicrm_line_item cli
LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
WHERE cpf.price_set_id = %1";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
while ($crmFormDAO->fetch()) {
$forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
@@ -315,13 +313,13 @@ public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuick
if ($isQuickConfig) {
$sql .= ' AND ps.is_quick_config = 0 ';
}
- $params = array(
- 1 => array($entityTable, 'String'),
- 2 => array($entityId, 'Integer'),
- );
+ $params = [
+ 1 => [$entityTable, 'String'],
+ 2 => [$entityId, 'Integer'],
+ ];
if ($usedFor) {
$sql .= " AND ps.extends LIKE '%%3%' ";
- $params[3] = array($usedFor, 'Integer');
+ $params[3] = [$usedFor, 'Integer'];
}
$dao = CRM_Core_DAO::executeQuery($sql, $params);
@@ -392,7 +390,7 @@ public static function getAssoc($withInactive = FALSE, $extendComponentName = FA
$query .= ' AND s.domain_id = ' . CRM_Core_Config::domainID();
}
- $priceSets = array();
+ $priceSets = [];
if ($extendComponentName) {
$componentId = CRM_Core_Component::getComponentID($extendComponentName);
@@ -436,9 +434,9 @@ public static function getAssoc($withInactive = FALSE, $extendComponentName = FA
*/
public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
// create a new tree
- $setTree = array();
+ $setTree = [];
- $priceFields = array(
+ $priceFields = [
'id',
'name',
'label',
@@ -455,7 +453,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
'javascript',
'visibility_id',
'is_required',
- );
+ ];
if ($required == TRUE) {
$priceFields[] = 'is_required';
}
@@ -464,9 +462,9 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
$select = 'SELECT ' . implode(',', $priceFields);
$from = ' FROM civicrm_price_field';
- $params = array(
- 1 => array($setID, 'Integer'),
- );
+ $params = [
+ 1 => [$setID, 'Integer'],
+ ];
$currentTime = date('YmdHis');
$where = "
WHERE price_set_id = %1
@@ -495,7 +493,7 @@ public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE
while ($dao->fetch()) {
$fieldID = $dao->id;
- $setTree[$setID]['fields'][$fieldID] = array();
+ $setTree[$setID]['fields'][$fieldID] = [];
$setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
foreach ($priceFields as $field) {
@@ -561,7 +559,6 @@ public static function getOnlyPriceFieldValueID(array $priceSet) {
return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
}
-
/**
* Initiate price set such that various non-BAO things are set on the form.
*
@@ -630,7 +627,7 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
//get option count info.
$form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
if ($form->_priceSet['optionsCountTotal']) {
- $optionsCountDetails = array();
+ $optionsCountDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
foreach ($field['options'] as $option) {
@@ -644,7 +641,7 @@ public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $val
//get option max value info.
$optionsMaxValueTotal = 0;
- $optionsMaxValueDetails = array();
+ $optionsMaxValueDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
@@ -698,13 +695,13 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
$amount_override = NULL;
if ($component) {
- $autoRenew = array();
+ $autoRenew = [];
$autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
}
if ($priceSetID) {
$priceFields = self::filterPriceFieldsFromParams($priceSetID, $params);
- if (count($priceFields) == 1 && !empty($params['total_amount'])) {
- $amount_override = $params['total_amount'];
+ if (count($priceFields) == 1) {
+ $amount_override = CRM_Utils_Array::value('partial_payment_total', $params, CRM_Utils_Array::value('total_amount', $params));
}
}
foreach ($fields as $id => $field) {
@@ -718,8 +715,8 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
switch ($field['html_type']) {
case 'Text':
$firstOption = reset($field['options']);
- $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
- CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
+ $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
$optionValueId = key($field['options']);
if (CRM_Utils_Array::value('name', $field['options'][$optionValueId]) == 'contribution_amount') {
@@ -739,15 +736,15 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
case 'Radio':
//special case if user select -none-
if ($params["price_{$id}"] <= 0) {
- continue;
+ break;
}
- $params["price_{$id}"] = array($params["price_{$id}"] => 1);
+ $params["price_{$id}"] = [$params["price_{$id}"] => 1];
$optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, $amount_override);
if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
$lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
- if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
+ if ($amount_override) {
$lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
}
}
@@ -764,10 +761,10 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
break;
case 'Select':
- $params["price_{$id}"] = array($params["price_{$id}"] => 1);
+ $params["price_{$id}"] = [$params["price_{$id}"] => 1];
$optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
- CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
$lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
}
@@ -783,7 +780,7 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
case 'CheckBox':
- CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
+ CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, CRM_Utils_Array::value('partial_payment_total', $params));
foreach ($params["price_{$id}"] as $optionId => $option) {
if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
$lineItem = self::setLineItem($field, $lineItem, $optionId, $totalTax);
@@ -801,7 +798,7 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
}
}
- $amount_level = array();
+ $amount_level = [];
$totalParticipant = 0;
if (is_array($lineItem)) {
foreach ($lineItem as $values) {
@@ -838,9 +835,8 @@ public static function processAmount($fields, &$params, &$lineItem, $component =
$params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
}
}
- // @todo this was a fix for CRM-16460 but is too deep in the system for formatting
- // and probably causes negative amounts to save as $0 depending on server config.
- $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
+
+ $params['amount'] = $totalPrice;
$params['tax_amount'] = $totalTax;
if ($component) {
foreach ($autoRenew as $dontCare => $eachAmount) {
@@ -872,7 +868,7 @@ public static function getAmountLevelText($params) {
$priceFieldMetadata = self::getCachedPriceSetDetail($priceSetID);
$displayParticipantCount = NULL;
- $amount_level = array();
+ $amount_level = [];
foreach ($priceFieldMetadata['fields'] as $field) {
if (!empty($priceFieldSelection[$field['id']])) {
$qtyString = '';
@@ -903,7 +899,7 @@ public static function getAmountLevelText($params) {
*/
public static function filterPriceFieldsFromParams($priceSetID, $params) {
$priceSet = self::getCachedPriceSetDetail($priceSetID);
- $return = array();
+ $return = [];
foreach ($priceSet['fields'] as $field) {
if (!empty($params['price_' . $field['id']])) {
$return[$field['id']] = $params['price_' . $field['id']];
@@ -954,10 +950,10 @@ public static function buildPriceSet(&$form) {
$validFieldsOnly = TRUE;
$className = CRM_Utils_System::getClassName($form);
- if (in_array($className, array(
+ if (in_array($className, [
'CRM_Contribute_Form_Contribution',
'CRM_Member_Form_Membership',
- ))) {
+ ])) {
$validFieldsOnly = FALSE;
}
@@ -976,7 +972,7 @@ public static function buildPriceSet(&$form) {
// Mark which field should have the auto-renew checkbox, if any. CRM-18305
if (!empty($form->_membershipTypeValues) && is_array($form->_membershipTypeValues)) {
- $autoRenewMembershipTypes = array();
+ $autoRenewMembershipTypes = [];
foreach ($form->_membershipTypeValues as $membershiptTypeValue) {
if ($membershiptTypeValue['auto_renew']) {
$autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
@@ -1052,7 +1048,7 @@ public static function buildPriceSet(&$form) {
}
}
- $formClasses = array('CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership');
+ $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
continue;
@@ -1091,7 +1087,7 @@ public static function checkCurrentMembership(&$options, $userid) {
if (!$userid || empty($options)) {
return FALSE;
}
- static $_contact_memberships = array();
+ static $_contact_memberships = [];
$checkLifetime = FALSE;
foreach ($options as $key => $value) {
if (!empty($value['membership_type_id'])) {
@@ -1255,27 +1251,27 @@ public static function getFieldIds($id) {
*/
public static function copy($id) {
$maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
- $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $id));
+ $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
$newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
- $title = ts('[Copy id %1]', array(1 => $maxId + 1));
- $fieldsFix = array(
- 'replace' => array(
+ $title = ts('[Copy id %1]', [1 => $maxId + 1]);
+ $fieldsFix = [
+ 'replace' => [
'title' => trim($newTitle) . ' ' . $title,
'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId + 1),
- ),
- );
+ ],
+ ];
$copy = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
- array('id' => $id),
+ ['id' => $id],
NULL,
$fieldsFix
);
//copying all the blocks pertaining to the price set
$copyPriceField = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
- array('price_set_id' => $id),
- array('price_set_id' => $copy->id)
+ ['price_set_id' => $id],
+ ['price_set_id' => $copy->id]
);
if (!empty($copyPriceField)) {
$price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
@@ -1283,8 +1279,8 @@ public static function copy($id) {
//copy option group and values
foreach ($price as $originalId => $copyId) {
CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
- array('price_field_id' => $originalId),
- array('price_field_id' => $copyId)
+ ['price_field_id' => $originalId],
+ ['price_field_id' => $copyId]
);
}
}
@@ -1334,7 +1330,7 @@ public static function getPricesetCount($sid, $onlyActive = TRUE) {
$where = 'AND value.is_active = 1 AND field.is_active = 1';
}
- static $pricesetFieldCount = array();
+ static $pricesetFieldCount = [];
if (!isset($pricesetFieldCount[$sid])) {
$sql = "
SELECT sum(value.count) as totalCount
@@ -1344,7 +1340,7 @@ public static function getPricesetCount($sid, $onlyActive = TRUE) {
WHERE pset.id = %1
$where";
- $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
+ $count = CRM_Core_DAO::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
$pricesetFieldCount[$sid] = ($count) ? $count : 0;
}
@@ -1365,7 +1361,7 @@ public static function getMembershipCount($ids) {
GROUP BY mt.member_of_contact_id ";
$crmDAO = CRM_Core_DAO::executeQuery($queryString);
- $count = array();
+ $count = [];
while ($crmDAO->fetch()) {
$count[$crmDAO->id] = $crmDAO->count;
@@ -1399,7 +1395,7 @@ public static function checkAutoRenewForPriceSet($priceSetId) {
AND pfv.is_active = 1
ORDER BY price_field_id';
- $params = array(1 => array($priceSetId, 'Integer'));
+ $params = [1 => [$priceSetId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
@@ -1410,7 +1406,7 @@ public static function checkAutoRenewForPriceSet($priceSetId) {
}
$autoRenewOption = 2;
- $priceFields = array();
+ $priceFields = [];
while ($dao->fetch()) {
if (!$dao->auto_renew) {
// If any one can't be renewed none can.
@@ -1453,10 +1449,10 @@ public static function getRecurDetails($priceSetId) {
INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
WHERE pf.price_set_id = %1 LIMIT 1';
- $params = array(1 => array($priceSetId, 'Integer'));
+ $params = [1 => [$priceSetId, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$dao->fetch();
- return array($dao->duration_interval, $dao->duration_unit);
+ return [$dao->duration_interval, $dao->duration_unit];
}
/**
@@ -1474,8 +1470,8 @@ public static function eventPriceSetDomainID() {
* @param bool $isQuickConfig we want to set the is_quick_config field.
* Value we want to set the is_quick_config field.
*
- * @return Object
- * DAO object on success, null otherwise
+ * @return bool
+ * true if we found and updated the object, else false
*/
public static function setIsQuickConfig($id, $isQuickConfig) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
@@ -1514,15 +1510,15 @@ public static function getMembershipTypesFromPriceSet($id) {
WHERE ps.id = %1
";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
- $membershipTypes = array(
- 'all' => array(),
- 'autorenew' => array(),
- 'autorenew_required' => array(),
- 'autorenew_optional' => array(),
- );
+ $membershipTypes = [
+ 'all' => [],
+ 'autorenew' => [],
+ 'autorenew_required' => [],
+ 'autorenew_optional' => [],
+ ];
while ($dao->fetch()) {
if (empty($dao->membership_type_id)) {
continue;
@@ -1563,12 +1559,12 @@ public static function copyPriceSet($baoName, $id, $newId) {
CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
}
else {
- $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
- array(
+ $copyPriceSet = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
+ [
'entity_id' => $id,
'entity_table' => $baoName,
- ),
- array('entity_id' => $newId)
+ ],
+ ['entity_id' => $newId]
);
}
// copy event discount
@@ -1580,13 +1576,13 @@ public static function copyPriceSet($baoName, $id, $newId) {
CRM_Core_DAO::copyGeneric(
'CRM_Core_DAO_Discount',
- array(
+ [
'id' => $discountId,
- ),
- array(
+ ],
+ [
'entity_id' => $newId,
'price_set_id' => $copyPriceSet->id,
- )
+ ]
);
}
}
@@ -1643,7 +1639,7 @@ public static function parseFirstPriceSetValueIDFromParams($params) {
*/
public static function parsePriceSetValueIDsFromParams($params) {
$priceSetParams = self::parsePriceSetArrayFromParams($params);
- $priceSetValueIDs = array();
+ $priceSetValueIDs = [];
foreach ($priceSetParams as $priceSetParam) {
foreach (array_keys($priceSetParam) as $priceValueID) {
$priceSetValueIDs[] = $priceValueID;
@@ -1661,7 +1657,7 @@ public static function parsePriceSetValueIDsFromParams($params) {
* Array of price fields filtered from the params.
*/
public static function parsePriceSetArrayFromParams($params) {
- $priceSetParams = array();
+ $priceSetParams = [];
foreach ($params as $field => $value) {
$parts = explode('_', $field);
if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
@@ -1705,12 +1701,12 @@ public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem
* )
*/
public static function getFormsUsingPriceSet($id) {
- $forms = array();
+ $forms = [];
$queryString = "
SELECT entity_table, entity_id
FROM civicrm_price_set_entity
WHERE price_set_id = %1";
- $params = array(1 => array($id, 'Integer'));
+ $params = [1 => [$id, 'Integer']];
$crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
while ($crmFormDAO->fetch()) {
@@ -1736,7 +1732,7 @@ public static function getFormsUsingPriceSet($id) {
* @throws \Exception
*/
protected static function reformatUsedByFormsWithEntityData($forms) {
- $usedBy = array();
+ $usedBy = [];
foreach ($forms as $table => $entities) {
switch ($table) {
case 'civicrm_event':
diff --git a/CRM/Price/DAO/LineItem.php b/CRM/Price/DAO/LineItem.php
index 2f05c853d160..8d7ae16d2961 100644
--- a/CRM/Price/DAO/LineItem.php
+++ b/CRM/Price/DAO/LineItem.php
@@ -1,416 +1,429 @@
__table = 'civicrm_line_item';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_field_id', 'civicrm_price_field', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_field_value_id', 'civicrm_price_field_value', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'contribution_id', 'civicrm_contribution', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_field_id', 'civicrm_price_field', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_field_value_id', 'civicrm_price_field_value', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item ID') ,
- 'description' => 'Line Item',
- 'required' => true,
+ 'title' => ts('Line Item ID'),
+ 'description' => ts('Line Item'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_line_item.id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Line Item Entity Type') ,
- 'description' => 'table which has the transaction',
- 'required' => true,
+ 'title' => ts('Line Item Entity Type'),
+ 'description' => ts('table which has the transaction'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_line_item.entity_table',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Entity') ,
- 'description' => 'entry in table',
- 'required' => true,
+ 'title' => ts('Line Item Entity'),
+ 'description' => ts('entry in table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_line_item.entity_id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'contribution_id' => array(
+ ],
+ 'contribution_id' => [
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Contribution') ,
- 'description' => 'FK to civicrm_contribution',
+ 'title' => ts('Line Item Contribution'),
+ 'description' => ts('FK to civicrm_contribution'),
+ 'where' => 'civicrm_line_item.contribution_id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
- ) ,
- 'price_field_id' => array(
+ ],
+ 'price_field_id' => [
'name' => 'price_field_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Price Field') ,
- 'description' => 'FK to civicrm_price_field',
+ 'title' => ts('Line Item Price Field'),
+ 'description' => ts('FK to civicrm_price_field'),
+ 'where' => 'civicrm_line_item.price_field_id',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceField',
- ) ,
- 'label' => array(
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Line Item Label') ,
- 'description' => 'descriptive label for item - from price_field_value.label',
+ 'title' => ts('Line Item Label'),
+ 'description' => ts('descriptive label for item - from price_field_value.label'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_line_item.label',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'qty' => array(
+ ],
+ ],
+ 'qty' => [
'name' => 'qty',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Line Item Quantity') ,
- 'description' => 'How many items ordered',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Line Item Quantity'),
+ 'description' => ts('How many items ordered'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_line_item.qty',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'unit_price' => array(
+ ],
+ ],
+ 'unit_price' => [
'name' => 'unit_price',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Unit Price') ,
- 'description' => 'price of each item',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Unit Price'),
+ 'description' => ts('price of each item'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_line_item.unit_price',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'line_total' => array(
+ ],
+ ],
+ 'line_total' => [
'name' => 'line_total',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Line Item Total') ,
- 'description' => 'qty * unit_price',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Line Item Total'),
+ 'description' => ts('qty * unit_price'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_line_item.line_total',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- ) ,
- 'participant_count' => array(
+ ],
+ 'participant_count' => [
'name' => 'participant_count',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Participant Count') ,
- 'description' => 'Participant count for field',
+ 'title' => ts('Line Item Participant Count'),
+ 'description' => ts('Participant count for field'),
+ 'where' => 'civicrm_line_item.participant_count',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'price_field_value_id' => array(
+ ],
+ ],
+ 'price_field_value_id' => [
'name' => 'price_field_value_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Line Item Option') ,
- 'description' => 'FK to civicrm_price_field_value',
+ 'title' => ts('Line Item Option'),
+ 'description' => ts('FK to civicrm_price_field_value'),
+ 'where' => 'civicrm_line_item.price_field_value_id',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceFieldValue',
- ) ,
- 'financial_type_id' => array(
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type.'),
+ 'where' => 'civicrm_line_item.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'non_deductible_amount' => array(
+ ]
+ ],
+ 'non_deductible_amount' => [
'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Non-deductible Amount') ,
- 'description' => 'Portion of total amount which is NOT tax deductible.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Non-deductible Amount'),
+ 'description' => ts('Portion of total amount which is NOT tax deductible.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_line_item.non_deductible_amount',
+ 'headerPattern' => '/non?.?deduct/i',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
'default' => '0.0',
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'tax_amount' => array(
+ ],
+ ],
+ 'tax_amount' => [
'name' => 'tax_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Tax Amount') ,
- 'description' => 'tax of each item',
- 'precision' => array(
+ 'title' => ts('Tax Amount'),
+ 'description' => ts('tax of each item'),
+ 'precision' => [
20,
2
- ) ,
- 'import' => true,
+ ],
+ 'import' => TRUE,
'where' => 'civicrm_line_item.tax_amount',
'headerPattern' => '/tax(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
- 'export' => true,
+ 'export' => TRUE,
'table_name' => 'civicrm_line_item',
'entity' => 'LineItem',
'bao' => 'CRM_Price_BAO_LineItem',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -418,10 +431,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'line_item', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'line_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -429,38 +443,44 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'line_item', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'line_item', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_entity' => array(
+ $indices = [
+ 'index_entity' => [
'name' => 'index_entity',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_line_item::0::entity_table::entity_id',
- ) ,
- 'UI_line_item_value' => array(
+ ],
+ 'UI_line_item_value' => [
'name' => 'UI_line_item_value',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
2 => 'contribution_id',
3 => 'price_field_value_id',
4 => 'price_field_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_line_item::1::entity_table::entity_id::contribution_id::price_field_value_id::price_field_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceField.php b/CRM/Price/DAO/PriceField.php
index b9af981d7956..8f825a193812 100644
--- a/CRM/Price/DAO/PriceField.php
+++ b/CRM/Price/DAO/PriceField.php
@@ -1,465 +1,485 @@
1)
*
* @var boolean
*/
public $is_required;
+
/**
* If non-zero, do not show this field before the date specified
*
* @var datetime
*/
public $active_on;
+
/**
* If non-zero, do not show this field after the date specified
*
* @var datetime
*/
public $expire_on;
+
/**
* Optional scripting attributes for field
*
* @var string
*/
public $javascript;
+
/**
* Implicit FK to civicrm_option_group with name = 'visibility'
*
* @var int unsigned
*/
public $visibility_id;
+
/**
* Class constructor.
*/
- function __construct() {
+ public function __construct() {
$this->__table = 'civicrm_price_field';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_set_id', 'civicrm_price_set', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_set_id', 'civicrm_price_set', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field ID') ,
- 'description' => 'Price Field',
- 'required' => true,
+ 'title' => ts('Price Field ID'),
+ 'description' => ts('Price Field'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field.id',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- ) ,
- 'price_set_id' => array(
+ ],
+ 'price_set_id' => [
'name' => 'price_set_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set') ,
- 'description' => 'FK to civicrm_price_set',
- 'required' => true,
+ 'title' => ts('Price Set'),
+ 'description' => ts('FK to civicrm_price_set'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field.price_set_id',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceSet',
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Variable name/programmatic handle for this field.',
- 'required' => true,
+ 'title' => ts('Name'),
+ 'description' => ts('Variable name/programmatic handle for this field.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field.name',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'label' => array(
+ ],
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label') ,
- 'description' => 'Text for form field label (also friendly name for administering this field).',
- 'required' => true,
+ 'title' => ts('Label'),
+ 'description' => ts('Text for form field label (also friendly name for administering this field).'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field.label',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'html_type' => array(
+ ],
+ ],
+ 'html_type' => [
'name' => 'html_type',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Html Type') ,
- 'required' => true,
+ 'title' => ts('Html Type'),
+ 'required' => TRUE,
'maxlength' => 12,
'size' => CRM_Utils_Type::TWELVE,
+ 'where' => 'civicrm_price_field.html_type',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'callback' => 'CRM_Price_BAO_PriceField::htmlTypes',
- )
- ) ,
- 'is_enter_qty' => array(
+ ]
+ ],
+ 'is_enter_qty' => [
'name' => 'is_enter_qty',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Quantity Required?') ,
- 'description' => 'Enter a quantity for this field?',
+ 'title' => ts('Price Field Quantity Required?'),
+ 'description' => ts('Enter a quantity for this field?'),
+ 'where' => 'civicrm_price_field.is_enter_qty',
+ 'default' => '0',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'help_pre' => array(
+ ],
+ ],
+ 'help_pre' => [
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Field Pre Text') ,
- 'description' => 'Description and/or help text to display before this field.',
+ 'title' => ts('Price Field Pre Text'),
+ 'description' => ts('Description and/or help text to display before this field.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_field.help_pre',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_post' => array(
+ ],
+ ],
+ 'help_post' => [
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Field Post Text') ,
- 'description' => 'Description and/or help text to display after this field.',
+ 'title' => ts('Price Field Post Text'),
+ 'description' => ts('Description and/or help text to display after this field.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_field.help_post',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'Order in which the fields should appear',
+ 'title' => ts('Order'),
+ 'description' => ts('Order in which the fields should appear'),
+ 'where' => 'civicrm_price_field.weight',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'is_display_amounts' => array(
+ ],
+ ],
+ 'is_display_amounts' => [
'name' => 'is_display_amounts',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Show Amounts?') ,
- 'description' => 'Should the price be displayed next to the label for each option?',
+ 'title' => ts('Price Field Show Amounts?'),
+ 'description' => ts('Should the price be displayed next to the label for each option?'),
+ 'where' => 'civicrm_price_field.is_display_amounts',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'options_per_line' => array(
+ ],
+ ],
+ 'options_per_line' => [
'name' => 'options_per_line',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Options per Row') ,
- 'description' => 'number of options per line for checkbox and radio',
+ 'title' => ts('Price Field Options per Row'),
+ 'description' => ts('number of options per line for checkbox and radio'),
+ 'where' => 'civicrm_price_field.options_per_line',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Is Active?') ,
- 'description' => 'Is this price field active',
+ 'title' => ts('Price Field Is Active?'),
+ 'description' => ts('Is this price field active'),
+ 'where' => 'civicrm_price_field.is_active',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_required' => array(
+ ],
+ ],
+ 'is_required' => [
'name' => 'is_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field is Required?') ,
- 'description' => 'Is this price field required (value must be > 1)',
+ 'title' => ts('Price Field is Required?'),
+ 'description' => ts('Is this price field required (value must be > 1)'),
+ 'where' => 'civicrm_price_field.is_required',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'active_on' => array(
+ ],
+ ],
+ 'active_on' => [
'name' => 'active_on',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Price Field Start Date') ,
- 'description' => 'If non-zero, do not show this field before the date specified',
+ 'title' => ts('Price Field Start Date'),
+ 'description' => ts('If non-zero, do not show this field before the date specified'),
+ 'where' => 'civicrm_price_field.active_on',
'default' => 'NULL',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
- 'type' => 'CheckBox',
- ) ,
- ) ,
- 'expire_on' => array(
+ 'html' => [
+ 'type' => 'Select Date',
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'expire_on' => [
'name' => 'expire_on',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
- 'title' => ts('Price Field End Date') ,
- 'description' => 'If non-zero, do not show this field after the date specified',
+ 'title' => ts('Price Field End Date'),
+ 'description' => ts('If non-zero, do not show this field after the date specified'),
+ 'where' => 'civicrm_price_field.expire_on',
'default' => 'NULL',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select Date',
- ) ,
- ) ,
- 'javascript' => array(
+ 'formatType' => 'activityDateTime',
+ ],
+ ],
+ 'javascript' => [
'name' => 'javascript',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Field Javascript') ,
- 'description' => 'Optional scripting attributes for field',
+ 'title' => ts('Price Field Javascript'),
+ 'description' => ts('Optional scripting attributes for field'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field.javascript',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'visibility_id' => array(
+ ],
+ ],
+ 'visibility_id' => [
'name' => 'visibility_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Visibility') ,
- 'description' => 'Implicit FK to civicrm_option_group with name = \'visibility\'',
+ 'title' => ts('Price Field Visibility'),
+ 'description' => ts('Implicit FK to civicrm_option_group with name = \'visibility\''),
+ 'where' => 'civicrm_price_field.visibility_id',
'default' => '1',
'table_name' => 'civicrm_price_field',
'entity' => 'PriceField',
'bao' => 'CRM_Price_BAO_PriceField',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'visibility',
'optionEditPath' => 'civicrm/admin/options/visibility',
- )
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -467,10 +487,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -478,24 +499,30 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'index_name' => array(
+ $indices = [
+ 'index_name' => [
'name' => 'index_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
+ ],
+ 'localizable' => FALSE,
'sig' => 'civicrm_price_field::0::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceFieldValue.php b/CRM/Price/DAO/PriceFieldValue.php
index c51f08380cdc..bd6f7daa2001 100644
--- a/CRM/Price/DAO/PriceFieldValue.php
+++ b/CRM/Price/DAO/PriceFieldValue.php
@@ -1,496 +1,521 @@
Price field option description.
+ * Price field option description.
*
* @var text
*/
public $description;
+
/**
* Price field option pre help text.
*
* @var text
*/
public $help_pre;
+
/**
* Price field option post field help.
*
* @var text
*/
public $help_post;
+
/**
* Price field option amount
*
- * @var string
+ * @var float
*/
public $amount;
+
/**
* Number of participants per field option
*
* @var int unsigned
*/
public $count;
+
/**
* Max number of participants per field options
*
* @var int unsigned
*/
public $max_value;
+
/**
* Order in which the field options should appear
*
* @var int
*/
public $weight;
+
/**
* FK to Membership Type
*
* @var int unsigned
*/
public $membership_type_id;
+
/**
* Number of terms for this membership
*
* @var int unsigned
*/
public $membership_num_terms;
+
/**
* Is this default price field option
*
* @var boolean
*/
public $is_default;
+
/**
* Is this price field value active
*
* @var boolean
*/
public $is_active;
+
/**
* FK to Financial Type.
*
* @var int unsigned
*/
public $financial_type_id;
+
/**
* Portion of total amount which is NOT tax deductible.
*
* @var float
*/
public $non_deductible_amount;
+
/**
- * Implicit FK to civicrm_option_group with name = \'visibility\'
+ * Implicit FK to civicrm_option_group with name = 'visibility'
*
* @var int unsigned
*/
public $visibility_id;
+
/**
* Class constructor.
*/
- function __construct() {
+ public function __construct() {
$this->__table = 'civicrm_price_field_value';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_field_id', 'civicrm_price_field', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'membership_type_id', 'civicrm_membership_type', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_field_id', 'civicrm_price_field', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'membership_type_id', 'civicrm_membership_type', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Value ID') ,
- 'description' => 'Price Field Value',
- 'required' => true,
+ 'title' => ts('Price Field Value ID'),
+ 'description' => ts('Price Field Value'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field_value.id',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- ) ,
- 'price_field_id' => array(
+ ],
+ 'price_field_id' => [
'name' => 'price_field_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field') ,
- 'description' => 'FK to civicrm_price_field',
- 'required' => true,
+ 'title' => ts('Price Field'),
+ 'description' => ts('FK to civicrm_price_field'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_field_value.price_field_id',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceField',
- ) ,
- 'name' => array(
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Price field option name',
+ 'title' => ts('Name'),
+ 'description' => ts('Price field option name'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field_value.name',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'label' => array(
+ ],
+ ],
+ 'label' => [
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Label') ,
- 'description' => 'Price field option label',
+ 'title' => ts('Label'),
+ 'description' => ts('Price field option label'),
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_field_value.label',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'description' => array(
+ ],
+ ],
+ 'description' => [
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Description') ,
- 'description' => '>Price field option description.',
+ 'title' => ts('Description'),
+ 'description' => ts('Price field option description.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_price_field_value.description',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_pre' => array(
+ ],
+ ],
+ 'help_pre' => [
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Help Pre') ,
- 'description' => 'Price field option pre help text.',
+ 'title' => ts('Help Pre'),
+ 'description' => ts('Price field option pre help text.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_price_field_value.help_pre',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_post' => array(
+ ],
+ ],
+ 'help_post' => [
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Help Post') ,
- 'description' => 'Price field option post field help.',
+ 'title' => ts('Help Post'),
+ 'description' => ts('Price field option post field help.'),
'rows' => 2,
'cols' => 60,
+ 'where' => 'civicrm_price_field_value.help_post',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'amount' => array(
+ ],
+ ],
+ 'amount' => [
'name' => 'amount',
- 'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Amount') ,
- 'description' => 'Price field option amount',
- 'required' => true,
- 'maxlength' => 512,
- 'size' => 8,
+ 'type' => CRM_Utils_Type::T_MONEY,
+ 'title' => ts('Amount'),
+ 'description' => ts('Price field option amount'),
+ 'required' => TRUE,
+ 'precision' => [
+ 18,
+ 9
+ ],
+ 'where' => 'civicrm_price_field_value.amount',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'count' => array(
+ ],
+ ],
+ 'count' => [
'name' => 'count',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Count') ,
- 'description' => 'Number of participants per field option',
+ 'title' => ts('Count'),
+ 'description' => ts('Number of participants per field option'),
+ 'where' => 'civicrm_price_field_value.count',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'max_value' => array(
+ ],
+ ],
+ 'max_value' => [
'name' => 'max_value',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Max Value') ,
- 'description' => 'Max number of participants per field options',
+ 'title' => ts('Max Value'),
+ 'description' => ts('Max number of participants per field options'),
+ 'where' => 'civicrm_price_field_value.max_value',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'weight' => array(
+ ],
+ ],
+ 'weight' => [
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Order') ,
- 'description' => 'Order in which the field options should appear',
+ 'title' => ts('Order'),
+ 'description' => ts('Order in which the field options should appear'),
+ 'where' => 'civicrm_price_field_value.weight',
'default' => '1',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'membership_type_id' => array(
+ ],
+ ],
+ 'membership_type_id' => [
'name' => 'membership_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Type') ,
- 'description' => 'FK to Membership Type',
+ 'title' => ts('Membership Type'),
+ 'description' => ts('FK to Membership Type'),
+ 'where' => 'civicrm_price_field_value.membership_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
'FKClassName' => 'CRM_Member_DAO_MembershipType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- ) ,
- 'membership_num_terms' => array(
+ ],
+ ],
+ 'membership_num_terms' => [
'name' => 'membership_num_terms',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Membership Num Terms') ,
- 'description' => 'Number of terms for this membership',
+ 'title' => ts('Membership Num Terms'),
+ 'description' => ts('Number of terms for this membership'),
+ 'where' => 'civicrm_price_field_value.membership_num_terms',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_default' => array(
+ ],
+ ],
+ 'is_default' => [
'name' => 'is_default',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Default Price Field Option?') ,
- 'description' => 'Is this default price field option',
+ 'title' => ts('Is Default Price Field Option?'),
+ 'description' => ts('Is this default price field option'),
+ 'where' => 'civicrm_price_field_value.is_default',
+ 'default' => '0',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Field Value is Active') ,
- 'description' => 'Is this price field value active',
+ 'title' => ts('Price Field Value is Active'),
+ 'description' => ts('Is this price field value active'),
+ 'where' => 'civicrm_price_field_value.is_active',
'default' => '1',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- ) ,
- 'financial_type_id' => array(
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type.',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type.'),
+ 'where' => 'civicrm_price_field_value.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'non_deductible_amount' => array(
+ ]
+ ],
+ 'non_deductible_amount' => [
'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
- 'title' => ts('Non-deductible Amount') ,
- 'description' => 'Portion of total amount which is NOT tax deductible.',
- 'required' => true,
- 'precision' => array(
+ 'title' => ts('Non-deductible Amount'),
+ 'description' => ts('Portion of total amount which is NOT tax deductible.'),
+ 'required' => TRUE,
+ 'precision' => [
20,
2
- ) ,
+ ],
+ 'where' => 'civicrm_price_field_value.non_deductible_amount',
+ 'headerPattern' => '/non?.?deduct/i',
+ 'dataPattern' => '/^\d+(\.\d{2})?$/',
'default' => '0.0',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'visibility_id' => array(
+ ],
+ ],
+ 'visibility_id' => [
'name' => 'visibility_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Field Option Visibility') ,
- 'description' => 'Implicit FK to civicrm_option_group with name = \'visibility\'',
+ 'title' => ts('Price Field Option Visibility'),
+ 'description' => ts('Implicit FK to civicrm_option_group with name = \'visibility\''),
+ 'where' => 'civicrm_price_field_value.visibility_id',
'default' => '1',
'table_name' => 'civicrm_price_field_value',
'entity' => 'PriceFieldValue',
'bao' => 'CRM_Price_BAO_PriceFieldValue',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'optionGroupName' => 'visibility',
'optionEditPath' => 'civicrm/admin/options/visibility',
- ),
- ) ,
- );
+ ]
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -498,10 +523,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field_value', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_field_value', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -509,15 +535,21 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field_value', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_field_value', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array();
+ $indices = [];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceSet.php b/CRM/Price/DAO/PriceSet.php
index e310a831a87c..ae2e04ef8ea4 100644
--- a/CRM/Price/DAO/PriceSet.php
+++ b/CRM/Price/DAO/PriceSet.php
@@ -1,397 +1,410 @@
__table = 'civicrm_price_set';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'domain_id', 'civicrm_domain', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'domain_id', 'civicrm_domain', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'financial_type_id', 'civicrm_financial_type', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set ID') ,
- 'description' => 'Price Set',
- 'required' => true,
+ 'title' => ts('Price Set ID'),
+ 'description' => ts('Price Set'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set.id',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- ) ,
- 'domain_id' => array(
+ ],
+ 'domain_id' => [
'name' => 'domain_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set Domain') ,
- 'description' => 'Which Domain is this price-set for',
+ 'title' => ts('Price Set Domain'),
+ 'description' => ts('Which Domain is this price-set for'),
+ 'where' => 'civicrm_price_set.domain_id',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Domain',
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_domain',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'name' => array(
+ ]
+ ],
+ 'name' => [
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Name') ,
- 'description' => 'Variable name/programmatic handle for this set of price fields.',
- 'required' => true,
+ 'title' => ts('Name'),
+ 'description' => ts('Variable name/programmatic handle for this set of price fields.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_set.name',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'title' => array(
+ ],
+ ],
+ 'title' => [
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Set Title') ,
- 'description' => 'Displayed title for the Price Set.',
- 'required' => true,
+ 'title' => ts('Price Set Title'),
+ 'description' => ts('Displayed title for the Price Set.'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_set.title',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'is_active' => array(
+ ],
+ ],
+ 'is_active' => [
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Set Is Active?') ,
- 'description' => 'Is this price set active',
+ 'title' => ts('Price Set Is Active?'),
+ 'description' => ts('Is this price set active'),
+ 'where' => 'civicrm_price_set.is_active',
'default' => '1',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'help_pre' => array(
+ ],
+ ],
+ 'help_pre' => [
'name' => 'help_pre',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Set Pre Help') ,
- 'description' => 'Description and/or help text to display before fields in form.',
+ 'title' => ts('Price Set Pre Help'),
+ 'description' => ts('Description and/or help text to display before fields in form.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_set.help_pre',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'help_post' => array(
+ ],
+ ],
+ 'help_post' => [
'name' => 'help_post',
'type' => CRM_Utils_Type::T_TEXT,
- 'title' => ts('Price Set Post Help') ,
- 'description' => 'Description and/or help text to display after fields in form.',
+ 'title' => ts('Price Set Post Help'),
+ 'description' => ts('Description and/or help text to display after fields in form.'),
'rows' => 4,
'cols' => 80,
+ 'where' => 'civicrm_price_set.help_post',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 1,
- 'html' => array(
+ 'html' => [
'type' => 'TextArea',
- ) ,
- ) ,
- 'javascript' => array(
+ ],
+ ],
+ 'javascript' => [
'name' => 'javascript',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Set Javascript') ,
- 'description' => 'Optional Javascript script function(s) included on the form with this price_set. Can be used for conditional',
+ 'title' => ts('Price Set Javascript'),
+ 'description' => ts('Optional Javascript script function(s) included on the form with this price_set. Can be used for conditional'),
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_price_set.javascript',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- 'extends' => array(
+ ],
+ ],
+ 'extends' => [
'name' => 'extends',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Price Set Extends') ,
- 'description' => 'What components are using this price set?',
- 'required' => true,
+ 'title' => ts('Price Set Extends'),
+ 'description' => ts('What components are using this price set?'),
+ 'required' => TRUE,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
+ 'where' => 'civicrm_price_set.extends',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_component',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'financial_type_id' => array(
+ ]
+ ],
+ 'financial_type_id' => [
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Financial Type') ,
- 'description' => 'FK to Financial Type(for membership price sets only).',
+ 'title' => ts('Financial Type'),
+ 'description' => ts('FK to Financial Type(for membership price sets only).'),
+ 'where' => 'civicrm_price_set.financial_type_id',
'default' => 'NULL',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
- 'html' => array(
+ 'html' => [
'type' => 'Select',
- ) ,
- 'pseudoconstant' => array(
+ ],
+ 'pseudoconstant' => [
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
- )
- ) ,
- 'is_quick_config' => array(
+ ]
+ ],
+ 'is_quick_config' => [
'name' => 'is_quick_config',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Is Price Set Quick Config?') ,
- 'description' => 'Is set if edited on Contribution or Event Page rather than through Manage Price Sets',
+ 'title' => ts('Is Price Set Quick Config?'),
+ 'description' => ts('Is set if edited on Contribution or Event Page rather than through Manage Price Sets'),
+ 'where' => 'civicrm_price_set.is_quick_config',
+ 'default' => '0',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'is_reserved' => array(
+ ],
+ ],
+ 'is_reserved' => [
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
- 'title' => ts('Price Set Is Reserved') ,
- 'description' => 'Is this a predefined system price set (i.e. it can not be deleted, edited)?',
+ 'title' => ts('Price Set Is Reserved'),
+ 'description' => ts('Is this a predefined system price set (i.e. it can not be deleted, edited)?'),
+ 'where' => 'civicrm_price_set.is_reserved',
+ 'default' => '0',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'CheckBox',
- ) ,
- ) ,
- 'min_amount' => array(
+ ],
+ ],
+ 'min_amount' => [
'name' => 'min_amount',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Minimum Amount') ,
- 'description' => 'Minimum Amount required for this set.',
+ 'title' => ts('Minimum Amount'),
+ 'description' => ts('Minimum Amount required for this set.'),
+ 'where' => 'civicrm_price_set.min_amount',
+ 'default' => '0',
'table_name' => 'civicrm_price_set',
'entity' => 'PriceSet',
'bao' => 'CRM_Price_BAO_PriceSet',
'localizable' => 0,
- 'html' => array(
+ 'html' => [
'type' => 'Text',
- ) ,
- ) ,
- );
+ ],
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -399,10 +412,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -410,25 +424,31 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_name' => array(
+ $indices = [
+ 'UI_name' => [
'name' => 'UI_name',
- 'field' => array(
+ 'field' => [
0 => 'name',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_price_set::1::name',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/DAO/PriceSetEntity.php b/CRM/Price/DAO/PriceSetEntity.php
index 41da550b5546..c665acc98a64 100644
--- a/CRM/Price/DAO/PriceSetEntity.php
+++ b/CRM/Price/DAO/PriceSetEntity.php
@@ -1,189 +1,181 @@
__table = 'civicrm_price_set_entity';
parent::__construct();
}
+
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
- static function getReferenceColumns() {
+ public static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
- Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'price_set_id', 'civicrm_price_set', 'id');
- Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
+ Civi::$statics[__CLASS__]['links'] = static::createReferenceColumns(__CLASS__);
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName(), 'price_set_id', 'civicrm_price_set', 'id');
+ Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName(), 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
+
/**
* Returns all the column names of this table
*
* @return array
*/
- static function &fields() {
+ public static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
- Civi::$statics[__CLASS__]['fields'] = array(
- 'id' => array(
+ Civi::$statics[__CLASS__]['fields'] = [
+ 'id' => [
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set Entity ID') ,
- 'description' => 'Price Set Entity',
- 'required' => true,
+ 'title' => ts('Price Set Entity ID'),
+ 'description' => ts('Price Set Entity'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set_entity.id',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
- ) ,
- 'entity_table' => array(
+ ],
+ 'entity_table' => [
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
- 'title' => ts('Entity Table') ,
- 'description' => 'Table which uses this price set',
- 'required' => true,
+ 'title' => ts('Entity Table'),
+ 'description' => ts('Table which uses this price set'),
+ 'required' => TRUE,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
+ 'where' => 'civicrm_price_set_entity.entity_table',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
- ) ,
- 'entity_id' => array(
+ ],
+ 'entity_id' => [
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Entity IF') ,
- 'description' => 'Item in table',
- 'required' => true,
+ 'title' => ts('Entity IF'),
+ 'description' => ts('Item in table'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set_entity.entity_id',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
- ) ,
- 'price_set_id' => array(
+ ],
+ 'price_set_id' => [
'name' => 'price_set_id',
'type' => CRM_Utils_Type::T_INT,
- 'title' => ts('Price Set') ,
- 'description' => 'price set being used',
- 'required' => true,
+ 'title' => ts('Price Set'),
+ 'description' => ts('price set being used'),
+ 'required' => TRUE,
+ 'where' => 'civicrm_price_set_entity.price_set_id',
'table_name' => 'civicrm_price_set_entity',
'entity' => 'PriceSetEntity',
'bao' => 'CRM_Price_DAO_PriceSetEntity',
'localizable' => 0,
'FKClassName' => 'CRM_Price_DAO_PriceSet',
- ) ,
- );
+ ],
+ ];
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
+
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
- static function &fieldKeys() {
+ public static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
+
/**
* Returns the names of this table
*
* @return string
*/
- static function getTableName() {
+ public static function getTableName() {
return self::$_tableName;
}
+
/**
* Returns if this table needs to be logged
*
- * @return boolean
+ * @return bool
*/
- function getLog() {
+ public function getLog() {
return self::$_log;
}
+
/**
* Returns the list of fields that can be imported
*
@@ -191,10 +183,11 @@ function getLog() {
*
* @return array
*/
- static function &import($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set_entity', $prefix, array());
+ public static function &import($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'price_set_entity', $prefix, []);
return $r;
}
+
/**
* Returns the list of fields that can be exported
*
@@ -202,26 +195,32 @@ static function &import($prefix = false) {
*
* @return array
*/
- static function &export($prefix = false) {
- $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set_entity', $prefix, array());
+ public static function &export($prefix = FALSE) {
+ $r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'price_set_entity', $prefix, []);
return $r;
}
+
/**
* Returns the list of indices
+ *
+ * @param bool $localize
+ *
+ * @return array
*/
public static function indices($localize = TRUE) {
- $indices = array(
- 'UI_entity' => array(
+ $indices = [
+ 'UI_entity' => [
'name' => 'UI_entity',
- 'field' => array(
+ 'field' => [
0 => 'entity_table',
1 => 'entity_id',
- ) ,
- 'localizable' => false,
- 'unique' => true,
+ ],
+ 'localizable' => FALSE,
+ 'unique' => TRUE,
'sig' => 'civicrm_price_set_entity::1::entity_table::entity_id',
- ) ,
- );
+ ],
+ ];
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
+
}
diff --git a/CRM/Price/Form/DeleteField.php b/CRM/Price/Form/DeleteField.php
index 20319b8591cf..23c5dbda7048 100644
--- a/CRM/Price/Form/DeleteField.php
+++ b/CRM/Price/Form/DeleteField.php
@@ -1,9 +1,9 @@
addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Price Field'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -97,7 +97,7 @@ public function buildQuickForm() {
*/
public function postProcess() {
if (CRM_Price_BAO_PriceField::deleteField($this->_fid)) {
- CRM_Core_Session::setStatus(ts('The Price Field \'%1\' has been deleted.', array(1 => $this->_title)), '', 'success');
+ CRM_Core_Session::setStatus(ts('The Price Field \'%1\' has been deleted.', [1 => $this->_title]), '', 'success');
}
}
diff --git a/CRM/Price/Form/DeleteSet.php b/CRM/Price/Form/DeleteSet.php
index a4bb5a0d8a33..a9045f3da35d 100644
--- a/CRM/Price/Form/DeleteSet.php
+++ b/CRM/Price/Form/DeleteSet.php
@@ -1,9 +1,9 @@
assign('title', $this->_title);
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Price Set'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
}
/**
@@ -91,12 +91,12 @@ public function buildQuickForm() {
public function postProcess() {
if (CRM_Price_BAO_PriceSet::deleteSet($this->_sid)) {
CRM_Core_Session::setStatus(ts('The Price Set \'%1\' has been deleted.',
- array(1 => $this->_title), ts('Deleted'), 'success'
+ [1 => $this->_title], ts('Deleted'), 'success'
));
}
else {
CRM_Core_Session::setStatus(ts('The Price Set \'%1\' has not been deleted! You must delete all price fields in this set prior to deleting the set.',
- array(1 => $this->_title)
+ [1 => $this->_title]
), 'Unable to Delete', 'error');
}
}
diff --git a/CRM/Price/Form/Field.php b/CRM/Price/Form/Field.php
index 75ce1a44b1f6..dc237c1fa735 100644
--- a/CRM/Price/Form/Field.php
+++ b/CRM/Price/Form/Field.php
@@ -1,9 +1,9 @@
_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}");
- $breadCrumb = array(array('title' => ts('Price Set Fields'), 'url' => $url));
+ $breadCrumb = [['title' => ts('Price Set Fields'), 'url' => $url]];
- $this->_extendComponentId = array();
+ $this->_extendComponentId = [];
$extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
if ($extendComponentId) {
$this->_extendComponentId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
@@ -95,10 +96,10 @@ public function preProcess() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
// is it an edit operation ?
if (isset($this->_fid)) {
- $params = array('id' => $this->_fid);
+ $params = ['id' => $this->_fid];
$this->assign('fid', $this->_fid);
CRM_Price_BAO_PriceField::retrieve($params, $defaults);
$this->_sid = $defaults['price_set_id'];
@@ -106,7 +107,7 @@ public function setDefaultValues() {
// if text, retrieve price
if ($defaults['html_type'] == 'Text') {
$isActive = $defaults['is_active'];
- $valueParams = array('price_field_id' => $this->_fid);
+ $valueParams = ['price_field_id' => $this->_fid];
CRM_Price_BAO_PriceFieldValue::retrieve($valueParams, $defaults);
@@ -115,17 +116,6 @@ public function setDefaultValues() {
$defaults['is_active'] = $isActive;
}
- if (!empty($defaults['active_on'])) {
- list($defaults['active_on'],
- $defaults['active_on_time']
- ) = CRM_Utils_Date::setDateDefaults($defaults['active_on'], 'activityDateTime');
- }
-
- if (!empty($defaults['expire_on'])) {
- list($defaults['expire_on'],
- $defaults['expire_on_time']
- ) = CRM_Utils_Date::setDateDefaults($defaults['expire_on'], 'activityDateTime');
- }
}
else {
$defaults['is_active'] = 1;
@@ -137,7 +127,7 @@ public function setDefaultValues() {
}
if ($this->_action & CRM_Core_Action::ADD) {
- $fieldValues = array('price_set_id' => $this->_sid);
+ $fieldValues = ['price_set_id' => $this->_sid];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceField', $fieldValues);
$defaults['options_per_line'] = 1;
$defaults['is_display_amounts'] = 1;
@@ -210,7 +200,7 @@ public function buildQuickForm() {
$this->add('select', 'financial_type_id',
ts('Financial Type'),
- array(' ' => ts('- select -')) + $financialType
+ [' ' => ts('- select -')] + $financialType
);
$this->assign('useForMember', FALSE);
@@ -278,7 +268,7 @@ public function buildQuickForm() {
'select',
'option_financial_type_id[' . $i . ']',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialType
+ ['' => ts('- select -')] + $financialType
);
if (in_array($eventComponentId, $this->_extendComponentId)) {
// count
@@ -294,21 +284,21 @@ public function buildQuickForm() {
}
elseif (in_array($memberComponentId, $this->_extendComponentId)) {
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
- $js = array('onchange' => "calculateRowValues( $i );");
+ $js = ['onchange' => "calculateRowValues( $i );"];
$this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'),
- array('' => ' ') + $membershipTypes, FALSE, $js
+ ['' => ' '] + $membershipTypes, FALSE, $js
);
$this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array::value('membership_num_terms', $attributes));
}
// weight
- $this->add('text', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
+ $this->add('number', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
// is active ?
$this->add('checkbox', 'option_status[' . $i . ']', ts('Active?'));
- $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), array('' => ts('- select -')) + $visibilityType);
+ $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), $visibilityType);
$defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
//for checkbox handling of default option
@@ -322,7 +312,7 @@ public function buildQuickForm() {
$this->add('checkbox', 'is_display_amounts', ts('Display Amount?'));
// weight
- $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
+ $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// checkbox / radio options per line
@@ -338,10 +328,10 @@ public function buildQuickForm() {
CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
);
- $this->addDateTime('active_on', ts('Active On'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'active_on', ts('Active On'), [], FALSE, ['time' => TRUE]);
// expire_on
- $this->addDateTime('expire_on', ts('Expire On'), FALSE, array('formatType' => 'activityDateTime'));
+ $this->add('datepicker', 'expire_on', ts('Expire On'), [], FALSE, ['time' => TRUE]);
// is required ?
$this->add('checkbox', 'is_required', ts('Required?'));
@@ -350,27 +340,27 @@ public function buildQuickForm() {
$this->add('checkbox', 'is_active', ts('Active?'));
// add buttons
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'next',
'name' => ts('Save and New'),
'subName' => 'new',
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
// is public?
$this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
// add a form rule to check default value
- $this->addFormRule(array('CRM_Price_Form_Field', 'formRule'), $this);
+ $this->addFormRule(['CRM_Price_Form_Field', 'formRule'], $this);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
@@ -379,7 +369,7 @@ public function buildQuickForm() {
$this->addElement('button',
'done',
ts('Done'),
- array('onclick' => "location.href='$url'")
+ ['onclick' => "location.href='$url'"]
);
}
}
@@ -400,7 +390,7 @@ public function buildQuickForm() {
public static function formRule($fields, $files, $form) {
// all option fields are of type "money"
- $errors = array();
+ $errors = [];
/** Check the option values entered
* Appropriate values are required for the selected datatype
@@ -445,7 +435,7 @@ public static function formRule($fields, $files, $form) {
$publicOptionCount = $_flagOption = $_rowError = 0;
$_showHide = new CRM_Core_ShowHideBlocks('', '');
- $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', NULL, array('labelColumn' => 'name'));
+ $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', NULL, ['labelColumn' => 'name']);
for ($index = 1; $index <= self::NUM_OPTION; $index++) {
@@ -544,7 +534,7 @@ public static function formRule($fields, $files, $form) {
// check for checkboxes allowing user to select multiple memberships from same membership organization
if ($fields['html_type'] == 'CheckBox') {
$foundDuplicate = FALSE;
- $orgIds = array();
+ $orgIds = [];
foreach ($memTypesIDS as $key => $val) {
$org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val);
if (in_array($org[$val], $orgIds)) {
@@ -621,11 +611,11 @@ public static function formRule($fields, $files, $form) {
}
if (empty($fields['option_name'])) {
- $fields['option_amount'] = array();
+ $fields['option_amount'] = [];
}
if (empty($fields['option_label'])) {
- $fields['option_label'] = array();
+ $fields['option_label'] = [];
}
}
@@ -643,18 +633,6 @@ public function postProcess() {
$params['is_required'] = CRM_Utils_Array::value('is_required', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
- if (isset($params['active_on'])) {
- $params['active_on'] = CRM_Utils_Date::processDate($params['active_on'],
- CRM_Utils_Array::value('active_on_time', $params),
- TRUE
- );
- }
- if (isset($params['expire_on'])) {
- $params['expire_on'] = CRM_Utils_Date::processDate($params['expire_on'],
- CRM_Utils_Array::value('expire_on_time', $params),
- TRUE
- );
- }
$params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
$params['count'] = CRM_Utils_Array::value('count', $params, FALSE);
@@ -662,7 +640,7 @@ public function postProcess() {
$params['price_set_id'] = $this->_sid;
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
- $fieldValues = array('price_set_id' => $this->_sid);
+ $fieldValues = ['price_set_id' => $this->_sid];
$oldWeight = NULL;
if ($this->_fid) {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'weight', 'id');
@@ -681,15 +659,14 @@ public function postProcess() {
$params['is_enter_qty'] = 1;
// modify params values as per the option group and option
// value
- $params['option_amount'] = array(1 => $params['price']);
- $params['option_label'] = array(1 => $params['label']);
- $params['option_count'] = array(1 => $params['count']);
- $params['option_max_value'] = array(1 => CRM_Utils_Array::value('max_value', $params));
+ $params['option_amount'] = [1 => $params['price']];
+ $params['option_label'] = [1 => $params['label']];
+ $params['option_count'] = [1 => $params['count']];
+ $params['option_max_value'] = [1 => CRM_Utils_Array::value('max_value', $params)];
//$params['option_description'] = array( 1 => $params['description'] );
- $params['option_weight'] = array(1 => $params['weight']);
- $params['option_financial_type_id'] = array(1 => $params['financial_type_id']);
- $params['option_visibility_id'] = array(1 => CRM_Utils_Array::value('visibility_id', $params));
- $params['is_active'] = array(1 => 1);
+ $params['option_weight'] = [1 => $params['weight']];
+ $params['option_financial_type_id'] = [1 => $params['financial_type_id']];
+ $params['option_visibility_id'] = [1 => CRM_Utils_Array::value('visibility_id', $params)];
}
if ($this->_fid) {
@@ -701,7 +678,7 @@ public function postProcess() {
$priceField = CRM_Price_BAO_PriceField::create($params);
if (!is_a($priceField, 'CRM_Core_Error')) {
- CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', array(1 => $priceField->label)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', [1 => $priceField->label]), ts('Saved'), 'success');
}
$buttonName = $this->controller->getButtonName();
$session = CRM_Core_Session::singleton();
diff --git a/CRM/Price/Form/Option.php b/CRM/Price/Form/Option.php
index 022697a744b4..f159c37bdc94 100644
--- a/CRM/Price/Form/Option.php
+++ b/CRM/Price/Form/Option.php
@@ -1,9 +1,9 @@
_action == CRM_Core_Action::DELETE) {
return NULL;
}
- $defaults = array();
+ $defaults = [];
if (isset($this->_oid)) {
- $params = array('id' => $this->_oid);
+ $params = ['id' => $this->_oid];
CRM_Price_BAO_PriceFieldValue::retrieve($params, $defaults);
// fix the display of the monetary value, CRM-4038
- $defaults['value'] = CRM_Utils_Money::format(CRM_Utils_Array::value('value', $defaults), NULL, '%a');
+ foreach ($this->_moneyFields as $field) {
+ $defaults[$field] = CRM_Utils_Money::format(CRM_Utils_Array::value($field, $defaults), NULL, '%a');
+ }
}
$memberComponentId = CRM_Core_Component::getComponentID('CiviMember');
@@ -99,7 +108,7 @@ public function setDefaultValues() {
$defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'financial_type_id', 'id');;
}
if (!isset($defaults['weight']) || !$defaults['weight']) {
- $fieldValues = array('price_field_id' => $this->_fid);
+ $fieldValues = ['price_field_id' => $this->_fid];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceFieldValue', $fieldValues);
$defaults['is_active'] = 1;
}
@@ -120,16 +129,16 @@ public function buildQuickForm() {
}
}
if ($this->_action == CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete'),
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
return NULL;
}
else {
@@ -163,11 +172,11 @@ public function buildQuickForm() {
if ($memberComponentId == $extendComponentId) {
$this->assign('showMember', TRUE);
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
- $this->add('select', 'membership_type_id', ts('Membership Type'), array(
+ $this->add('select', 'membership_type_id', ts('Membership Type'), [
'' => ' ',
- ) + $membershipTypes, FALSE,
- array('onClick' => "calculateRowValues( );"));
- $this->add('text', 'membership_num_terms', ts('Number of Terms'), $attributes['membership_num_terms']);
+ ] + $membershipTypes, FALSE,
+ ['onClick' => "calculateRowValues( );"]);
+ $this->add('number', 'membership_num_terms', ts('Number of Terms'), $attributes['membership_num_terms']);
}
else {
$allComponents = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
@@ -175,10 +184,10 @@ public function buildQuickForm() {
if (in_array($eventComponentId, $allComponents)) {
$this->isEvent = TRUE;
// count
- $this->add('text', 'count', ts('Participant Count'));
+ $this->add('number', 'count', ts('Participant Count'));
$this->addRule('count', ts('Please enter a valid Max Participants.'), 'positiveInteger');
- $this->add('text', 'max_value', ts('Max Participants'));
+ $this->add('number', 'max_value', ts('Max Participants'));
$this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger');
}
@@ -193,7 +202,7 @@ public function buildQuickForm() {
'select',
'financial_type_id',
ts('Financial Type'),
- array('' => ts('- select -')) + $financialType,
+ ['' => ts('- select -')] + $financialType,
TRUE
);
@@ -223,7 +232,7 @@ public function buildQuickForm() {
$this->add('textarea', 'help_post', ts('Post Option Help'));
// weight
- $this->add('text', 'weight', ts('Order'), NULL, TRUE);
+ $this->add('number', 'weight', ts('Order'), NULL, TRUE);
$this->addRule('weight', ts('is a numeric field'), 'numeric');
// is active ?
@@ -244,31 +253,31 @@ public function buildQuickForm() {
}
}
// add buttons
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Save'),
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
// if view mode pls freeze it with the done button.
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
- $this->addFormRule(array('CRM_Price_Form_Option', 'formRule'), $this);
+ $this->addFormRule(['CRM_Price_Form_Option', 'formRule'], $this);
}
/**
@@ -285,7 +294,7 @@ public function buildQuickForm() {
* true otherwise
*/
public static function formRule($fields, $files, $form) {
- $errors = array();
+ $errors = [];
if (!empty($fields['count']) && !empty($fields['max_value']) &&
$fields['count'] > $fields['max_value']
) {
@@ -293,7 +302,7 @@ public static function formRule($fields, $files, $form) {
}
$priceField = CRM_Price_BAO_PriceField::findById($fields['fieldId']);
- $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', NULL, array('labelColumn' => 'name'));
+ $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', NULL, ['labelColumn' => 'name']);
$publicCount = 0;
$options = CRM_Price_BAO_PriceField::getOptions($priceField->id);
@@ -322,7 +331,7 @@ public static function formRule($fields, $files, $form) {
*/
public function postProcess() {
if ($this->_action == CRM_Core_Action::DELETE) {
- $fieldValues = array('price_field_id' => $this->_fid);
+ $fieldValues = ['price_field_id' => $this->_fid];
$wt = CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceFieldValue', $this->_oid, $fieldValues);
$label = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
$this->_oid,
@@ -330,27 +339,29 @@ public function postProcess() {
);
if (CRM_Price_BAO_PriceFieldValue::del($this->_oid)) {
- CRM_Core_Session::setStatus(ts('%1 option has been deleted.', array(1 => $label)), ts('Record Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts('%1 option has been deleted.', [1 => $label]), ts('Record Deleted'), 'success');
}
return NULL;
}
else {
- $params = $ids = array();
+ $params = $ids = [];
$params = $this->controller->exportValues('Option');
$fieldLabel = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'label');
- $params['amount'] = CRM_Utils_Rule::cleanMoney(trim($params['amount']));
+ foreach ($this->_moneyFields as $field) {
+ $params[$field] = CRM_Utils_Rule::cleanMoney(trim($params[$field]));
+ }
$params['price_field_id'] = $this->_fid;
$params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
- $ids = array();
+ $ids = [];
if ($this->_oid) {
$ids['id'] = $this->_oid;
}
$optionValue = CRM_Price_BAO_PriceFieldValue::create($params, $ids);
- CRM_Core_Session::setStatus(ts("The option '%1' has been saved.", array(1 => $params['label'])), ts('Value Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("The option '%1' has been saved.", [1 => $params['label']]), ts('Value Saved'), 'success');
}
}
diff --git a/CRM/Price/Form/Preview.php b/CRM/Price/Form/Preview.php
index 70d4b3c986eb..4d3cad25e525 100644
--- a/CRM/Price/Form/Preview.php
+++ b/CRM/Price/Form/Preview.php
@@ -1,9 +1,9 @@
_groupTree[$groupId]['fields'][$fieldId] = $groupTree[$groupId]['fields'][$fieldId];
$this->assign('preview_type', 'field');
$url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$groupId}");
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Price Set Fields'),
'url' => $url,
- ),
- );
+ ],
+ ];
}
else {
// group preview
@@ -80,12 +80,12 @@ public function preProcess() {
$this->assign('preview_type', 'group');
$this->assign('setTitle', CRM_Price_BAO_PriceSet::getTitle($groupId));
$url = CRM_Utils_System::url('civicrm/admin/price', 'reset=1');
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Price Sets'),
'url' => $url,
- ),
- );
+ ],
+ ];
}
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -97,7 +97,7 @@ public function preProcess() {
* the default array reference
*/
public function setDefaultValues() {
- $defaults = array();
+ $defaults = [];
$groupId = $this->get('groupId');
$fieldId = $this->get('fieldId');
if (!empty($this->_groupTree[$groupId]['fields'])) {
@@ -139,13 +139,13 @@ public function buildQuickForm() {
}
}
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'cancel',
'name' => ts('Done with Preview'),
'isDefault' => TRUE,
- ),
- ));
+ ],
+ ]);
}
}
diff --git a/CRM/Price/Form/Set.php b/CRM/Price/Form/Set.php
index c6c17e5efb19..1f49fa4e0461 100644
--- a/CRM/Price/Form/Set.php
+++ b/CRM/Price/Form/Set.php
@@ -1,9 +1,9 @@
_sid;
+ }
+
+ /**
+ * Explicitly declare the entity api name.
+ */
+ public function getDefaultEntity() {
+ return 'PriceSet';
+ }
+
+ /**
+ * Fields for the entity to be assigned to the template.
+ *
+ * Fields may have keys
+ * - name (required to show in tpl from the array)
+ * - description (optional, will appear below the field)
+ * - not-auto-addable - this class will not attempt to add the field using addField.
+ * (this will be automatically set if the field does not have html in it's metadata
+ * or is not a core field on the form's entity).
+ * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
+ * - template - use a field specific template to render this field
+ * @var array
+ */
+ protected $entityFields = [];
+
+ /**
+ * Set entity fields to be assigned to the form.
+ */
+ protected function setEntityFields() {
+ $this->entityFields = [
+ 'title' => [
+ 'required' => 'TRUE',
+ 'name' => 'title',
+ ],
+ 'min_amount' => ['name' => 'min_amount'],
+ 'help_pre' => ['name' => 'help_pre'],
+ 'help_post' => ['name' => 'help_post'],
+ 'is_active' => ['name' => 'is_active'],
+ ];
+ }
+
+ /**
+ * Deletion message to be assigned to the form.
+ *
+ * @var string
+ */
+ protected $deleteMessage;
+
+ /**
+ * Set the delete message.
+ *
+ * We do this from the constructor in order to do a translation.
+ */
+ public function setDeleteMessage() {}
+
/**
* Set variables up before form is built.
*/
@@ -52,24 +115,24 @@ public function preProcess() {
// setting title for html page
$title = ts('New Price Set');
- if ($this->_sid) {
- $title = CRM_Price_BAO_PriceSet::getTitle($this->_sid);
+ if ($this->getEntityId()) {
+ $title = CRM_Price_BAO_PriceSet::getTitle($this->getEntityId());
}
if ($this->_action & CRM_Core_Action::UPDATE) {
- $title = ts('Edit %1', array(1 => $title));
+ $title = ts('Edit %1', [1 => $title]);
}
elseif ($this->_action & CRM_Core_Action::VIEW) {
- $title = ts('Preview %1', array(1 => $title));
+ $title = ts('Preview %1', [1 => $title]);
}
CRM_Utils_System::setTitle($title);
$url = CRM_Utils_System::url('civicrm/admin/price', 'reset=1');
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('Price Sets'),
'url' => $url,
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -87,7 +150,7 @@ public function preProcess() {
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $options) {
- $errors = array();
+ $errors = [];
$count = count(CRM_Utils_Array::value('extends', $fields));
//price sets configured for membership
if ($count && array_key_exists(CRM_Core_Component::getComponentID('CiviMember'), $fields['extends'])) {
@@ -106,23 +169,18 @@ public static function formRule($fields, $files, $options) {
* Build the form object.
*/
public function buildQuickForm() {
- $this->applyFilter('__ALL__', 'trim');
-
- $this->assign('sid', $this->_sid);
+ $this->buildQuickEntityForm();
+ $this->assign('sid', $this->getEntityId());
- // title
- $this->add('text', 'title', ts('Set Name'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'title'), TRUE);
$this->addRule('title', ts('Name already exists in Database.'),
- 'objectExists', array('CRM_Price_DAO_PriceSet', $this->_sid, 'title')
+ 'objectExists', ['CRM_Price_DAO_PriceSet', $this->getEntityId(), 'title']
);
- $priceSetUsedTables = $extends = array();
- if ($this->_action == CRM_Core_Action::UPDATE && $this->_sid) {
- $priceSetUsedTables = CRM_Price_BAO_PriceSet::getUsedBy($this->_sid, 'table');
+ $priceSetUsedTables = $extends = [];
+ if ($this->_action == CRM_Core_Action::UPDATE && $this->getEntityId()) {
+ $priceSetUsedTables = CRM_Price_BAO_PriceSet::getUsedBy($this->getEntityId(), 'table');
}
- $config = CRM_Core_Config::singleton();
- $showContribution = FALSE;
$enabledComponents = CRM_Core_Component::getEnabledComponents();
foreach ($enabledComponents as $name => $compObj) {
@@ -130,7 +188,7 @@ public function buildQuickForm() {
case 'CiviEvent':
$option = $this->createElement('checkbox', $compObj->componentID, NULL, ts('Event'));
if (!empty($priceSetUsedTables)) {
- foreach (array('civicrm_event', 'civicrm_participant') as $table) {
+ foreach (['civicrm_event', 'civicrm_participant'] as $table) {
if (in_array($table, $priceSetUsedTables)) {
$option->freeze();
break;
@@ -143,7 +201,7 @@ public function buildQuickForm() {
case 'CiviContribute':
$option = $this->createElement('checkbox', $compObj->componentID, NULL, ts('Contribution'));
if (!empty($priceSetUsedTables)) {
- foreach (array('civicrm_contribution', 'civicrm_contribution_page') as $table) {
+ foreach (['civicrm_contribution', 'civicrm_contribution_page'] as $table) {
if (in_array($table, $priceSetUsedTables)) {
$option->freeze();
break;
@@ -156,7 +214,7 @@ public function buildQuickForm() {
case 'CiviMember':
$option = $this->createElement('checkbox', $compObj->componentID, NULL, ts('Membership'));
if (!empty($priceSetUsedTables)) {
- foreach (array('civicrm_membership', 'civicrm_contribution_page') as $table) {
+ foreach (['civicrm_membership', 'civicrm_contribution_page'] as $table) {
if (in_array($table, $priceSetUsedTables)) {
$option->freeze();
break;
@@ -168,8 +226,6 @@ public function buildQuickForm() {
}
}
- $this->addElement('text', 'min_amount', ts('Minimum Amount'));
-
if (CRM_Utils_System::isNull($extends)) {
$this->assign('extends', FALSE);
}
@@ -179,54 +235,21 @@ public function buildQuickForm() {
$this->addGroup($extends, 'extends', ts('Used For'), ' ', TRUE);
- $this->addRule('extends', ts('%1 is a required field.', array(1 => ts('Used For'))), 'required');
+ $this->addRule('extends', ts('%1 is a required field.', [1 => ts('Used For')]), 'required');
// financial type
$financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
- foreach ($financialType as $finTypeId => $type) {
- if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
- && !CRM_Core_Permission::check('add contributions of type ' . $type)
- ) {
- unset($financialType[$finTypeId]);
- }
- }
-
$this->add('select', 'financial_type_id',
ts('Default Financial Type'),
- array('' => ts('- select -')) + $financialType, 'required'
+ ['' => ts('- select -')] + $financialType, 'required'
);
- // help text
- $this->add('textarea', 'help_pre', ts('Pre-form Help'),
- CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'help_pre')
- );
- $this->add('textarea', 'help_post', ts('Post-form Help'),
- CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'help_post')
- );
-
- // is this set active ?
- $this->addElement('checkbox', 'is_active', ts('Is this Price Set active?'));
-
- $this->addButtons(array(
- array(
- 'type' => 'next',
- 'name' => ts('Save'),
- 'spacing' => ' ',
- 'isDefault' => TRUE,
- ),
- array(
- 'type' => 'cancel',
- 'name' => ts('Cancel'),
- ),
- ));
-
- $this->addFormRule(array('CRM_Price_Form_Set', 'formRule'));
+ $this->addFormRule(['CRM_Price_Form_Set', 'formRule']);
// views are implemented as frozen form
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
- //$this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/price?reset=1&action=browse'"));
}
}
@@ -239,9 +262,9 @@ public function buildQuickForm() {
* array of default values
*/
public function setDefaultValues() {
- $defaults = array('is_active' => TRUE);
- if ($this->_sid) {
- $params = array('id' => $this->_sid);
+ $defaults = ['is_active' => TRUE];
+ if ($this->getEntityId()) {
+ $params = ['id' => $this->getEntityId()];
CRM_Price_BAO_PriceSet::retrieve($params, $defaults);
$extends = explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['extends']);
unset($defaults['extends']);
@@ -263,7 +286,7 @@ public function postProcess() {
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
- $compIds = array();
+ $compIds = [];
$extends = CRM_Utils_Array::value('extends', $params);
if (is_array($extends)) {
foreach ($extends as $compId => $selected) {
@@ -275,7 +298,7 @@ public function postProcess() {
$params['extends'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $compIds);
if ($this->_action & CRM_Core_Action::UPDATE) {
- $params['id'] = $this->_sid;
+ $params['id'] = $this->getEntityId();
}
else {
$params['name'] = CRM_Utils_String::titleToVar($params['title'],
@@ -284,19 +307,19 @@ public function postProcess() {
$set = CRM_Price_BAO_PriceSet::create($params);
if ($this->_action & CRM_Core_Action::UPDATE) {
- CRM_Core_Session::setStatus(ts('The Set \'%1\' has been saved.', array(1 => $set->title)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts('The Set \'%1\' has been saved.', [1 => $set->title]), ts('Saved'), 'success');
}
else {
// Jump directly to adding a field if popups are disabled
$action = CRM_Core_Resources::singleton()->ajaxPopupsEnabled ? 'browse' : 'add';
- $url = CRM_Utils_System::url('civicrm/admin/price/field', array(
+ $url = CRM_Utils_System::url('civicrm/admin/price/field', [
'reset' => 1,
'action' => $action,
'sid' => $set->id,
'new' => 1,
- ));
+ ]);
CRM_Core_Session::setStatus(ts("Your Set '%1' has been added. You can add fields to this set now.",
- array(1 => $set->title)
+ [1 => $set->title]
), ts('Saved'), 'success');
$session = CRM_Core_Session::singleton();
$session->replaceUserContext($url);
diff --git a/CRM/Price/Page/Field.php b/CRM/Price/Page/Field.php
index 536195af8fc9..47e1cb1c93dc 100644
--- a/CRM/Price/Page/Field.php
+++ b/CRM/Price/Page/Field.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Price Field'),
'url' => 'civicrm/admin/price/field',
'qs' => 'action=update&reset=1&sid=%%sid%%&fid=%%fid%%',
'title' => ts('Edit Price'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview Field'),
'url' => 'civicrm/admin/price/field',
'qs' => 'action=preview&reset=1&sid=%%sid%%&fid=%%fid%%',
'title' => ts('Preview Price'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Price'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Price'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/price/field',
'qs' => 'action=delete&reset=1&sid=%%sid%%&fid=%%fid%%',
'title' => ts('Delete Price'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -117,7 +117,7 @@ public function browse() {
$resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header');
}
- $priceField = array();
+ $priceField = [];
$priceFieldBAO = new CRM_Price_BAO_PriceField();
// fkey is sid
@@ -133,13 +133,13 @@ public function browse() {
$taxRate = CRM_Core_PseudoConstant::getTaxRates();
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
while ($priceFieldBAO->fetch()) {
- $priceField[$priceFieldBAO->id] = array();
+ $priceField[$priceFieldBAO->id] = [];
CRM_Core_DAO::storeValues($priceFieldBAO, $priceField[$priceFieldBAO->id]);
// get price if it's a text field
if ($priceFieldBAO->html_type == 'Text') {
- $optionValues = array();
- $params = array('price_field_id' => $priceFieldBAO->id);
+ $optionValues = [];
+ $params = ['price_field_id' => $priceFieldBAO->id];
CRM_Price_BAO_PriceFieldValue::retrieve($params, $optionValues);
$priceField[$priceFieldBAO->id]['price'] = CRM_Utils_Array::value('amount', $optionValues);
@@ -149,7 +149,7 @@ public function browse() {
$getTaxDetails = TRUE;
}
if (isset($priceField[$priceFieldBAO->id]['tax_rate'])) {
- $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceField[$priceFieldBAO->id]['price'], $priceField[$priceFieldBAO->id]['tax_rate']);
+ $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceField[$priceFieldBAO->id]['price'], $priceField[$priceFieldBAO->id]['tax_rate'], TRUE);
$priceField[$priceFieldBAO->id]['tax_amount'] = $taxAmount['tax_amount'];
}
}
@@ -183,10 +183,10 @@ public function browse() {
$priceField[$priceFieldBAO->id]['action'] = CRM_Core_Action::formLink(
self::actionLinks(),
$action,
- array(
+ [
'fid' => $priceFieldBAO->id,
'sid' => $this->_sid,
- ),
+ ],
ts('more'),
FALSE,
'priceField.row.actions',
@@ -256,12 +256,12 @@ public function run() {
$this->assign('isReserved', $this->_isSetReserved);
CRM_Price_BAO_PriceSet::checkPermission($this->_sid);
- $comps = array(
+ $comps = [
'Event' => 'civicrm_event',
'Contribution' => 'civicrm_contribution_page',
'EventTemplate' => 'civicrm_event_template',
- );
- $priceSetContexts = array();
+ ];
+ $priceSetContexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$priceSetContexts[] = $name;
@@ -298,7 +298,7 @@ public function run() {
$groupTitle = CRM_Price_BAO_PriceSet::getTitle($this->_sid);
$this->assign('sid', $this->_sid);
$this->assign('groupTitle', $groupTitle);
- CRM_Utils_System::setTitle(ts('%1 - Price Fields', array(1 => $groupTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Price Fields', [1 => $groupTitle]));
}
// assign vars to templates
diff --git a/CRM/Price/Page/Option.php b/CRM/Price/Page/Option.php
index 0724ebec9b0a..bdf06ffc3631 100644
--- a/CRM/Price/Page/Option.php
+++ b/CRM/Price/Page/Option.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::UPDATE => [
'name' => ts('Edit Option'),
'url' => 'civicrm/admin/price/field/option',
'qs' => 'reset=1&action=update&oid=%%oid%%&fid=%%fid%%&sid=%%sid%%',
'title' => ts('Edit Price Option'),
- ),
- CRM_Core_Action::VIEW => array(
+ ],
+ CRM_Core_Action::VIEW => [
'name' => ts('View'),
'url' => 'civicrm/admin/price/field/option',
'qs' => 'action=view&oid=%%oid%%',
'title' => ts('View Price Option'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Price Option'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Price Option'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/price/field/option',
'qs' => 'action=delete&oid=%%oid%%',
'title' => ts('Disable Price Option'),
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -121,16 +121,16 @@ public static function &actionLinks() {
* @return void
*/
public function browse() {
- $priceOptions = civicrm_api3('PriceFieldValue', 'get', array(
- 'price_field_id' => $this->_fid,
+ $priceOptions = civicrm_api3('PriceFieldValue', 'get', [
+ 'price_field_id' => $this->_fid,
// Explicitly do not check permissions so we are not
// restricted by financial type, so we can change them.
- 'check_permissions' => FALSE,
- 'options' => array(
- 'limit' => 0,
- 'sort' => array('weight', 'label'),
- ),
- ));
+ 'check_permissions' => FALSE,
+ 'options' => [
+ 'limit' => 0,
+ 'sort' => ['weight', 'label'],
+ ],
+ ]);
$customOption = $priceOptions['values'];
// CRM-15378 - check if these price options are in an Event price set
@@ -158,7 +158,7 @@ public function browse() {
if ($invoicing && isset($customOption[$id]['tax_rate'])) {
$getTaxDetails = TRUE;
}
- $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($customOption[$id]['amount'], $customOption[$id]['tax_rate']);
+ $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($customOption[$id]['amount'], $customOption[$id]['tax_rate'], TRUE);
$customOption[$id]['tax_amount'] = $taxAmount['tax_amount'];
}
if (!empty($values['financial_type_id'])) {
@@ -184,11 +184,11 @@ public function browse() {
}
$customOption[$id]['order'] = $customOption[$id]['weight'];
$customOption[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action,
- array(
+ [
'oid' => $id,
'fid' => $this->_fid,
'sid' => $this->_sid,
- ),
+ ],
ts('more'),
FALSE,
'priceFieldValue.row.actions',
@@ -224,7 +224,7 @@ public function edit($action) {
$oid = CRM_Utils_Request::retrieve('oid', 'Positive',
$this, FALSE, 0
);
- $params = array();
+ $params = [];
if ($oid) {
$params['oid'] = $oid;
$sid = CRM_Price_BAO_PriceSet::getSetId($params);
@@ -251,11 +251,11 @@ public function edit($action) {
);
$this->assign('usedPriceSetTitle', CRM_Price_BAO_PriceFieldValue::getOptionLabel($oid));
$this->assign('usedBy', $usedBy);
- $comps = array(
+ $comps = [
"Event" => "civicrm_event",
"Contribution" => "civicrm_contribution_page",
- );
- $priceSetContexts = array();
+ ];
+ $priceSetContexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$priceSetContexts[] = $name;
@@ -289,19 +289,19 @@ public function run() {
$this->assign('isReserved', $this->_isSetReserved);
}
//as url contain $sid so append breadcrumb dynamically.
- $breadcrumb = array(
- array(
+ $breadcrumb = [
+ [
'title' => ts('Price Fields'),
'url' => CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&sid=' . $this->_sid),
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadcrumb);
if ($this->_fid) {
$fieldTitle = CRM_Price_BAO_PriceField::getTitle($this->_fid);
$this->assign('fid', $this->_fid);
$this->assign('fieldTitle', $fieldTitle);
- CRM_Utils_System::setTitle(ts('%1 - Price Options', array(1 => $fieldTitle)));
+ CRM_Utils_System::setTitle(ts('%1 - Price Options', [1 => $fieldTitle]));
$htmlType = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $this->_fid, 'html_type');
$this->assign('addMoreFields', TRUE);
diff --git a/CRM/Price/Page/Set.php b/CRM/Price/Page/Set.php
index c3ec481e7b5f..accc307829e5 100644
--- a/CRM/Price/Page/Set.php
+++ b/CRM/Price/Page/Set.php
@@ -1,9 +1,9 @@
array(
+ self::$_actionLinks = [
+ CRM_Core_Action::BROWSE => [
'name' => ts('View and Edit Price Fields'),
'url' => 'civicrm/admin/price/field',
'qs' => 'reset=1&action=browse&sid=%%sid%%',
'title' => ts('View and Edit Price Fields'),
- ),
- CRM_Core_Action::PREVIEW => array(
+ ],
+ CRM_Core_Action::PREVIEW => [
'name' => ts('Preview'),
'url' => 'civicrm/admin/price',
'qs' => 'action=preview&reset=1&sid=%%sid%%',
'title' => ts('Preview Price Set'),
- ),
- CRM_Core_Action::UPDATE => array(
+ ],
+ CRM_Core_Action::UPDATE => [
'name' => ts('Settings'),
'url' => 'civicrm/admin/price',
'qs' => 'action=update&reset=1&sid=%%sid%%',
'title' => ts('Edit Price Set'),
- ),
- CRM_Core_Action::DISABLE => array(
+ ],
+ CRM_Core_Action::DISABLE => [
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Price Set'),
- ),
- CRM_Core_Action::ENABLE => array(
+ ],
+ CRM_Core_Action::ENABLE => [
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Price Set'),
- ),
- CRM_Core_Action::DELETE => array(
+ ],
+ CRM_Core_Action::DELETE => [
'name' => ts('Delete'),
'url' => 'civicrm/admin/price',
'qs' => 'action=delete&reset=1&sid=%%sid%%',
'title' => ts('Delete Price Set'),
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
- ),
- CRM_Core_Action::COPY => array(
+ ],
+ CRM_Core_Action::COPY => [
'name' => ts('Copy Price Set'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=copy&sid=%%sid%%',
'title' => ts('Make a Copy of Price Set'),
'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"',
- ),
- );
+ ],
+ ];
}
return self::$_actionLinks;
}
@@ -168,12 +168,12 @@ public function run() {
$this->assign('usedPriceSetTitle', CRM_Price_BAO_PriceSet::getTitle($sid));
$this->assign('usedBy', $usedBy);
- $comps = array(
+ $comps = [
'Event' => 'civicrm_event',
'Contribution' => 'civicrm_contribution_page',
'EventTemplate' => 'civicrm_event_template',
- );
- $priceSetContexts = array();
+ ];
+ $priceSetContexts = [];
foreach ($comps as $name => $table) {
if (array_key_exists($table, $usedBy)) {
$priceSetContexts[] = $name;
@@ -224,7 +224,7 @@ public function edit($sid, $action) {
public function preview($sid) {
$controller = new CRM_Core_Controller_Simple('CRM_Price_Form_Preview', ts('Preview Price Set'), NULL);
$session = CRM_Core_Session::singleton();
- $context = CRM_Utils_Request::retrieve('context', 'String', $this);
+ $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
if ($context == 'field') {
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/price/field', "action=browse&sid={$sid}"));
}
@@ -247,12 +247,12 @@ public function preview($sid) {
*/
public function browse($action = NULL) {
// get all price sets
- $priceSet = array();
- $comps = array(
+ $priceSet = [];
+ $comps = [
'CiviEvent' => ts('Event'),
'CiviContribute' => ts('Contribution'),
'CiviMember' => ts('Membership'),
- );
+ ];
$dao = new CRM_Price_DAO_PriceSet();
if (CRM_Price_BAO_PriceSet::eventPriceSetDomainID()) {
@@ -261,13 +261,13 @@ public function browse($action = NULL) {
$dao->is_quick_config = 0;
$dao->find();
while ($dao->fetch()) {
- $priceSet[$dao->id] = array();
+ $priceSet[$dao->id] = [];
CRM_Core_DAO::storeValues($dao, $priceSet[$dao->id]);
$compIds = explode(CRM_Core_DAO::VALUE_SEPARATOR,
CRM_Utils_Array::value('extends', $priceSet[$dao->id])
);
- $extends = array();
+ $extends = [];
//CRM-10225
foreach ($compIds as $compId) {
if (!empty($comps[CRM_Core_Component::getComponentName($compId)])) {
@@ -294,10 +294,10 @@ public function browse($action = NULL) {
$actionLinks = self::actionLinks();
//CRM-10117
if ($dao->is_reserved) {
- $actionLinks[CRM_Core_Action::BROWSE]['name'] = 'View Price Fields';
+ $actionLinks[CRM_Core_Action::BROWSE]['name'] = ts('View Price Fields');
}
$priceSet[$dao->id]['action'] = CRM_Core_Action::formLink($actionLinks, $action,
- array('sid' => $dao->id),
+ ['sid' => $dao->id],
ts('more'),
FALSE,
'priceSet.row.actions',
diff --git a/CRM/Profile/Form.php b/CRM/Profile/Form.php
index 1b57c6380706..4c110de5d402 100644
--- a/CRM/Profile/Form.php
+++ b/CRM/Profile/Form.php
@@ -1,9 +1,9 @@
'unknown');
+ protected $_ufGroup = ['name' => 'unknown'];
/**
* The group id that we are passing in url.
@@ -79,7 +79,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Name of button for saving matching contacts.
- * @var
+ * @var string
*/
protected $_duplicateButtonName;
/**
@@ -113,6 +113,7 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Dedupe using a specific rule (CRM-6131).
* Not currently exposed in profile settings, but can be set in a buildForm hook.
+ * @var int
*/
public $_ruleGroupID = NULL;
@@ -137,8 +138,9 @@ class CRM_Profile_Form extends CRM_Core_Form {
/**
* Store profile ids if multiple profile ids are passed using comma separated.
* Currently lets implement this functionality only for dialog mode.
+ * @var array
*/
- protected $_profileIds = array();
+ protected $_profileIds = [];
/**
* Contact profile having activity fields?
@@ -179,6 +181,104 @@ class CRM_Profile_Form extends CRM_Core_Form {
protected $_currentUserID = NULL;
protected $_session = NULL;
+ /**
+ * Check for any duplicates.
+ *
+ * Depending on form settings & usage scenario we potentially use the found id,
+ * create links to found ids or add an error.
+ *
+ * @param array $errors
+ * @param array $fields
+ * @param CRM_Profile_Form $form
+ *
+ * @return array
+ */
+ protected static function handleDuplicateChecking(&$errors, $fields, $form) {
+ if ($form->_mode == CRM_Profile_Form::MODE_CREATE) {
+ // fix for CRM-2888
+ $exceptions = [];
+ }
+ else {
+ // for edit mode we need to allow our own record to be a dupe match!
+ $exceptions = [$form->_session->get('userID')];
+ }
+ $contactType = CRM_Core_BAO_UFGroup::getContactType($form->_gid);
+ // If all profile fields is of Contact Type then consider
+ // profile is of Individual type(default).
+ if (!$contactType) {
+ $contactType = 'Individual';
+ }
+
+ $ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
+ $fields, $contactType,
+ ($form->_context === 'dialog' ? 'Supervised' : 'Unsupervised'),
+ $exceptions,
+ FALSE,
+ $form->_ruleGroupID
+ );
+ if ($ids) {
+ if ($form->_isUpdateDupe == 2) {
+ CRM_Core_Session::setStatus(ts('Note: this contact may be a duplicate of an existing record.'), ts('Possible Duplicate Detected'), 'alert');
+ }
+ elseif ($form->_isUpdateDupe == 1) {
+ $form->_id = $ids[0];
+ }
+ else {
+ if ($form->_context == 'dialog') {
+ $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE);
+
+ $duplicateContactsLinks = '
';
+ $duplicateContactsLinks .= ts('One matching contact was found. ', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => '%count matching contacts were found. ',
+ ]);
+ if ($contactLinks['msg'] == 'view') {
+ $duplicateContactsLinks .= ts('You can View the existing contact.', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => 'You can View the existing contacts.',
+ ]);
+ }
+ else {
+ $duplicateContactsLinks .= ts('You can View or Edit the existing contact.', [
+ 'count' => count($contactLinks['rows']),
+ 'plural' => 'You can View or Edit the existing contacts.',
+ ]);
+ }
+ $duplicateContactsLinks .= '
' . ts('The body of the SMS cannot exceed %1 characters.', array(1 => CRM_SMS_Provider::MAX_SMS_CHAR)) . '
';
+ $dataErrors[] = '
' . ts('The body of the SMS cannot exceed %1 characters.', [1 => CRM_SMS_Provider::MAX_SMS_CHAR]) . '
';
}
if (!empty($dataErrors)) {
- $errors['textFile'] = ts('The following errors were detected in %1:', array(
+ $errors['textFile'] = ts('The following errors were detected in %1:', [
1 => $name,
- )) . '
' . implode('', $dataErrors) . '
';
+ ]) . '
' . implode('', $dataErrors) . '
';
}
}
diff --git a/CRM/SMS/Message.php b/CRM/SMS/Message.php
index 0d4289bf699d..c6b1557ca1d4 100644
--- a/CRM/SMS/Message.php
+++ b/CRM/SMS/Message.php
@@ -1,31 +1,30 @@
getMapper();
if ($ext->isExtensionKey($providerName)) {
- $paymentClass = $ext->keyToClass($providerName);
- require_once "{$paymentClass}.php";
+ $providerClass = $ext->keyToClass($providerName);
+ require_once "{$providerClass}.php";
}
else {
- CRM_Core_Error::fatal("Could not locate extension for {$providerName}.");
+ // If we are running unit tests we simulate an SMS provider with the name "CiviTestSMSProvider"
+ if ($providerName !== 'CiviTestSMSProvider') {
+ CRM_Core_Error::fatal("Could not locate extension for {$providerName}.");
+ }
+ $providerClass = 'CiviTestSMSProvider';
}
- self::$_singleton[$cacheKey] = $paymentClass::singleton($providerParams, $force);
+ self::$_singleton[$cacheKey] = $providerClass::singleton($providerParams, $force);
}
return self::$_singleton[$cacheKey];
}
@@ -158,12 +162,11 @@ public function createActivity($apiMsgID, $message, $headers = array(), $jobID =
return FALSE;
}
- $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS delivery', 'name');
// note: lets not pass status here, assuming status will be updated by callback
$activityParams = array(
'source_contact_id' => $sourceContactID,
'target_contact_id' => $headers['contact_id'],
- 'activity_type_id' => $activityTypeID,
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS delivery'),
'activity_date_time' => date('YmdHis'),
'details' => $message,
'result' => $apiMsgID,
@@ -186,7 +189,7 @@ public function retrieve($name, $type, $abort = TRUE, $default = NULL, $location
FALSE, $default, $location
);
if ($abort && $value === NULL) {
- CRM_Core_Error::debug_log_message("Could not find an entry for $name in $location");
+ Civi::log()->warning("Could not find an entry for $name in $location");
echo "Failure: Missing Parameter
";
exit();
}
@@ -215,7 +218,8 @@ public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
// find sender by phone number if $fromContactID not set by hook
$formatFrom = '%' . $this->formatPhone($this->stripPhone($message->from), $like, "like");
$message->fromContactID = CRM_Core_DAO::singleValueQuery("SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE %1", array(
- 1 => array($formatFrom, 'String')));
+ 1 => array($formatFrom, 'String'),
+ ));
}
if (!$message->fromContactID) {
@@ -251,7 +255,8 @@ public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
// find recipient if $toContactID not set by hook
if ($message->to) {
$message->toContactID = CRM_Core_DAO::singleValueQuery("SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE %1", array(
- 1 => array('%' . $message->to, 'String')));
+ 1 => array('%' . $message->to, 'String'),
+ ));
}
else {
$message->toContactID = $message->fromContactID;
@@ -259,16 +264,13 @@ public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
}
if ($message->fromContactID) {
- $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
- $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS');
-
// note: lets not pass status here, assuming status will be updated by callback
$activityParams = array(
'source_contact_id' => $message->toContactID,
'target_contact_id' => $message->fromContactID,
- 'activity_type_id' => $activityTypeID,
+ 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound SMS'),
'activity_date_time' => date('YmdHis'),
- 'status_id' => $actStatusIDs['Completed'],
+ 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
'details' => $message->body,
'phone_number' => $message->from,
);
@@ -277,7 +279,7 @@ public function processInbound($from, $body, $to = NULL, $trackID = NULL) {
}
$result = CRM_Activity_BAO_Activity::create($activityParams);
- CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$message->fromContactID}.");
+ Civi::log()->info("Inbound SMS recorded for cid={$message->fromContactID}.");
return $result;
}
}
diff --git a/CRM/SMS/StateMachine/Send.php b/CRM/SMS/StateMachine/Send.php
index 985b078c4f90..1d4646114fe1 100644
--- a/CRM/SMS/StateMachine/Send.php
+++ b/CRM/SMS/StateMachine/Send.php
@@ -1,9 +1,9 @@
_pages = array(
+ $this->_pages = [
'CRM_SMS_Form_Group' => NULL,
'CRM_SMS_Form_Upload' => NULL,
'CRM_SMS_Form_Schedule' => NULL,
- );
+ ];
$this->addSequentialPages($this->_pages, $action);
}
diff --git a/CRM/Tag/Form/Edit.php b/CRM/Tag/Form/Edit.php
index e8afa5838a5a..14b4adb6e124 100644
--- a/CRM/Tag/Form/Edit.php
+++ b/CRM/Tag/Form/Edit.php
@@ -1,9 +1,9 @@
$tag)), $bounceUrl);
+ CRM_Core_Error::statusBounce(ts("This tag cannot be deleted. You must delete all its child tags ('%1', etc) prior to deleting this tag.", [1 => $tag]), $bounceUrl);
}
if (!CRM_Core_Permission::check('administer reserved tags') && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Tag', $id, 'is_reserved')) {
CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to delete this reserved tag."), $bounceUrl);
}
}
if (count($this->_id) > 1) {
- $this->assign('delName', ts('%1 tags', array(1 => count($this->_id))));
+ $this->assign('delName', ts('%1 tags', [1 => count($this->_id)]));
}
}
else {
@@ -107,7 +107,7 @@ public function buildQuickForm() {
if (!$this->_isTagSet) {
if (!$isTagSetChild) {
$colorTags = CRM_Core_BAO_Tag::getColorTags(NULL, TRUE, $this->_id);
- $this->add('select2', 'parent_id', ts('Parent Tag'), $colorTags, FALSE, array('placeholder' => ts('- select -')));
+ $this->add('select2', 'parent_id', ts('Parent Tag'), $colorTags, FALSE, ['placeholder' => ts('- select -')]);
}
// Tagsets are not selectable by definition so only include the selectable field if NOT a tagset.
@@ -127,10 +127,10 @@ public function buildQuickForm() {
$this->add('text', 'name', ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'name'), TRUE
);
- $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', array(
- 'CRM_Core_DAO_Tag',
- $this->_id,
- ));
+ $this->addRule('name', ts('Name already exists in Database.'), 'objectExists', [
+ 'CRM_Core_DAO_Tag',
+ $this->_id,
+ ]);
$this->add('text', 'description', ts('Description'),
CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'description')
@@ -139,7 +139,7 @@ public function buildQuickForm() {
$isReserved = $this->add('checkbox', 'is_reserved', ts('Reserved?'));
if (!$isTagSetChild) {
- $this->addSelect('used_for', array('multiple' => TRUE, 'option_url' => NULL));
+ $this->addSelect('used_for', ['multiple' => TRUE, 'option_url' => NULL]);
}
$this->assign('adminTagset', $adminTagset);
@@ -162,7 +162,7 @@ public function setDefaultValues() {
$defaults = parent::setDefaultValues();
$cloneFrom = CRM_Utils_Request::retrieve('clone_from', 'Integer');
if (empty($this->_id) && $cloneFrom) {
- $params = array('id' => $cloneFrom);
+ $params = ['id' => $cloneFrom];
CRM_Core_BAO_Tag::retrieve($params, $this->_values);
$this->_values['name'] .= ' (' . ts('copy') . ')';
if (!empty($this->_values['is_reserved']) && !CRM_Core_Permission::check('administer reserved tags')) {
@@ -185,7 +185,7 @@ public function setDefaultValues() {
public function postProcess() {
if ($this->_action == CRM_Core_Action::DELETE) {
$deleted = 0;
- $tag = civicrm_api3('tag', 'getsingle', array('id' => $this->_id[0]));
+ $tag = civicrm_api3('tag', 'getsingle', ['id' => $this->_id[0]]);
foreach ($this->_id as $id) {
if (CRM_Core_BAO_Tag::del($id)) {
$deleted++;
@@ -193,14 +193,14 @@ public function postProcess() {
}
if (count($this->_id) == 1 && $deleted == 1) {
if ($tag['is_tagset']) {
- CRM_Core_Session::setStatus(ts("The tag set '%1' has been deleted.", array(1 => $tag['name'])), ts('Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The tag set '%1' has been deleted.", [1 => $tag['name']]), ts('Deleted'), 'success');
}
else {
- CRM_Core_Session::setStatus(ts("The tag '%1' has been deleted.", array(1 => $tag['name'])), ts('Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("The tag '%1' has been deleted.", [1 => $tag['name']]), ts('Deleted'), 'success');
}
}
else {
- CRM_Core_Session::setStatus(ts("Deleted %1 tags.", array(1 => $deleted)), ts('Deleted'), 'success');
+ CRM_Core_Session::setStatus(ts("Deleted %1 tags.", [1 => $deleted]), ts('Deleted'), 'success');
}
}
else {
@@ -233,7 +233,7 @@ public function postProcess() {
$params['is_selectable'] = 0;
}
$tag = CRM_Core_BAO_Tag::add($params);
- CRM_Core_Session::setStatus(ts("The tag '%1' has been saved.", array(1 => $tag->name)), ts('Saved'), 'success');
+ CRM_Core_Session::setStatus(ts("The tag '%1' has been saved.", [1 => $tag->name]), ts('Saved'), 'success');
$this->ajaxResponse['tag'] = $tag->toArray();
}
CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/tag'));
diff --git a/CRM/Tag/Form/Merge.php b/CRM/Tag/Form/Merge.php
index f6778083d0b1..67ef526fb430 100644
--- a/CRM/Tag/Form/Merge.php
+++ b/CRM/Tag/Form/Merge.php
@@ -1,9 +1,9 @@
_id) < 2) {
CRM_Core_Error::statusBounce(ts("You must select at least 2 tags for merging."), $url);
}
- $tags = civicrm_api3('Tag', 'get', array('id' => array('IN' => $this->_id), 'options' => array('limit' => 0)));
+ $tags = civicrm_api3('Tag', 'get', ['id' => ['IN' => $this->_id], 'options' => ['limit' => 0]]);
$this->_tags = $tags['values'];
if (count($this->_id) != count($this->_tags)) {
CRM_Core_Error::statusBounce(ts("Unknown tag."), $url);
@@ -66,19 +66,18 @@ public function buildQuickForm() {
$this->add('text', 'name', ts('Name of combined tag'), TRUE);
$this->assign('tags', CRM_Utils_Array::collect('name', $this->_tags));
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Merge'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- )
- );
+ ],
+ ]);
}
/**
@@ -88,9 +87,9 @@ public function buildQuickForm() {
*/
public function setDefaultValues() {
$primary = CRM_Utils_Array::first($this->_tags);
- return array(
+ return [
'name' => $primary['name'],
- );
+ ];
}
/**
@@ -106,7 +105,7 @@ public function postProcess() {
}
if ($params['name'] != $primary['name']) {
- civicrm_api3('Tag', 'create', array('id' => $primary['id'], 'name' => $params['name']));
+ civicrm_api3('Tag', 'create', ['id' => $primary['id'], 'name' => $params['name']]);
}
$key = array_search($params['name'], $deleted);
@@ -115,8 +114,8 @@ public function postProcess() {
}
CRM_Core_Session::setStatus(
- ts('All records previously tagged %1 are now tagged %2.', array(1 => implode(' ' . ts('or') . ' ', $deleted), 2 => $params['name'])),
- ts('%1 Tags Merged', array(1 => count($this->_id))),
+ ts('All records previously tagged %1 are now tagged %2.', [1 => implode(' ' . ts('or') . ' ', $deleted), 2 => $params['name']]),
+ ts('%1 Tags Merged', [1 => count($this->_id)]),
'success'
);
diff --git a/CRM/Tag/Form/Tag.php b/CRM/Tag/Form/Tag.php
index 231fb43db0a4..27e5048e21b4 100644
--- a/CRM/Tag/Form/Tag.php
+++ b/CRM/Tag/Form/Tag.php
@@ -1,9 +1,9 @@
$varValue) {
if (in_array($tagID, $entityTag)) {
- $tagAttribute = array(
+ $tagAttribute = [
'checked' => 'checked',
'id' => "tag_{$tagID}",
- );
+ ];
}
else {
- $tagAttribute = array(
+ $tagAttribute = [
'id' => "tag_{$tagID}",
- );
+ ];
}
$tagChk[$tagID] = $this->createElement('checkbox', $tagID, '', '', $tagAttribute);
@@ -113,7 +113,7 @@ public function buildQuickForm() {
* @return void
*/
public function postProcess() {
- CRM_Utils_System::flushCache('CRM_Core_DAO_Tag');
+ CRM_Utils_System::flushCache();
// array contains the posted values
// exportvalues is not used because its give value 1 of the checkbox which were checked by default,
diff --git a/CRM/Tag/Page/Tag.php b/CRM/Tag/Page/Tag.php
index 1c98beca0462..11d899a511f9 100644
--- a/CRM/Tag/Page/Tag.php
+++ b/CRM/Tag/Page/Tag.php
@@ -1,9 +1,9 @@
addScriptFile('civicrm', 'bower_components/jstree/dist/jstree.min.js', 0, 'html-header')
->addStyleFile('civicrm', 'bower_components/jstree/dist/themes/default/style.min.css')
- ->addPermissions(array('administer reserved tags', 'administer Tagsets'));
+ ->addPermissions(['administer reserved tags', 'administer Tagsets']);
- $usedFor = $tagsets = array();
+ $usedFor = $tagsets = [];
- $result = civicrm_api3('OptionValue', 'get', array(
- 'return' => array("value", "name"),
+ $result = civicrm_api3('OptionValue', 'get', [
+ 'return' => ["value", "name"],
'option_group_id' => "tag_used_for",
- ));
+ ]);
foreach ($result['values'] as $value) {
$usedFor[$value['value']] = $value['name'];
}
- $result = civicrm_api3('Tag', 'get', array(
- 'return' => array("name", "used_for", "description", "created_id.display_name", "created_date", "is_reserved"),
+ $result = civicrm_api3('Tag', 'get', [
+ 'return' => ["name", "used_for", "description", "created_id.display_name", "created_date", "is_reserved"],
'is_tagset' => 1,
- 'options' => array('limit' => 0),
- ));
+ 'options' => ['limit' => 0],
+ ]);
foreach ($result['values'] as $id => $tagset) {
$used = explode(',', CRM_Utils_Array::value('used_for', $tagset, ''));
$tagset['used_for_label'] = array_values(array_intersect_key($usedFor, array_flip($used)));
diff --git a/CRM/UF/Form/AbstractPreview.php b/CRM/UF/Form/AbstractPreview.php
index 3e41c2c12ac7..d0b0889b0392 100644
--- a/CRM/UF/Form/AbstractPreview.php
+++ b/CRM/UF/Form/AbstractPreview.php
@@ -1,9 +1,9 @@
_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name'])) {
CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, NULL, CRM_Profile_Form::MODE_REGISTER);
@@ -111,6 +111,7 @@ public function buildQuickForm() {
*
* @return string
*/
+
/**
* @return string
*/
diff --git a/CRM/UF/Form/AdvanceSetting.php b/CRM/UF/Form/AdvanceSetting.php
index 28a6c62d30e5..7caff1af5dea 100644
--- a/CRM/UF/Form/AdvanceSetting.php
+++ b/CRM/UF/Form/AdvanceSetting.php
@@ -1,9 +1,9 @@
assign('advancedFieldsConverted', $entityFields);
+
// should mapping be enabled for this group
$form->addElement('checkbox', 'is_map', ts('Enable mapping for this profile?'));
// should we allow updates on a exisitng contact
- $options = array();
+ $options = [];
$options[] = $form->createElement('radio', NULL, NULL, ts('Issue warning and do not save'), 0);
$options[] = $form->createElement('radio', NULL, NULL, ts('Update the matching contact'), 1);
$options[] = $form->createElement('radio', NULL, NULL, ts('Allow duplicate contact to be created'), 2);
@@ -50,10 +56,12 @@ public static function buildAdvanceSetting(&$form) {
$form->addGroup($options, 'is_update_dupe', ts('What to do upon duplicate match'));
// we do not have any url checks to allow relative urls
$form->addElement('text', 'post_URL', ts('Redirect URL'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFGroup', 'post_URL'));
+
+ $form->add('advcheckbox', 'add_cancel_button', ts('Include Cancel Button?'));
$form->addElement('text', 'cancel_URL', ts('Cancel Redirect URL'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFGroup', 'cancel_URL'));
// add select for groups
- $group = array('' => ts('- select -')) + $form->_group;
+ $group = ['' => ts('- select -')] + $form->_group;
$form->_groupElement = &$form->addElement('select', 'group', ts('Limit listings to a specific Group?'), $group);
//add notify field
@@ -70,7 +78,7 @@ public static function buildAdvanceSetting(&$form) {
// should we display a link to the website profile
$config = CRM_Core_Config::singleton();
- $form->addElement('checkbox', 'is_uf_link', ts('Include %1 user account information links in search results?', array(1 => $config->userFramework)));
+ $form->addElement('checkbox', 'is_uf_link', ts('Include %1 user account information links in search results?', [1 => $config->userFramework]));
// want to create cms user
$session = CRM_Core_Session::singleton();
@@ -79,15 +87,15 @@ public static function buildAdvanceSetting(&$form) {
$form->_cmsId = TRUE;
}
- $options = array();
+ $options = [];
$options[] = $form->createElement('radio', NULL, NULL, ts('No account create option'), 0);
$options[] = $form->createElement('radio', NULL, NULL, ts('Give option, but not required'), 1);
$options[] = $form->createElement('radio', NULL, NULL, ts('Account creation required'), 2);
- $form->addGroup($options, 'is_cms_user', ts('%1 user account registration option?', array(1 => $config->userFramework)));
+ $form->addGroup($options, 'is_cms_user', ts('%1 user account registration option?', [1 => $config->userFramework]));
// options for including Proximity Search in the profile search form
- $proxOptions = array();
+ $proxOptions = [];
$proxOptions[] = $form->createElement('radio', NULL, NULL, ts('None'), 0);
$proxOptions[] = $form->createElement('radio', NULL, NULL, ts('Optional'), 1);
$proxOptions[] = $form->createElement('radio', NULL, NULL, ts('Required'), 2);
diff --git a/CRM/UF/Form/Field.php b/CRM/UF/Form/Field.php
index 35bd5f45d2c5..8640d593f07e 100644
--- a/CRM/UF/Form/Field.php
+++ b/CRM/UF/Form/Field.php
@@ -1,9 +1,9 @@
pushUserContext($url);
- $breadCrumb = array(
- array(
+ $breadCrumb = [
+ [
'title' => ts('CiviCRM Profile Fields'),
'url' => $url,
- ),
- );
+ ],
+ ];
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
@@ -149,7 +149,7 @@ public function preProcess() {
$this->_fields = array_merge($this->_fields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
- $this->_selectFields = array();
+ $this->_selectFields = [];
foreach ($this->_fields as $name => $field) {
// lets skip note for now since we dont support it
if ($name == 'note') {
@@ -182,30 +182,31 @@ public function preProcess() {
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
- $this->addButtons(array(
- array(
+ $this->addButtons([
+ [
'type' => 'next',
'name' => ts('Delete Profile Field'),
'spacing' => ' ',
'isDefault' => TRUE,
- ),
- array(
+ ],
+ [
'type' => 'cancel',
'name' => ts('Cancel'),
- ),
- ));
+ ],
+ ]);
return;
}
+ $addressCustomFields = array_keys(CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
if (isset($this->_id)) {
- $params = array('id' => $this->_id);
+ $params = ['id' => $this->_id];
CRM_Core_BAO_UFField::retrieve($params, $defaults);
// set it to null if so (avoids crappy E_NOTICE errors below
$defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults);
- $specialFields = CRM_Core_BAO_UFGroup::getLocationFields();
-
+ //CRM-20861 - Include custom fields defined for address to set its default location type to 0.
+ $specialFields = array_merge(CRM_Core_BAO_UFGroup::getLocationFields(), $addressCustomFields);
if (!$defaults['location_type_id'] &&
$defaults["field_type"] != "Formatting" &&
in_array($defaults['field_name'], $specialFields)
@@ -213,12 +214,12 @@ public function buildQuickForm() {
$defaults['location_type_id'] = 0;
}
- $defaults['field_name'] = array(
+ $defaults['field_name'] = [
$defaults['field_type'],
($defaults['field_type'] == "Formatting" ? "" : $defaults['field_name']),
($defaults['field_name'] == "url") ? $defaults['website_type_id'] : $defaults['location_type_id'],
CRM_Utils_Array::value('phone_type_id', $defaults),
- );
+ ];
$this->_gid = $defaults['uf_group_id'];
}
else {
@@ -229,7 +230,7 @@ public function buildQuickForm() {
$this->assign('otherModules', $otherModules);
if ($this->_action & CRM_Core_Action::ADD) {
- $fieldValues = array('uf_group_id' => $this->_gid);
+ $fieldValues = ['uf_group_id' => $this->_gid];
$defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues);
}
@@ -244,8 +245,7 @@ public function buildQuickForm() {
$fields = CRM_Core_BAO_UFField::getAvailableFields($this->_gid, $defaults);
- $noSearchable = $hasWebsiteTypes = array();
- $addressCustomFields = array_keys(CRM_Core_BAO_CustomField::getFieldsForImport('Address'));
+ $noSearchable = $hasWebsiteTypes = [];
foreach ($fields as $key => $value) {
foreach ($value as $key1 => $value1) {
@@ -290,20 +290,20 @@ public function buildQuickForm() {
if ($defaultLocationType) {
$defaultLocation = $this->_location_types[$defaultLocationType->id];
unset($this->_location_types[$defaultLocationType->id]);
- $this->_location_types = array(
+ $this->_location_types = [
$defaultLocationType->id => $defaultLocation,
- ) + $this->_location_types;
+ ] + $this->_location_types;
}
- $this->_location_types = array('Primary') + $this->_location_types;
+ $this->_location_types = ['Primary'] + $this->_location_types;
// since we need a hierarchical list to display contact types & subtypes,
// this is what we going to display in first selector
$contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
unset($contactTypes['']);
- $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
- $sel1 = array('' => '- select -') + $contactTypes;
+ $contactTypes = !empty($contactTypes) ? ['Contact' => 'Contacts'] + $contactTypes : [];
+ $sel1 = ['' => '- select -'] + $contactTypes;
if (!empty($fields['Activity'])) {
$sel1['Activity'] = 'Activity';
@@ -365,7 +365,7 @@ public function buildQuickForm() {
}
}
- $this->_defaults = array();
+ $this->_defaults = [];
$js = "@siu',
'@
@siu',
@@ -113,8 +104,8 @@ public static function html2pdf(&$text, $fileName = 'civicrm.pdf', $output = FAL
'@]*?>@siu',
'@@siu',
'@]*?>@siu',
- );
- $htmlElementsInstead = array('', '', '', '', '', '');
+ ];
+ $htmlElementsInstead = ['', '', '', '', '', ''];
foreach ($pages as & $page) {
$page = preg_replace($htmlElementstoStrip,
$htmlElementsInstead,
@@ -127,12 +118,11 @@ public static function html2pdf(&$text, $fileName = 'civicrm.pdf', $output = FAL
";
- if ($config->wkhtmltopdfPath) {
+ if (CRM_Core_Config::singleton()->wkhtmltopdfPath) {
return self::_html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName);
}
else {
return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
- //return self::_html2pdf_tcpdf($paper_size, $orientation, $margins, $html, $output, $fileName, $stationery_path);
}
}
@@ -152,9 +142,10 @@ public static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $htm
// This function also uses the FPDI library documented at: http://www.setasign.com/products/fpdi/about/
// Syntax borrowed from https://github.com/jake-mw/CDNTaxReceipts/blob/master/cdntaxreceipts.functions.inc
require_once 'tcpdf/tcpdf.php';
- require_once 'FPDI/fpdi.php'; // This library is only in the 'packages' area as of version 4.5
+ // This library is only in the 'packages' area as of version 4.5
+ require_once 'FPDI/fpdi.php';
- $paper_size_arr = array($paper_size[2], $paper_size[3]);
+ $paper_size_arr = [$paper_size[2], $paper_size[3]];
$pdf = new TCPDF($orientation, 'pt', $paper_size_arr);
$pdf->Open();
@@ -189,7 +180,7 @@ public static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $htm
$pdf->Close();
$pdf_file = 'CiviLetter' . '.pdf';
$pdf->Output($pdf_file, 'D');
- CRM_Utils_System::civiExit(1);
+ CRM_Utils_System::civiExit();
}
/**
diff --git a/CRM/Utils/Pager.php b/CRM/Utils/Pager.php
index bd33490a8361..390764d766ac 100644
--- a/CRM/Utils/Pager.php
+++ b/CRM/Utils/Pager.php
@@ -1,9 +1,9 @@
$start, 2 => $end, 3 => $params['total']));
+ $statusMessage = ts('%1 - %2 of %3', [1 => $start, 2 => $end, 3 => $params['total']]);
}
$params['status'] = str_replace('%%StatusMessage%%', $statusMessage, $params['status']);
- $this->_response = array(
+ $this->_response = [
'first' => $this->getFirstPageLink(),
'back' => $this->getBackPageLink(),
'next' => $this->getNextPageLink(),
@@ -104,21 +104,21 @@ public function __construct($params) {
'buttonTop' => CRM_Utils_Array::value('buttonTop', $params),
'buttonBottom' => CRM_Utils_Array::value('buttonBottom', $params),
'currentLocation' => $this->getCurrentLocation(),
- );
+ ];
/**
* A page cannot have two variables with the same form name. Hence in the
* pager display, we have a form submission at the top with the normal
* page variable, but a different form element for one at the bottom.
*/
- $this->_response['titleTop'] = ts('Page %1 of %2', array(
- 1 => '',
- 2 => $this->_response['numPages'],
- ));
- $this->_response['titleBottom'] = ts('Page %1 of %2', array(
- 1 => '',
- 2 => $this->_response['numPages'],
- ));
+ $this->_response['titleTop'] = ts('Page %1 of %2', [
+ 1 => '',
+ 2 => $this->_response['numPages'],
+ ]);
+ $this->_response['titleBottom'] = ts('Page %1 of %2', [
+ 1 => '',
+ 2 => $this->_response['numPages'],
+ ]);
}
/**
@@ -148,8 +148,8 @@ public function initialize(&$params) {
$params['separator'] = '';
$params['spacesBeforeSeparator'] = 1;
$params['spacesAfterSeparator'] = 1;
- $params['extraVars'] = array('force' => 1);
- $params['excludeVars'] = array('reset', 'snippet', 'section');
+ $params['extraVars'] = ['force' => 1];
+ $params['excludeVars'] = ['reset', 'snippet', 'section'];
// set previous and next text labels
$params['prevImg'] = ' ' . ts('< Previous');
@@ -248,7 +248,7 @@ public function getOffsetAndRowCount() {
$offset = ($pageId - 1) * $this->_perPage;
- return array($offset, $this->_perPage);
+ return [$offset, $this->_perPage];
}
/**
diff --git a/CRM/Utils/PagerAToZ.php b/CRM/Utils/PagerAToZ.php
index 3c605e6edee4..32da0ee8cc46 100644
--- a/CRM/Utils/PagerAToZ.php
+++ b/CRM/Utils/PagerAToZ.php
@@ -1,9 +1,9 @@
fetch()) {
- $dynamicAlphabets[] = $result->sort_name;
+ $dynamicAlphabets[] = strtoupper($result->sort_name);
}
return $dynamicAlphabets;
}
@@ -156,13 +156,13 @@ public static function createLinks(&$query, $sortByCharacter, $isDAO) {
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $emptyVariable, FALSE, NULL, $_REQUEST);
}
- $aToZBar = array();
+ $aToZBar = [];
foreach ($AToZBar as $key => $link) {
if ($link === NULL) {
continue;
}
- $element = array();
+ $element = [];
if (in_array($link, $dynamicAlphabets)) {
$klass = '';
if ($link == $sortByCharacter) {
@@ -193,7 +193,7 @@ public static function createLinks(&$query, $sortByCharacter, $isDAO) {
),
ts('All')
);
- $aToZBar[] = array('item' => $url);
+ $aToZBar[] = ['item' => $url];
return $aToZBar;
}
diff --git a/CRM/Utils/PseudoConstant.php b/CRM/Utils/PseudoConstant.php
index 6ffc725adfcc..7a3cf0d54768 100644
--- a/CRM/Utils/PseudoConstant.php
+++ b/CRM/Utils/PseudoConstant.php
@@ -1,9 +1,9 @@
hasDeclaredIndex($tableName, $columns)
) {
$formattedQuery = $this->format($queryText, CRM_Utils_QueryFormatter::LANG_SQL_FTSBOOL);
- $prefixedFieldNames = array();
+ $prefixedFieldNames = [];
foreach ($columns as $fieldName) {
$prefixedFieldNames[] = "$tableAlias.$fieldName";
}
@@ -287,8 +290,8 @@ protected function _formatFts($text, $mode) {
*/
protected function _formatFtsBool($text, $mode) {
$result = NULL;
- $operators = array('+', '-', '~', '(', ')');
- $wildCards = array('@', '%', '*');
+ $operators = ['+', '-', '~', '(', ')'];
+ $wildCards = ['@', '%', '*'];
$expression = preg_quote(implode('', array_merge($operators, $wildCards)), '/');
//Return if searched string ends with an unsupported operator.
@@ -399,7 +402,7 @@ protected function _formatLike($text, $mode) {
* @return string
*/
protected function mapWords($text, $template, $quotes = FALSE) {
- $result = array();
+ $result = [];
foreach ($this->parseWords($text, $quotes) as $word) {
$result[] = str_replace('word', $word, $template);
}
@@ -407,8 +410,8 @@ protected function mapWords($text, $template, $quotes = FALSE) {
}
/**
- * @param $text
- * @bool $quotes
+ * @param string $text
+ * @param bool $quotes
* @return array
*/
protected function parseWords($text, $quotes) {
@@ -458,13 +461,13 @@ protected function dedupeWildcards($text, $wildcard) {
* @return array
*/
public static function getModes() {
- return array(
+ return [
self::MODE_NONE,
self::MODE_PHRASE,
self::MODE_WILDPHRASE,
self::MODE_WILDWORDS,
self::MODE_WILDWORDS_SUFFIX,
- );
+ ];
}
/**
@@ -473,12 +476,12 @@ public static function getModes() {
* @return array
*/
public static function getLanguages() {
- return array(
+ return [
self::LANG_SOLR,
self::LANG_SQL_FTS,
self::LANG_SQL_FTSBOOL,
self::LANG_SQL_LIKE,
- );
+ ];
}
/**
diff --git a/CRM/Utils/REST.php b/CRM/Utils/REST.php
index bd88f4202714..b1df33aee17c 100644
--- a/CRM/Utils/REST.php
+++ b/CRM/Utils/REST.php
@@ -1,9 +1,9 @@
get('key');
// $session->set( 'key', $var );
- return self::simple(array('message' => "PONG: $key"));
+ return self::simple(['message' => "PONG: $key"]);
}
/**
@@ -78,10 +80,10 @@ public static function ping($var = NULL) {
* @return array
*/
public static function error($message = 'Unknown Error') {
- $values = array(
+ $values = [
'error_message' => $message,
'is_error' => 1,
- );
+ ];
return $values;
}
@@ -92,7 +94,7 @@ public static function error($message = 'Unknown Error') {
* @return array
*/
public static function simple($params) {
- $values = array('is_error' => 0);
+ $values = ['is_error' => 0];
$values += $params;
return $values;
}
@@ -129,7 +131,7 @@ public static function output(&$result) {
if (!$result) {
$result = 0;
}
- $result = self::simple(array('result' => $result));
+ $result = self::simple(['result' => $result]);
}
elseif (is_array($result)) {
if (CRM_Utils_Array::isHierarchical($result)) {
@@ -146,6 +148,7 @@ public static function output(&$result) {
if (!empty($requestParams['json'])) {
if (!empty($requestParams['prettyprint'])) {
// Don't set content-type header for api explorer output
+ return json_encode(array_merge($result), JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE);
return self::jsonFormated(array_merge($result));
}
CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
@@ -181,100 +184,6 @@ public static function output(&$result) {
return $xml;
}
- /**
- * @param $data
- *
- * @deprecated - switch to native JSON_PRETTY_PRINT when we drop support for php 5.3
- *
- * @return string
- */
- public static function jsonFormated($data) {
- // If php is 5.4+ we can use the native method
- if (defined('JSON_PRETTY_PRINT')) {
- return json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE);
- }
-
- // PHP 5.3 shim
- $json = str_replace('\/', '/', json_encode($data));
- $tabcount = 0;
- $result = '';
- $inquote = FALSE;
- $inarray = FALSE;
- $ignorenext = FALSE;
-
- $tab = "\t";
- $newline = "\n";
-
- for ($i = 0; $i < strlen($json); $i++) {
- $char = $json[$i];
-
- if ($ignorenext) {
- $result .= $char;
- $ignorenext = FALSE;
- }
- else {
- switch ($char) {
- case '{':
- if ($inquote) {
- $result .= $char;
- }
- else {
- $inarray = FALSE;
- $tabcount++;
- $result .= $char . $newline . str_repeat($tab, $tabcount);
- }
- break;
-
- case '}':
- if ($inquote) {
- $result .= $char;
- }
- else {
- $tabcount--;
- $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
- }
- break;
-
- case ',':
- if ($inquote || $inarray) {
- $result .= $char;
- }
- else {
- $result .= $char . $newline . str_repeat($tab, $tabcount);
- }
- break;
-
- case '"':
- $inquote = !$inquote;
- $result .= $char;
- break;
-
- case '\\':
- if ($inquote) {
- $ignorenext = TRUE;
- }
- $result .= $char;
- break;
-
- case '[':
- $inarray = TRUE;
- $result .= $char;
- break;
-
- case ']':
- $inarray = FALSE;
- $result .= $char;
- break;
-
- default:
- $result .= $char;
- }
- }
- }
-
- return $result;
- }
-
/**
* @return array|int
*/
@@ -309,7 +218,7 @@ public static function handle() {
}
else {
// or the api format (entity+action)
- $args = array();
+ $args = [];
$args[0] = 'civicrm';
$args[1] = CRM_Utils_Array::value('entity', $requestParams);
$args[2] = CRM_Utils_Array::value('action', $requestParams);
@@ -370,7 +279,7 @@ public static function process(&$args, $params) {
return self::error('Unknown function invocation.');
}
- return call_user_func(array($params['className'], $params['fnName']), $params);
+ return call_user_func([$params['className'], $params['fnName']], $params);
}
if (!array_key_exists('version', $params)) {
@@ -385,22 +294,25 @@ public static function process(&$args, $params) {
}
if ($_SERVER['REQUEST_METHOD'] == 'GET' &&
- strtolower(substr($args[2], 0, 3)) != 'get' &&
- strtolower($args[2] != 'check')) {
+ strtolower(substr($args[2], 0, 3)) != 'get' &&
+ strtolower($args[2] != 'check')) {
// get only valid for non destructive methods
require_once 'api/v3/utils.php';
return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.",
- array(
+ [
'IP' => $_SERVER['REMOTE_ADDR'],
'level' => 'security',
'referer' => $_SERVER['HTTP_REFERER'],
'reason' => 'Destructive HTTP GET',
- )
+ ]
);
}
// trap all fatal errors
- $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal'));
+ $errorScope = CRM_Core_TemporaryErrorScope::create([
+ 'CRM_Utils_REST',
+ 'fatal',
+ ]);
$result = civicrm_api($args[1], $args[2], $params);
unset($errorScope);
@@ -415,21 +327,25 @@ public static function process(&$args, $params) {
*/
public static function &buildParamList() {
$requestParams = CRM_Utils_Request::exportValues();
- $params = array();
+ $params = [];
- $skipVars = array(
+ $skipVars = [
'q' => 1,
'json' => 1,
'key' => 1,
'api_key' => 1,
'entity' => 1,
'action' => 1,
- );
+ ];
if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") {
$params = json_decode($requestParams['json'], TRUE);
if ($params === NULL) {
- CRM_Utils_JSON::output(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.'));
+ CRM_Utils_JSON::output([
+ 'is_error' => 1,
+ 0 => 'error_message',
+ 1 => 'Unable to decode supplied JSON.',
+ ]);
}
}
foreach ($requestParams as $n => $v) {
@@ -450,7 +366,7 @@ public static function &buildParamList() {
*/
public static function fatal($pearError) {
CRM_Utils_System::setHttpHeader('Content-Type', 'text/xml');
- $error = array();
+ $error = [];
$error['code'] = $pearError->getCode();
$error['error_message'] = $pearError->getMessage();
$error['mode'] = $pearError->getMode();
@@ -471,7 +387,7 @@ public static function fatal($pearError) {
public static function loadTemplate() {
$request = CRM_Utils_Request::retrieve('q', 'String');
if (FALSE !== strpos($request, '..')) {
- die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
+ die("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org");
}
$request = explode('/', $request);
@@ -483,15 +399,17 @@ public static function loadTemplate() {
CRM_Utils_System::setTitle("$entity::$tplfile inline $tpl");
if (!$smarty->template_exists($tpl)) {
CRM_Utils_System::setHttpHeader("Status", "404 Not Found");
- die ("Can't find the requested template file templates/$tpl");
+ die("Can't find the requested template file templates/$tpl");
}
- if (array_key_exists('id', $_GET)) {// special treatmenent, because it's often used
- $smarty->assign('id', (int) $_GET['id']);// an id is always positive
+ // special treatmenent, because it's often used
+ if (array_key_exists('id', $_GET)) {
+ // an id is always positive
+ $smarty->assign('id', (int) $_GET['id']);
}
$pos = strpos(implode(array_keys($_GET)), '<');
if ($pos !== FALSE) {
- die ("SECURITY FATAL: one of the param names contains <");
+ die("SECURITY FATAL: one of the param names contains <");
}
$param = array_map('htmlentities', $_GET);
unset($param['q']);
@@ -537,12 +455,12 @@ public static function ajaxJson() {
)
) {
$error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
- array(
+ [
'IP' => $_SERVER['REMOTE_ADDR'],
'level' => 'security',
'referer' => $_SERVER['HTTP_REFERER'],
'reason' => 'CSRF suspected',
- )
+ ]
);
CRM_Utils_JSON::output($error);
}
@@ -558,21 +476,25 @@ public static function ajaxJson() {
$entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams));
$action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams));
if (!is_array($params)) {
- CRM_Utils_JSON::output(array(
- 'is_error' => 1,
- 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}',
- ));
+ CRM_Utils_JSON::output([
+ 'is_error' => 1,
+ 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}',
+ ]);
}
$params['check_permissions'] = TRUE;
$params['version'] = 3;
- $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
+ // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions
+ $_GET['json'] = $requestParams['json'] = 1;
if (!$params['sequential']) {
$params['sequential'] = 1;
}
// trap all fatal errors
- $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal'));
+ $errorScope = CRM_Core_TemporaryErrorScope::create([
+ 'CRM_Utils_REST',
+ 'fatal',
+ ]);
$result = civicrm_api($entity, $action, $params);
unset($errorScope);
@@ -600,12 +522,12 @@ public static function ajax() {
) {
require_once 'api/v3/utils.php';
$error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().",
- array(
+ [
'IP' => $_SERVER['REMOTE_ADDR'],
'level' => 'security',
'referer' => $_SERVER['HTTP_REFERER'],
'reason' => 'CSRF suspected',
- )
+ ]
);
CRM_Utils_JSON::output($error);
}
@@ -615,11 +537,14 @@ public static function ajax() {
$entity = CRM_Utils_Array::value('entity', $requestParams);
$action = CRM_Utils_Array::value('action', $requestParams);
if (!$entity || !$action) {
- $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1);
+ $err = [
+ 'error_message' => 'missing mandatory params "entity=" or "action="',
+ 'is_error' => 1,
+ ];
echo self::output($err);
CRM_Utils_System::civiExit();
}
- $args = array('civicrm', $entity, $action);
+ $args = ['civicrm', $entity, $action];
}
else {
$args = explode('/', $q);
@@ -651,14 +576,14 @@ public static function ajax() {
* @return array
*/
public static function processMultiple() {
- $output = array();
+ $output = [];
foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) {
- $args = array(
+ $args = [
'civicrm',
$call[0],
$call[1],
- );
- $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, array()));
+ ];
+ $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, []));
}
return $output;
}
@@ -676,8 +601,9 @@ public function loadCMSBootstrap() {
// Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping"
if (!empty($q)) {
if (count($args) == 2 && $args[1] == 'ping') {
- CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE);
- return NULL; // this is pretty wonky but maybe there's some reason I can't see
+ CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
+ // this is pretty wonky but maybe there's some reason I can't see
+ return NULL;
}
if (count($args) != 3) {
return self::error('ERROR: Malformed REST path');
@@ -692,7 +618,7 @@ public function loadCMSBootstrap() {
// FIXME: At time of writing, this doesn't actually do anything because
// authenticateKey abends, but that's a bad behavior which sends a
// malformed response.
- CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE);
+ CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
return self::error('Failed to authenticate key');
}
@@ -701,7 +627,7 @@ public function loadCMSBootstrap() {
$store = NULL;
$api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST');
if (empty($api_key)) {
- CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE);
+ CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
return self::error("FATAL: mandatory param 'api_key' (user key) missing");
}
$contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key');
@@ -711,17 +637,17 @@ public function loadCMSBootstrap() {
}
if ($uid && $contact_id) {
- CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE);
+ CRM_Utils_System::loadBootStrap(['uid' => $uid], TRUE, FALSE);
$session = CRM_Core_Session::singleton();
$session->set('ufID', $uid);
$session->set('userID', $contact_id);
CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
- array(1 => array($contact_id, 'Integer'))
+ [1 => [$contact_id, 'Integer']]
);
return NULL;
}
else {
- CRM_Utils_System::loadBootStrap(array(), FALSE, FALSE);
+ CRM_Utils_System::loadBootStrap([], FALSE, FALSE);
return self::error('ERROR: No CMS user associated with given api-key');
}
}
diff --git a/CRM/Utils/ReCAPTCHA.php b/CRM/Utils/ReCAPTCHA.php
index aa27d26dd6ba..31980430149b 100644
--- a/CRM/Utils/ReCAPTCHA.php
+++ b/CRM/Utils/ReCAPTCHA.php
@@ -1,9 +1,9 @@
recaptchaPublicKey == NULL || $config->recaptchaPublicKey == "") {
+ return FALSE;
+ }
+ return TRUE;
+ }
+
+ /**
+ * Check if reCaptcha has to be added on form forcefully.
+ */
+ public static function hasToAddForcefully() {
+ $config = CRM_Core_Config::singleton();
+ if (!$config->forceRecaptcha) {
+ return FALSE;
+ }
+ return TRUE;
+ }
+
/**
* Add element to form.
*
@@ -75,11 +97,10 @@ public static function add(&$form) {
require_once 'packages/recaptcha/recaptchalib.php';
}
- // See if we are using SSL
- if (CRM_Utils_System::isSSL()) {
- $useSSL = TRUE;
- }
- $html = recaptcha_get_html($config->recaptchaPublicKey, $error, $useSSL);
+ // Load the Recaptcha api.js over HTTPS
+ $useHTTPS = TRUE;
+
+ $html = recaptcha_get_html($config->recaptchaPublicKey, $error, $useHTTPS);
$form->assign('recaptchaHTML', $html);
$form->assign('recaptchaOptions', $config->recaptchaOptions);
diff --git a/CRM/Utils/Recent.php b/CRM/Utils/Recent.php
index 75109d74edf9..55ccf47b4b5c 100644
--- a/CRM/Utils/Recent.php
+++ b/CRM/Utils/Recent.php
@@ -1,9 +1,9 @@
get(self::STORE_NAME);
if (!self::$_recent) {
- self::$_recent = array();
+ self::$_recent = [];
}
}
}
@@ -104,7 +104,7 @@ public static function add(
$type,
$contactId,
$contactName,
- $others = array()
+ $others = []
) {
self::initialize();
@@ -116,7 +116,7 @@ public static function add(
// make sure item is not already present in list
for ($i = 0; $i < count(self::$_recent); $i++) {
- if (self::$_recent[$i]['url'] == $url) {
+ if (self::$_recent[$i]['type'] === $type && self::$_recent[$i]['id'] == $id) {
// delete item from array
array_splice(self::$_recent, $i, 1);
break;
@@ -124,11 +124,11 @@ public static function add(
}
if (!is_array($others)) {
- $others = array();
+ $others = [];
}
array_unshift(self::$_recent,
- array(
+ [
'title' => $title,
'url' => $url,
'id' => $id,
@@ -140,7 +140,7 @@ public static function add(
'image_url' => CRM_Utils_Array::value('imageUrl', $others),
'edit_url' => CRM_Utils_Array::value('editUrl', $others),
'delete_url' => CRM_Utils_Array::value('deleteUrl', $others),
- )
+ ]
);
if (count(self::$_recent) > self::$_maxItems) {
@@ -162,7 +162,7 @@ public static function del($recentItem) {
self::initialize();
$tempRecent = self::$_recent;
- self::$_recent = array();
+ self::$_recent = [];
// make sure item is not already present in list
for ($i = 0; $i < count($tempRecent); $i++) {
@@ -174,6 +174,7 @@ public static function del($recentItem) {
}
}
+ CRM_Utils_Hook::recent(self::$_recent);
$session = CRM_Core_Session::singleton();
$session->set(self::STORE_NAME, self::$_recent);
}
@@ -189,7 +190,7 @@ public static function delContact($id) {
$tempRecent = self::$_recent;
- self::$_recent = array();
+ self::$_recent = [];
// rebuild recent.
for ($i = 0; $i < count($tempRecent); $i++) {
@@ -200,15 +201,17 @@ public static function delContact($id) {
self::$_recent[] = $tempRecent[$i];
}
+ CRM_Utils_Hook::recent(self::$_recent);
$session = CRM_Core_Session::singleton();
$session->set(self::STORE_NAME, self::$_recent);
}
/**
* Check if a provider is allowed to add stuff.
- * If correspondig setting is empty, all are allowed
+ * If corresponding setting is empty, all are allowed
*
* @param string $providerName
+ * @return bool
*/
public static function isProviderEnabled($providerName) {
@@ -230,9 +233,11 @@ public static function isProviderEnabled($providerName) {
/**
* Gets the list of available providers to civi's recent items stack
+ *
+ * @return array
*/
public static function getProviders() {
- $providers = array(
+ $providers = [
'Contact' => ts('Contacts'),
'Relationship' => ts('Relationships'),
'Activity' => ts('Activities'),
@@ -246,7 +251,7 @@ public static function getProviders() {
'Pledge' => ts('Pledges'),
'Event' => ts('Events'),
'Campaign' => ts('Campaigns'),
- );
+ ];
return $providers;
}
diff --git a/CRM/Utils/Request.php b/CRM/Utils/Request.php
index 2748e07d7df8..2f55cea32c37 100644
--- a/CRM/Utils/Request.php
+++ b/CRM/Utils/Request.php
@@ -1,9 +1,9 @@
$name)));
+ if ($isThrowException) {
+ throw new CRM_Core_Exception(ts("Could not find valid value for %1", [1 => $name]));
+ }
+ CRM_Core_Error::fatal(ts("Could not find valid value for %1", [1 => $name]));
}
if (!isset($value) && $default) {
@@ -125,8 +126,10 @@ public static function retrieve($name, $type, &$store = NULL, $abort = FALSE, $d
}
// minor hack for action
- if ($name == 'action' && is_string($value)) {
- $value = CRM_Core_Action::resolve($value);
+ if ($name == 'action') {
+ if (!is_numeric($value) && is_string($value)) {
+ $value = CRM_Core_Action::resolve($value);
+ }
}
if (isset($value) && $store) {
@@ -143,9 +146,9 @@ public static function retrieve($name, $type, &$store = NULL, $abort = FALSE, $d
* @param array $method - '$_GET', '$_POST' or '$_REQUEST'.
*
* @return mixed
- * The value of the variable
+ * The value of the variable
*/
- public static function getValue($name, $method) {
+ protected static function getValue($name, $method) {
if (isset($method[$name])) {
return $method[$name];
}
@@ -165,6 +168,10 @@ public static function getValue($name, $method) {
}
/**
+ * @deprecated
+ *
+ * We should use a function that checks url values.
+ *
* This is a replacement for $_REQUEST which includes $_GET/$_POST
* but excludes $_COOKIE / $_ENV / $_SERVER.
*
@@ -176,7 +183,7 @@ public static function exportValues() {
// http://www.php.net/manual/en/ini.core.php#ini.request-order
// http://www.php.net/manual/en/ini.core.php#ini.variables-order
- $result = array();
+ $result = [];
if ($_GET) {
$result = array_merge($result, $_GET);
}
@@ -186,4 +193,63 @@ public static function exportValues() {
return $result;
}
+ /**
+ * Retrieve a variable from the http request.
+ *
+ * @param string $name
+ * Name of the variable to be retrieved.
+ * @param string $type
+ * Type of the variable (see CRM_Utils_Type for details).
+ * Most common options are:
+ * - 'Integer'
+ * - 'Positive'
+ * - 'CommaSeparatedIntegers'
+ * - 'Boolean'
+ * - 'String'
+ *
+ * @param mixed $defaultValue
+ * Default value of the variable if not present.
+ * @param bool $isRequired
+ * Is the variable required for this function to proceed without an exception.
+ * @param string $method
+ * Where to look for the value - GET|POST|REQUEST
+ *
+ * @return mixed
+ */
+ public static function retrieveValue($name, $type, $defaultValue = NULL, $isRequired = FALSE, $method = 'REQUEST') {
+ $null = NULL;
+ return CRM_Utils_Request::retrieve((string) $name, (string) $type, $null, (bool) $isRequired, $defaultValue, $method, TRUE);
+ }
+
+ /**
+ * Retrieve the component from the action attribute of a form.
+ *
+ * Contribution Page forms and Event Management forms detect the value of a
+ * component (and therefore the desired tab key) by reaching into the "action"
+ * attribute of a form and reading the final item of the path. In WordPress,
+ * however, the URL may be urlencoded, and so the URL may need to be decoded
+ * before parsing it.
+ *
+ * @see https://lab.civicrm.org/dev/wordpress/issues/12#note_10699
+ *
+ * @param array $attributes
+ * The form attributes array.
+ *
+ * @return string
+ * The desired value.
+ */
+ public static function retrieveComponent($attributes) {
+ $url = CRM_Utils_Array::value('action', $attributes);
+ // Whilst the following is a fallible universal test for urlencoded URLs,
+ // thankfully the "action" URL has a limited and predictable form and
+ // therefore this comparison is sufficient for our purposes.
+ if (rawurlencode(rawurldecode($url)) !== $url) {
+ $value = strtolower(basename(rawurldecode($url)));
+ }
+ else {
+ $value = strtolower(basename($url));
+ }
+ return $value;
+ }
+
}
diff --git a/CRM/Utils/Rule.php b/CRM/Utils/Rule.php
index c9a92fa96791..50d72d38352e 100644
--- a/CRM/Utils/Rule.php
+++ b/CRM/Utils/Rule.php
@@ -1,9 +1,9 @@
+ *
* @param $value
+ * @return bool
+ */
+ public static function color($value) {
+ return (bool) preg_match('/^#([\da-fA-F]{6})$/', $value);
+ }
+
+ /**
+ * Strip thousand separator from a money string.
+ *
+ * Note that this should be done at the form layer. Once we are processing
+ * money at the BAO or processor layer we should be working with something that
+ * is already in a normalised format.
+ *
+ * @param string $value
*
- * @return mixed
+ * @return string
*/
public static function cleanMoney($value) {
// first remove all white space
- $value = str_replace(array(' ', "\t", "\n"), '', $value);
+ $value = str_replace([' ', "\t", "\n"], '', $value);
$config = CRM_Core_Config::singleton();
//CRM-14868
$currencySymbols = CRM_Core_PseudoConstant::get(
'CRM_Contribute_DAO_Contribution',
- 'currency', array(
+ 'currency', [
'keyColumn' => 'name',
'labelColumn' => 'symbol',
- )
+ ]
);
$value = str_replace($currencySymbols, '', $value);
@@ -793,6 +848,25 @@ public static function xssString($value) {
}
}
+ /**
+ * Validate json string for xss
+ *
+ * @param string $value
+ *
+ * @return bool
+ * False if invalid, true if valid / safe.
+ */
+ public static function json($value) {
+ if (!self::xssString($value)) {
+ return FALSE;
+ }
+ $array = json_decode($value, TRUE);
+ if (!$array || !is_array($array)) {
+ return FALSE;
+ }
+ return self::arrayValue($array);
+ }
+
/**
* @param $path
*
@@ -907,7 +981,7 @@ public static function validDateRange($fields, $fieldName, &$errors, $title) {
$highDate = strtotime($fields[$fieldName . '_high']);
if ($lowDate > $highDate) {
- $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', array(1 => $title));
+ $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $title]);
}
}
@@ -915,11 +989,31 @@ public static function validDateRange($fields, $fieldName, &$errors, $title) {
* @param string $key Extension Key to check
* @return bool
*/
- public static function checkExtesnionKeyIsValid($key = NULL) {
+ public static function checkExtensionKeyIsValid($key = NULL) {
if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {
return FALSE;
}
return TRUE;
}
+ /**
+ * Validate array recursively checking keys and values.
+ *
+ * @param array $array
+ * @return bool
+ */
+ protected static function arrayValue($array) {
+ foreach ($array as $key => $item) {
+ if (is_array($item)) {
+ if (!self::xssString($key) || !self::arrayValue($item)) {
+ return FALSE;
+ }
+ }
+ if (!self::xssString($key) || !self::xssString($item)) {
+ return FALSE;
+ }
+ }
+ return TRUE;
+ }
+
}
diff --git a/CRM/Utils/SQL.php b/CRM/Utils/SQL.php
index 574b3a6cfeca..8c7f4c693854 100644
--- a/CRM/Utils/SQL.php
+++ b/CRM/Utils/SQL.php
@@ -1,9 +1,9 @@
addSelectWhereClause() as $field => $vals) {
if ($vals && $field == $joinColumn) {
$clauses = array_merge($clauses, (array) $vals);
@@ -59,4 +59,117 @@ public static function mergeSubquery($entity, $joinColumn = 'id') {
return $clauses;
}
+ /**
+ * Get current sqlModes of the session
+ * @return array
+ */
+ public static function getSqlModes() {
+ $sqlModes = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode'));
+ return $sqlModes;
+ }
+
+ /**
+ * Checks if this system enforce the MYSQL mode ONLY_FULL_GROUP_BY.
+ * This function should be named supportsAnyValueAndEnforcesFullGroupBY(),
+ * but should be deprecated instead.
+ *
+ * @return mixed
+ * @deprecated
+ */
+ public static function supportsFullGroupBy() {
+ // CRM-21455 MariaDB 10.2 does not support ANY_VALUE
+ $version = self::getDatabaseVersion();
+
+ if (stripos($version, 'mariadb') !== FALSE) {
+ return FALSE;
+ }
+
+ return version_compare($version, '5.7', '>=');
+ }
+
+ /**
+ * Disable ONLY_FULL_GROUP_BY for MySQL versions lower then 5.7
+ *
+ * @return bool
+ */
+ public static function disableFullGroupByMode() {
+ $sqlModes = self::getSqlModes();
+
+ // Disable only_full_group_by mode for lower sql versions.
+ if (!self::supportsFullGroupBy() || (!empty($sqlModes) && !in_array('ONLY_FULL_GROUP_BY', $sqlModes))) {
+ if ($key = array_search('ONLY_FULL_GROUP_BY', $sqlModes)) {
+ unset($sqlModes[$key]);
+ CRM_Core_DAO::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlModes) . "'");
+ }
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ /**
+ * CHeck if ONLY_FULL_GROUP_BY is in the global sql_modes
+ * @return bool
+ */
+ public static function isGroupByModeInDefault() {
+ $sqlModes = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@global.sql_mode'));
+ if (!in_array('ONLY_FULL_GROUP_BY', $sqlModes)) {
+ return FALSE;
+ }
+ return TRUE;
+ }
+
+ /**
+ * Is the Database set up to handle acceents.
+ * @warning This function was introduced in attempt to determine the reason why the test getInternationalStrings was failing on ubu1604 but passing on ubu1204-5
+ * This function should not be used as the basis of further work as the reasoning is not perfact and is giving false failures.
+ * @return bool
+ */
+ public static function supportStorageOfAccents() {
+ $charSetDB = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE 'character_set_database'")->fetchAll();
+ $charSet = $charSetDB[0]['Value'];
+ if ($charSet == 'utf8') {
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Does the DB version support mutliple locks per
+ *
+ * https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
+ *
+ * As an interim measure we ALSO require CIVICRM_SUPPORT_MULTIPLE_LOCKS to be defined.
+ *
+ * This is a conservative measure to introduce the change which we expect to deprecate later.
+ *
+ * @todo we only check mariadb & mysql right now but maybe can add percona.
+ */
+ public static function supportsMultipleLocks() {
+ if (!defined('CIVICRM_SUPPORT_MULTIPLE_LOCKS')) {
+ return FALSE;
+ }
+ static $isSupportLocks = NULL;
+ if (!isset($isSupportLocks)) {
+ $version = self::getDatabaseVersion();
+ if (stripos($version, 'mariadb') !== FALSE) {
+ $isSupportLocks = version_compare($version, '10.0.2', '>=');
+ }
+ else {
+ $isSupportLocks = version_compare($version, '5.7.5', '>=');
+ }
+ }
+
+ return $isSupportLocks;
+ }
+
+ /**
+ * Get the version string for the database.
+ *
+ * @return string
+ */
+ public static function getDatabaseVersion() {
+ return CRM_Core_DAO::singleValueQuery('SELECT VERSION()');
+ }
+
}
diff --git a/CRM/Utils/SQL/BaseParamQuery.php b/CRM/Utils/SQL/BaseParamQuery.php
new file mode 100644
index 000000000000..f48d05556c6d
--- /dev/null
+++ b/CRM/Utils/SQL/BaseParamQuery.php
@@ -0,0 +1,241 @@
+strict = $strict;
+ return $this;
+ }
+
+ /**
+ * Given a string like "field_name = @value", replace "@value" with an escaped SQL string
+ *
+ * @param string $expr SQL expression
+ * @param null|array $args a list of values to insert into the SQL expression; keys are prefix-coded:
+ * prefix '@' => escape SQL
+ * prefix '#' => literal number, skip escaping but do validation
+ * prefix '!' => literal, skip escaping and validation
+ * if a value is an array, then it will be imploded
+ *
+ * PHP NULL's will be treated as SQL NULL's. The PHP string "null" will be treated as a string.
+ *
+ * @param string $activeMode
+ *
+ * @return string
+ */
+ public function interpolate($expr, $args, $activeMode = self::INTERPOLATE_INPUT) {
+ if ($args === NULL) {
+ return $expr;
+ }
+ else {
+ if ($this->mode === self::INTERPOLATE_AUTO) {
+ $this->mode = $activeMode;
+ }
+ elseif ($activeMode !== $this->mode) {
+ throw new RuntimeException("Cannot mix interpolation modes.");
+ }
+
+ $select = $this;
+ return preg_replace_callback('/([#!@])([a-zA-Z0-9_]+)/', function($m) use ($select, $args) {
+ if (isset($args[$m[2]])) {
+ $values = $args[$m[2]];
+ }
+ elseif (isset($args[$m[1] . $m[2]])) {
+ // Backward compat. Keys in $args look like "#myNumber" or "@myString".
+ $values = $args[$m[1] . $m[2]];
+ }
+ elseif ($select->strict) {
+ throw new CRM_Core_Exception('Cannot build query. Variable "' . $m[1] . $m[2] . '" is unknown.');
+ }
+ else {
+ // Unrecognized variables are ignored. Mitigate risk of accidents.
+ return $m[0];
+ }
+ $values = is_array($values) ? $values : [$values];
+ switch ($m[1]) {
+ case '@':
+ $parts = array_map([$select, 'escapeString'], $values);
+ return implode(', ', $parts);
+
+ // TODO: ensure all uses of this un-escaped literal are safe
+ case '!':
+ return implode(', ', $values);
+
+ case '#':
+ foreach ($values as $valueKey => $value) {
+ if ($value === NULL) {
+ $values[$valueKey] = 'NULL';
+ }
+ elseif (!is_numeric($value)) {
+ //throw new API_Exception("Failed encoding non-numeric value" . var_export(array($m[0] => $values), TRUE));
+ throw new CRM_Core_Exception("Failed encoding non-numeric value (" . $m[0] . ")");
+ }
+ }
+ return implode(', ', $values);
+
+ default:
+ throw new CRM_Core_Exception("Unrecognized prefix");
+ }
+ }, $expr);
+ }
+ }
+
+ /**
+ * @param string|NULL $value
+ * @return string
+ * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes)
+ */
+ public function escapeString($value) {
+ return $value === NULL ? 'NULL' : '"' . CRM_Core_DAO::escapeString($value) . '"';
+ }
+
+ /**
+ * Set one (or multiple) parameters to interpolate into the query.
+ *
+ * @param array|string $keys
+ * Key name, or an array of key-value pairs.
+ * @param null|mixed $value
+ * The new value of the parameter.
+ * Values may be strings, ints, or arrays thereof -- provided that the
+ * SQL query uses appropriate prefix (e.g. "@", "!", "#").
+ * @return $this
+ */
+ public function param($keys, $value = NULL) {
+ if ($this->mode === self::INTERPOLATE_AUTO) {
+ $this->mode = self::INTERPOLATE_OUTPUT;
+ }
+ elseif ($this->mode !== self::INTERPOLATE_OUTPUT) {
+ throw new RuntimeException("Select::param() only makes sense when interpolating on output.");
+ }
+
+ if (is_array($keys)) {
+ foreach ($keys as $k => $v) {
+ $this->params[$k] = $v;
+ }
+ }
+ else {
+ $this->params[$keys] = $value;
+ }
+ return $this;
+ }
+
+ /**
+ * Has an offset been set.
+ *
+ * @param string $offset
+ *
+ * @return bool
+ */
+ public function offsetExists($offset) {
+ return isset($this->params[$offset]);
+ }
+
+ /**
+ * Get the value of a SQL parameter.
+ *
+ * @code
+ * $select['cid'] = 123;
+ * $select->where('contact.id = #cid');
+ * echo $select['cid'];
+ * @endCode
+ *
+ * @param string $offset
+ * @return mixed
+ * @see param()
+ * @see ArrayAccess::offsetGet
+ */
+ public function offsetGet($offset) {
+ return $this->params[$offset];
+ }
+
+ /**
+ * Set the value of a SQL parameter.
+ *
+ * @code
+ * $select['cid'] = 123;
+ * $select->where('contact.id = #cid');
+ * echo $select['cid'];
+ * @endCode
+ *
+ * @param string $offset
+ * @param mixed $value
+ * The new value of the parameter.
+ * Values may be strings, ints, or arrays thereof -- provided that the
+ * SQL query uses appropriate prefix (e.g. "@", "!", "#").
+ * @see param()
+ * @see ArrayAccess::offsetSet
+ */
+ public function offsetSet($offset, $value) {
+ $this->param($offset, $value);
+ }
+
+ /**
+ * Unset the value of a SQL parameter.
+ *
+ * @param string $offset
+ * @see param()
+ * @see ArrayAccess::offsetUnset
+ */
+ public function offsetUnset($offset) {
+ unset($this->params[$offset]);
+ }
+
+}
diff --git a/CRM/Utils/SQL/Delete.php b/CRM/Utils/SQL/Delete.php
new file mode 100644
index 000000000000..24d0f885fbb4
--- /dev/null
+++ b/CRM/Utils/SQL/Delete.php
@@ -0,0 +1,269 @@
+where('activity_type_id = #type', array('type' => 234))
+ * ->where('status_id IN (#statuses)', array('statuses' => array(1,2,3))
+ * ->where('subject like @subj', array('subj' => '%hello%'))
+ * ->where('!dynamicColumn = 1', array('dynamicColumn' => 'coalesce(is_active,0)'))
+ * ->where('!column = @value', array(
+ * 'column' => $customField->column_name,
+ * 'value' => $form['foo']
+ * ))
+ * echo $del->toSQL();
+ * @endcode
+ *
+ * Design principles:
+ * - Portable
+ * - No knowledge of the underlying SQL API (except for escaping -- CRM_Core_DAO::escapeString)
+ * - No knowledge of the underlying data model
+ * - SQL clauses correspond to PHP functions ($select->where("foo_id=123"))
+ * - Variable escaping is concise and controllable based on prefixes, eg
+ * - similar to Drupal's t()
+ * - use "@varname" to insert the escaped value
+ * - use "!varname" to insert raw (unescaped) values
+ * - use "#varname" to insert a numerical value (these are validated but not escaped)
+ * - to disable any preprocessing, simply omit the variable list
+ * - control characters (@!#) are mandatory in expressions but optional in arg-keys
+ * - Variables may be individual values or arrays; arrays are imploded with commas
+ * - Conditionals are AND'd; if you need OR's, do it yourself
+ * - Use classes/functions with documentation (rather than undocumented array-trees)
+ * - For any given string, interpolation is only performed once. After an interpolation,
+ * a string may never again be subjected to interpolation.
+ *
+ * The "interpolate-once" principle can be enforced by either interpolating on input
+ * xor output. The notations for input and output interpolation are a bit different,
+ * and they may not be mixed.
+ *
+ * @code
+ * // Interpolate on input. Set params when using them.
+ * $select->where('activity_type_id = #type', array(
+ * 'type' => 234,
+ * ));
+ *
+ * // Interpolate on output. Set params independently.
+ * $select
+ * ->where('activity_type_id = #type')
+ * ->param('type', 234),
+ * @endcode
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2019
+ */
+class CRM_Utils_SQL_Delete extends CRM_Utils_SQL_BaseParamQuery {
+
+ private $from;
+ private $wheres = [];
+
+ /**
+ * Create a new DELETE query.
+ *
+ * @param string $from
+ * Table-name and optional alias.
+ * @param array $options
+ * @return CRM_Utils_SQL_Delete
+ */
+ public static function from($from, $options = []) {
+ return new self($from, $options);
+ }
+
+ /**
+ * Create a new DELETE query.
+ *
+ * @param string $from
+ * Table-name and optional alias.
+ * @param array $options
+ */
+ public function __construct($from, $options = []) {
+ $this->from = $from;
+ $this->mode = isset($options['mode']) ? $options['mode'] : self::INTERPOLATE_AUTO;
+ }
+
+ /**
+ * Make a new copy of this query.
+ *
+ * @return CRM_Utils_SQL_Delete
+ */
+ public function copy() {
+ return clone $this;
+ }
+
+ /**
+ * Merge something or other.
+ *
+ * @param CRM_Utils_SQL_Delete $other
+ * @param array|NULL $parts
+ * ex: 'wheres'
+ * @return CRM_Utils_SQL_Delete
+ */
+ public function merge($other, $parts = NULL) {
+ if ($other === NULL) {
+ return $this;
+ }
+
+ if ($this->mode === self::INTERPOLATE_AUTO) {
+ $this->mode = $other->mode;
+ }
+ elseif ($other->mode === self::INTERPOLATE_AUTO) {
+ // Noop.
+ }
+ elseif ($this->mode !== $other->mode) {
+ // Mixing modes will lead to someone getting an expected substitution.
+ throw new RuntimeException("Cannot merge queries that use different interpolation modes ({$this->mode} vs {$other->mode}).");
+ }
+
+ $arrayFields = ['wheres', 'params'];
+ foreach ($arrayFields as $f) {
+ if ($parts === NULL || in_array($f, $parts)) {
+ $this->{$f} = array_merge($this->{$f}, $other->{$f});
+ }
+ }
+
+ $flatFields = ['from'];
+ foreach ($flatFields as $f) {
+ if ($parts === NULL || in_array($f, $parts)) {
+ if ($other->{$f} !== NULL) {
+ $this->{$f} = $other->{$f};
+ }
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Limit results by adding extra condition(s) to the WHERE clause
+ *
+ * @param string|array $exprs list of SQL expressions
+ * @param null|array $args use NULL to disable interpolation; use an array of variables to enable
+ * @return CRM_Utils_SQL_Delete
+ */
+ public function where($exprs, $args = NULL) {
+ $exprs = (array) $exprs;
+ foreach ($exprs as $expr) {
+ $evaluatedExpr = $this->interpolate($expr, $args);
+ $this->wheres[$evaluatedExpr] = $evaluatedExpr;
+ }
+ return $this;
+ }
+
+ /**
+ * Set one (or multiple) parameters to interpolate into the query.
+ *
+ * @param array|string $keys
+ * Key name, or an array of key-value pairs.
+ * @param null|mixed $value
+ * The new value of the parameter.
+ * Values may be strings, ints, or arrays thereof -- provided that the
+ * SQL query uses appropriate prefix (e.g. "@", "!", "#").
+ * @return \CRM_Utils_SQL_Delete
+ */
+ public function param($keys, $value = NULL) {
+ // Why bother with an override? To provide better type-hinting in `@return`.
+ return parent::param($keys, $value);
+ }
+
+ /**
+ * @param array|NULL $parts
+ * List of fields to check (e.g. 'wheres').
+ * Defaults to all.
+ * @return bool
+ */
+ public function isEmpty($parts = NULL) {
+ $empty = TRUE;
+ $fields = [
+ 'from',
+ 'wheres',
+ ];
+ if ($parts !== NULL) {
+ $fields = array_intersect($fields, $parts);
+ }
+ foreach ($fields as $field) {
+ if (!empty($this->{$field})) {
+ $empty = FALSE;
+ }
+ }
+ return $empty;
+ }
+
+ /**
+ * @return string
+ * SQL statement
+ */
+ public function toSQL() {
+ $sql = 'DELETE ';
+
+ if ($this->from !== NULL) {
+ $sql .= 'FROM ' . $this->from . "\n";
+ }
+ if ($this->wheres) {
+ $sql .= 'WHERE (' . implode(') AND (', $this->wheres) . ")\n";
+ }
+ if ($this->mode === self::INTERPOLATE_OUTPUT) {
+ $sql = $this->interpolate($sql, $this->params, self::INTERPOLATE_OUTPUT);
+ }
+ return $sql;
+ }
+
+ /**
+ * Execute the query.
+ *
+ * To examine the results, use a function like `fetch()`, `fetchAll()`,
+ * `fetchValue()`, or `fetchMap()`.
+ *
+ * @param string|NULL $daoName
+ * The return object should be an instance of this class.
+ * Ex: 'CRM_Contact_BAO_Contact'.
+ * @param bool $i18nRewrite
+ * If the system has multilingual features, should the field/table
+ * names be rewritten?
+ * @return CRM_Core_DAO
+ * @see CRM_Core_DAO::executeQuery
+ * @see CRM_Core_I18n_Schema::rewriteQuery
+ */
+ public function execute($daoName = NULL, $i18nRewrite = TRUE) {
+ // Don't pass through $params. toSQL() handles interpolation.
+ $params = [];
+
+ // Don't pass through $abort, $trapException. Just use straight-up exceptions.
+ $abort = TRUE;
+ $trapException = FALSE;
+ $errorScope = CRM_Core_TemporaryErrorScope::useException();
+
+ // Don't pass through freeDAO. You can do it yourself.
+ $freeDAO = FALSE;
+
+ return CRM_Core_DAO::executeQuery($this->toSQL(), $params, $abort, $daoName,
+ $freeDAO, $i18nRewrite, $trapException);
+ }
+
+}
diff --git a/CRM/Utils/SQL/Insert.php b/CRM/Utils/SQL/Insert.php
index fc8f13635830..816c89f605d0 100644
--- a/CRM/Utils/SQL/Insert.php
+++ b/CRM/Utils/SQL/Insert.php
@@ -36,6 +36,7 @@ class CRM_Utils_SQL_Insert {
/**
* Array list of column names
+ * @var array
*/
private $columns;
@@ -59,10 +60,11 @@ public static function into($table) {
*/
public static function dao(CRM_Core_DAO $dao) {
$table = CRM_Core_DAO::getLocaleTableName($dao->getTableName());
- $row = array();
+ $row = [];
foreach ((array) $dao as $key => $value) {
if ($value === 'null') {
- $value = NULL; // Blerg!!!
+ // Blerg!!!
+ $value = NULL;
}
// Skip '_foobar' and '{\u00}*_options' and 'N'.
if (preg_match('/[a-zA-Z]/', $key{0}) && $key !== 'N') {
@@ -80,7 +82,7 @@ public static function dao(CRM_Core_DAO $dao) {
*/
public function __construct($table) {
$this->table = $table;
- $this->rows = array();
+ $this->rows = [];
}
/**
@@ -128,11 +130,11 @@ public function row($row) {
sort($columns);
$this->columns = $columns;
}
- elseif (array_diff($this->columns, $columns) !== array()) {
+ elseif (array_diff($this->columns, $columns) !== []) {
throw new CRM_Core_Exception("Inconsistent column names");
}
- $escapedRow = array();
+ $escapedRow = [];
foreach ($this->columns as $column) {
$escapedRow[$column] = $this->escapeString($row[$column]);
}
diff --git a/CRM/Utils/SQL/Select.php b/CRM/Utils/SQL/Select.php
index fc6b762f8d29..bdb892ed4d9e 100644
--- a/CRM/Utils/SQL/Select.php
+++ b/CRM/Utils/SQL/Select.php
@@ -1,9 +1,9 @@
where("foo_id=123"))
* - Variable escaping is concise and controllable based on prefixes, eg
* - similar to Drupal's t()
@@ -79,57 +78,24 @@
* @endcode
*
* @package CRM
- * @copyright CiviCRM LLC (c) 2004-2017
+ * @copyright CiviCRM LLC (c) 2004-2019
*/
-class CRM_Utils_SQL_Select implements ArrayAccess {
+class CRM_Utils_SQL_Select extends CRM_Utils_SQL_BaseParamQuery {
- /**
- * Interpolate values as soon as they are passed in (where(), join(), etc).
- *
- * Default.
- *
- * Pro: Every clause has its own unique namespace for parameters.
- * Con: Probably slower.
- * Advice: Use this when aggregating SQL fragments from agents who
- * maintained by different parties.
- */
- const INTERPOLATE_INPUT = 'in';
-
- /**
- * Interpolate values when rendering SQL output (toSQL()).
- *
- * Pro: Probably faster.
- * Con: Must maintain an aggregated list of all parameters.
- * Advice: Use this when you have control over the entire query.
- */
- const INTERPOLATE_OUTPUT = 'out';
-
- /**
- * Determine mode automatically. When the first attempt is made
- * to use input-interpolation (eg `where(..., array(...))`) or
- * output-interpolation (eg `param(...)`), the mode will be
- * set. Subsequent calls will be validated using the same mode.
- */
- const INTERPOLATE_AUTO = 'auto';
-
- private $mode = NULL;
private $insertInto = NULL;
- private $insertIntoFields = array();
- private $selects = array();
+ private $insertVerb = 'INSERT INTO ';
+ private $insertIntoFields = [];
+ private $selects = [];
private $from;
- private $joins = array();
- private $wheres = array();
- private $groupBys = array();
- private $havings = array();
- private $orderBys = array();
+ private $joins = [];
+ private $wheres = [];
+ private $groupBys = [];
+ private $havings = [];
+ private $orderBys = [];
private $limit = NULL;
private $offset = NULL;
- private $params = array();
private $distinct = NULL;
- // Public to work-around PHP 5.3 limit.
- public $strict = NULL;
-
/**
* Create a new SELECT query.
*
@@ -138,7 +104,7 @@ class CRM_Utils_SQL_Select implements ArrayAccess {
* @param array $options
* @return CRM_Utils_SQL_Select
*/
- public static function from($from, $options = array()) {
+ public static function from($from, $options = []) {
return new self($from, $options);
}
@@ -148,7 +114,7 @@ public static function from($from, $options = array()) {
* @param array $options
* @return CRM_Utils_SQL_Select
*/
- public static function fragment($options = array()) {
+ public static function fragment($options = []) {
return new self(NULL, $options);
}
@@ -159,7 +125,7 @@ public static function fragment($options = array()) {
* Table-name and optional alias.
* @param array $options
*/
- public function __construct($from, $options = array()) {
+ public function __construct($from, $options = []) {
$this->from = $from;
$this->mode = isset($options['mode']) ? $options['mode'] : self::INTERPOLATE_AUTO;
}
@@ -176,7 +142,7 @@ public function copy() {
/**
* Merge something or other.
*
- * @param CRM_Utils_SQL_Select $other
+ * @param array|CRM_Utils_SQL_Select $other
* @param array|NULL $parts
* ex: 'joins', 'wheres'
* @return CRM_Utils_SQL_Select
@@ -186,6 +152,13 @@ public function merge($other, $parts = NULL) {
return $this;
}
+ if (is_array($other)) {
+ foreach ($other as $fragment) {
+ $this->merge($fragment, $parts);
+ }
+ return $this;
+ }
+
if ($this->mode === self::INTERPOLATE_AUTO) {
$this->mode = $other->mode;
}
@@ -197,14 +170,14 @@ public function merge($other, $parts = NULL) {
throw new RuntimeException("Cannot merge queries that use different interpolation modes ({$this->mode} vs {$other->mode}).");
}
- $arrayFields = array('insertIntoFields', 'selects', 'joins', 'wheres', 'groupBys', 'havings', 'orderBys', 'params');
+ $arrayFields = ['insertIntoFields', 'selects', 'joins', 'wheres', 'groupBys', 'havings', 'orderBys', 'params'];
foreach ($arrayFields as $f) {
if ($parts === NULL || in_array($f, $parts)) {
$this->{$f} = array_merge($this->{$f}, $other->{$f});
}
}
- $flatFields = array('insertInto', 'from', 'limit', 'offset');
+ $flatFields = ['insertInto', 'from', 'limit', 'offset'];
foreach ($flatFields as $f) {
if ($parts === NULL || in_array($f, $parts)) {
if ($other->{$f} !== NULL) {
@@ -331,7 +304,7 @@ public function orderBy($exprs, $args = NULL, $weight = 0) {
$exprs = (array) $exprs;
foreach ($exprs as $expr) {
$evaluatedExpr = $this->interpolate($expr, $args);
- $this->orderBys[$evaluatedExpr] = array('value' => $evaluatedExpr, 'weight' => $weight, 'guid' => $guid++);
+ $this->orderBys[$evaluatedExpr] = ['value' => $evaluatedExpr, 'weight' => $weight, 'guid' => $guid++];
}
return $this;
}
@@ -348,22 +321,8 @@ public function orderBy($exprs, $args = NULL, $weight = 0) {
* @return \CRM_Utils_SQL_Select
*/
public function param($keys, $value = NULL) {
- if ($this->mode === self::INTERPOLATE_AUTO) {
- $this->mode = self::INTERPOLATE_OUTPUT;
- }
- elseif ($this->mode !== self::INTERPOLATE_OUTPUT) {
- throw new RuntimeException("Select::param() only makes sense when interpolating on output.");
- }
-
- if (is_array($keys)) {
- foreach ($keys as $k => $v) {
- $this->params[$k] = $v;
- }
- }
- else {
- $this->params[$keys] = $value;
- }
- return $this;
+ // Why bother with an override? To provide bett er type-hinting in `@return`.
+ return parent::param($keys, $value);
}
/**
@@ -397,12 +356,39 @@ public function limit($limit, $offset = 0) {
* @return CRM_Utils_SQL_Select
* @see insertIntoField
*/
- public function insertInto($table, $fields = array()) {
+ public function insertInto($table, $fields = []) {
$this->insertInto = $table;
$this->insertIntoField($fields);
return $this;
}
+ /**
+ * Wrapper function of insertInto fn but sets insertVerb = "INSERT IGNORE INTO "
+ *
+ * @param string $table
+ * The name of the other table (which receives new data).
+ * @param array $fields
+ * The fields to fill in the other table (in order).
+ * @return CRM_Utils_SQL_Select
+ */
+ public function insertIgnoreInto($table, $fields = []) {
+ $this->insertVerb = "INSERT IGNORE INTO ";
+ return $this->insertInto($table, $fields);
+ }
+
+ /**
+ * Wrapper function of insertInto fn but sets insertVerb = "REPLACE INTO "
+ *
+ * @param string $table
+ * The name of the other table (which receives new data).
+ * @param array $fields
+ * The fields to fill in the other table (in order).
+ */
+ public function replaceInto($table, $fields = []) {
+ $this->insertVerb = "REPLACE INTO ";
+ return $this->insertInto($table, $fields);
+ }
+
/**
* @param array $fields
* The fields to fill in the other table (in order).
@@ -424,7 +410,7 @@ public function insertIntoField($fields) {
*/
public function isEmpty($parts = NULL) {
$empty = TRUE;
- $fields = array(
+ $fields = [
'insertInto',
'insertIntoFields',
'selects',
@@ -436,7 +422,7 @@ public function isEmpty($parts = NULL) {
'orderBys',
'limit',
'offset',
- );
+ ];
if ($parts !== NULL) {
$fields = array_intersect($fields, $parts);
}
@@ -448,101 +434,6 @@ public function isEmpty($parts = NULL) {
return $empty;
}
- /**
- * Enable (or disable) strict mode.
- *
- * In strict mode, unknown variables will generate exceptions.
- *
- * @param bool $strict
- * @return CRM_Utils_SQL_Select
- */
- public function strict($strict = TRUE) {
- $this->strict = $strict;
- return $this;
- }
-
- /**
- * Given a string like "field_name = @value", replace "@value" with an escaped SQL string
- *
- * @param string $expr SQL expression
- * @param null|array $args a list of values to insert into the SQL expression; keys are prefix-coded:
- * prefix '@' => escape SQL
- * prefix '#' => literal number, skip escaping but do validation
- * prefix '!' => literal, skip escaping and validation
- * if a value is an array, then it will be imploded
- *
- * PHP NULL's will be treated as SQL NULL's. The PHP string "null" will be treated as a string.
- *
- * @param string $activeMode
- *
- * @return string
- */
- public function interpolate($expr, $args, $activeMode = self::INTERPOLATE_INPUT) {
- if ($args === NULL) {
- return $expr;
- }
- else {
- if ($this->mode === self::INTERPOLATE_AUTO) {
- $this->mode = $activeMode;
- }
- elseif ($activeMode !== $this->mode) {
- throw new RuntimeException("Cannot mix interpolation modes.");
- }
-
- $select = $this;
- return preg_replace_callback('/([#!@])([a-zA-Z0-9_]+)/', function($m) use ($select, $args) {
- if (isset($args[$m[2]])) {
- $values = $args[$m[2]];
- }
- elseif (isset($args[$m[1] . $m[2]])) {
- // Backward compat. Keys in $args look like "#myNumber" or "@myString".
- $values = $args[$m[1] . $m[2]];
- }
- elseif ($select->strict) {
- throw new CRM_Core_Exception('Cannot build query. Variable "' . $m[1] . $m[2] . '" is unknown.');
- }
- else {
- // Unrecognized variables are ignored. Mitigate risk of accidents.
- return $m[0];
- }
- $values = is_array($values) ? $values : array($values);
- switch ($m[1]) {
- case '@':
- $parts = array_map(array($select, 'escapeString'), $values);
- return implode(', ', $parts);
-
- // TODO: ensure all uses of this un-escaped literal are safe
- case '!':
- return implode(', ', $values);
-
- case '#':
- foreach ($values as $valueKey => $value) {
- if ($value === NULL) {
- $values[$valueKey] = 'NULL';
- }
- elseif (!is_numeric($value)) {
- //throw new API_Exception("Failed encoding non-numeric value" . var_export(array($m[0] => $values), TRUE));
- throw new CRM_Core_Exception("Failed encoding non-numeric value (" . $m[0] . ")");
- }
- }
- return implode(', ', $values);
-
- default:
- throw new CRM_Core_Exception("Unrecognized prefix");
- }
- }, $expr);
- }
- }
-
- /**
- * @param string|NULL $value
- * @return string
- * SQL expression, e.g. "it\'s great" (with-quotes) or NULL (without-quotes)
- */
- public function escapeString($value) {
- return $value === NULL ? 'NULL' : '"' . CRM_Core_DAO::escapeString($value) . '"';
- }
-
/**
* @return string
* SQL statement
@@ -550,10 +441,11 @@ public function escapeString($value) {
public function toSQL() {
$sql = '';
if ($this->insertInto) {
- $sql .= 'INSERT INTO ' . $this->insertInto . ' (';
+ $sql .= $this->insertVerb . $this->insertInto . ' (';
$sql .= implode(', ', $this->insertIntoFields);
$sql .= ")\n";
}
+
if ($this->selects) {
$sql .= 'SELECT ' . $this->distinct . implode(', ', $this->selects) . "\n";
}
@@ -577,7 +469,7 @@ public function toSQL() {
}
if ($this->orderBys) {
$orderBys = CRM_Utils_Array::crmArraySortByField($this->orderBys,
- array('weight', 'guid'));
+ ['weight', 'guid']);
$orderBys = CRM_Utils_Array::collect('value', $orderBys);
$sql .= 'ORDER BY ' . implode(', ', $orderBys) . "\n";
}
@@ -611,7 +503,7 @@ public function toSQL() {
*/
public function execute($daoName = NULL, $i18nRewrite = TRUE) {
// Don't pass through $params. toSQL() handles interpolation.
- $params = array();
+ $params = [];
// Don't pass through $abort, $trapException. Just use straight-up exceptions.
$abort = TRUE;
@@ -625,65 +517,4 @@ public function execute($daoName = NULL, $i18nRewrite = TRUE) {
$freeDAO, $i18nRewrite, $trapException);
}
- /**
- * Has an offset been set.
- *
- * @param string $offset
- *
- * @return bool
- */
- public function offsetExists($offset) {
- return isset($this->params[$offset]);
- }
-
- /**
- * Get the value of a SQL parameter.
- *
- * @code
- * $select['cid'] = 123;
- * $select->where('contact.id = #cid');
- * echo $select['cid'];
- * @endCode
- *
- * @param string $offset
- * @return mixed
- * @see param()
- * @see ArrayAccess::offsetGet
- */
- public function offsetGet($offset) {
- return $this->params[$offset];
- }
-
- /**
- * Set the value of a SQL parameter.
- *
- * @code
- * $select['cid'] = 123;
- * $select->where('contact.id = #cid');
- * echo $select['cid'];
- * @endCode
- *
- * @param string $offset
- * @param mixed $value
- * The new value of the parameter.
- * Values may be strings, ints, or arrays thereof -- provided that the
- * SQL query uses appropriate prefix (e.g. "@", "!", "#").
- * @see param()
- * @see ArrayAccess::offsetSet
- */
- public function offsetSet($offset, $value) {
- $this->param($offset, $value);
- }
-
- /**
- * Unset the value of a SQL parameter.
- *
- * @param string $offset
- * @see param()
- * @see ArrayAccess::offsetUnset
- */
- public function offsetUnset($offset) {
- unset($this->params[$offset]);
- }
-
}
diff --git a/CRM/Utils/SQL/TempTable.php b/CRM/Utils/SQL/TempTable.php
new file mode 100644
index 000000000000..ad4cc452542f
--- /dev/null
+++ b/CRM/Utils/SQL/TempTable.php
@@ -0,0 +1,334 @@
+getName();
+ * $name = CRM_Utils_SQL_TempTable::build()->setDurable()->getName();
+ * $name = CRM_Utils_SQL_TempTable::build()->setCategory('contactstats')->setId($contact['id'])->getName();
+ *
+ * Example 2: Create a temp table using the results of a SELECT query.
+ *
+ * $tmpTbl = CRM_Utils_SQL_TempTable::build()->createWithQuery('SELECT id, display_name FROM civicrm_contact');
+ * $tmpTbl = CRM_Utils_SQL_TempTable::build()->createWithQuery(CRM_Utils_SQL_Select::from('civicrm_contact')->select('display_name'));
+ *
+ * Example 3: Create an empty temp table with list of columns.
+ *
+ * $tmpTbl = CRM_Utils_SQL_TempTable::build()->setDurable()->createWithColumns('id int(10, name varchar(64)');
+ *
+ * Example 4: Drop a table that you previously created.
+ *
+ * $tmpTbl->drop();
+ *
+ * Example 5: Auto-drop a temp table when $tmpTbl falls out of scope
+ *
+ * $tmpTbl->setAutodrop();
+ *
+ */
+class CRM_Utils_SQL_TempTable {
+
+ const UTF8 = 'DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
+ const CATEGORY_LENGTH = 12;
+ const CATEGORY_REGEXP = ';^[a-zA-Z0-9]+$;';
+ // MAX{64} - CATEGORY_LENGTH{12} - CONST_LENGHTH{15} = 37
+ const ID_LENGTH = 37;
+ const ID_REGEXP = ';^[a-zA-Z0-9_]+$;';
+ const INNODB = 'ENGINE=InnoDB';
+ const MEMORY = 'ENGINE=MEMORY';
+
+ /**
+ * @var bool
+ */
+ protected $durable;
+
+ /**
+ * @var bool
+ */
+ protected $utf8;
+
+ protected $category;
+
+ protected $id;
+
+ protected $autodrop;
+
+ protected $memory;
+
+ protected $createSql;
+
+ /**
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public static function build() {
+ $t = new CRM_Utils_SQL_TempTable();
+ $t->category = NULL;
+ $t->id = md5(uniqid('', TRUE));
+ // The constant CIVICRM_TEMP_FORCE_DURABLE is for local debugging.
+ $t->durable = CRM_Utils_Constant::value('CIVICRM_TEMP_FORCE_DURABLE', FALSE);
+ $t->utf8 = TRUE;
+ $t->autodrop = FALSE;
+ $t->memory = FALSE;
+ return $t;
+ }
+
+ public function __destruct() {
+ if ($this->autodrop) {
+ $this->drop();
+ }
+ }
+
+ /**
+ * Determine the full table name.
+ *
+ * @return string
+ * Ex: 'civicrm_tmp_d_foo_abcd1234abcd1234'
+ */
+ public function getName() {
+ $parts = ['civicrm', 'tmp'];
+ $parts[] = ($this->durable ? 'd' : 'e');
+ $parts[] = $this->category ? $this->category : 'dflt';
+ $parts[] = $this->id ? $this->id : 'dflt';
+ return implode('_', $parts);
+ }
+
+ /**
+ * Create the table using results from a SELECT query.
+ *
+ * @param string|CRM_Utils_SQL_Select $selectQuery
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function createWithQuery($selectQuery) {
+ $sql = sprintf('%s %s %s AS %s',
+ $this->toSQL('CREATE'),
+ $this->memory ? self::MEMORY : self::INNODB,
+ $this->utf8 ? self::UTF8 : '',
+ ($selectQuery instanceof CRM_Utils_SQL_Select ? $selectQuery->toSQL() : $selectQuery)
+ );
+ CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
+ $this->createSql = $sql;
+ return $this;
+ }
+
+ /**
+ * Create the empty table.
+ *
+ * @parma string $columns
+ * SQL column listing.
+ * Ex: 'id int(10), name varchar(64)'.
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function createWithColumns($columns) {
+ $sql = sprintf('%s (%s) %s %s',
+ $this->toSQL('CREATE'),
+ $columns,
+ $this->memory ? self::MEMORY : self::INNODB,
+ $this->utf8 ? self::UTF8 : ''
+ );
+ CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
+ $this->createSql = $sql;
+ return $this;
+ }
+
+ /**
+ * Drop the table.
+ *
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function drop() {
+ $sql = $this->toSQL('DROP', 'IF EXISTS');
+ CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE, FALSE);
+ return $this;
+ }
+
+ /**
+ * @param string $action
+ * Ex: 'CREATE', 'DROP'
+ * @param string|NULL $ifne
+ * Ex: 'IF EXISTS', 'IF NOT EXISTS'.
+ * @return string
+ * Ex: 'CREATE TEMPORARY TABLE `civicrm_tmp_e_foo_abcd1234`'
+ * Ex: 'CREATE TABLE IF NOT EXISTS `civicrm_tmp_d_foo_abcd1234`'
+ */
+ private function toSQL($action, $ifne = NULL) {
+ $parts = [];
+ $parts[] = $action;
+ if (!$this->durable) {
+ $parts[] = 'TEMPORARY';
+ }
+ $parts[] = 'TABLE';
+ if ($ifne) {
+ $parts[] = $ifne;
+ }
+ $parts[] = '`' . $this->getName() . '`';
+ return implode(' ', $parts);
+ }
+
+ /**
+ * @return string|NULL
+ */
+ public function getCategory() {
+ return $this->category;
+ }
+
+ /**
+ * @return string|NULL
+ */
+ public function getId() {
+ return $this->id;
+ }
+
+ /**
+ * @return string|NULL
+ */
+ public function getCreateSql() {
+ return $this->createSql;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isAutodrop() {
+ return $this->autodrop;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isDurable() {
+ return $this->durable;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isMemory() {
+ return $this->memory;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isUtf8() {
+ return $this->utf8;
+ }
+
+ /**
+ * @param bool $autodrop
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function setAutodrop($autodrop = TRUE) {
+ $this->autodrop = $autodrop;
+ return $this;
+ }
+
+ /**
+ * @param string|NULL $category
+ *
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function setCategory($category) {
+ if ($category && !preg_match(self::CATEGORY_REGEXP, $category) || strlen($category) > self::CATEGORY_LENGTH) {
+ throw new \RuntimeException("Malformed temp table category");
+ }
+ $this->category = $category;
+ return $this;
+ }
+
+ /**
+ * Set whether the table should be durable.
+ *
+ * Durable tables are not TEMPORARY in the mysql sense.
+ *
+ * @param bool $durable
+ *
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function setDurable($durable = TRUE) {
+ $this->durable = $durable;
+ return $this;
+ }
+
+ /**
+ * Setter for id
+ *
+ * @param mixed $id
+ *
+ * @return CRM_Utils_SQL_TempTable
+ */
+ public function setId($id) {
+ if ($id && !preg_match(self::ID_REGEXP, $id) || strlen($id) > self::ID_LENGTH) {
+ throw new \RuntimeException("Malformed temp table id");
+ }
+ $this->id = $id;
+ return $this;
+ }
+
+ /**
+ * Set table engine to MEMORY.
+ *
+ * @param bool $value
+ *
+ * @return $this
+ */
+ public function setMemory($value = TRUE) {
+ $this->memory = $value;
+ return $this;
+ }
+
+ /**
+ * Set table collation to UTF8.
+ *
+ * @deprecated This method is deprecated as tables should be assumed to have
+ * UTF-8 as the default character set and collation; some other character set
+ * or collation may be specified in the column definition.
+ *
+ * @param bool $value
+ *
+ * @return $this
+ */
+ public function setUtf8($value = TRUE) {
+ $this->utf8 = $value;
+ return $this;
+ }
+
+}
diff --git a/CRM/Utils/Signer.php b/CRM/Utils/Signer.php
index bd825d0a6ed7..6323b8931d7d 100644
--- a/CRM/Utils/Signer.php
+++ b/CRM/Utils/Signer.php
@@ -1,9 +1,9 @@
secret = $secret;
$this->paramNames = $paramNames;
- $this->signDelim = "_"; // chosen to be valid in URLs but not in salt or md5
+ // chosen to be valid in URLs but not in salt or md5
+ $this->signDelim = "_";
$this->defaultSalt = CRM_Utils_String::createRandom(self::SALT_LEN, CRM_Utils_String::ALPHANUMERIC);
}
@@ -81,9 +83,9 @@ public function __construct($secret, $paramNames) {
* @return string, the full public token representing the signature
*/
public function sign($params, $salt = NULL) {
- $message = array();
+ $message = [];
$message['secret'] = $this->secret;
- $message['payload'] = array();
+ $message['payload'] = [];
if (empty($salt)) {
$message['salt'] = $this->createSalt();
}
diff --git a/CRM/Utils/SoapServer.php b/CRM/Utils/SoapServer.php
index 5ab5672c3446..395cd549ebd9 100644
--- a/CRM/Utils/SoapServer.php
+++ b/CRM/Utils/SoapServer.php
@@ -1,9 +1,9 @@
verify($key);
- $params = array(
+ $params = [
'job_id' => $job,
'time_stamp' => date('YmdHis'),
'event_queue_id' => $queue,
'hash' => $hash,
'body' => $body,
'version' => 3,
- );
+ ];
$result = civicrm_api('Mailing', 'event_bounce', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -174,14 +176,14 @@ public function mailer_event_bounce($key, $job, $queue, $hash, $body) {
*/
public function mailer_event_unsubscribe($key, $job, $queue, $hash) {
$this->verify($key);
- $params = array(
+ $params = [
'job_id' => $job,
'time_stamp' => date('YmdHis'),
'org_unsubscribe' => 0,
'event_queue_id' => $queue,
'hash' => $hash,
'version' => 3,
- );
+ ];
$result = civicrm_api('MailingGroup', 'event_unsubscribe', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -197,14 +199,14 @@ public function mailer_event_unsubscribe($key, $job, $queue, $hash) {
*/
public function mailer_event_domain_unsubscribe($key, $job, $queue, $hash) {
$this->verify($key);
- $params = array(
+ $params = [
'job_id' => $job,
'time_stamp' => date('YmdHis'),
'org_unsubscribe' => 1,
'event_queue_id' => $queue,
'hash' => $hash,
'version' => 3,
- );
+ ];
$result = civicrm_api('MailingGroup', 'event_domain_unsubscribe', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -220,14 +222,14 @@ public function mailer_event_domain_unsubscribe($key, $job, $queue, $hash) {
*/
public function mailer_event_resubscribe($key, $job, $queue, $hash) {
$this->verify($key);
- $params = array(
+ $params = [
'job_id' => $job,
'time_stamp' => date('YmdHis'),
'org_unsubscribe' => 0,
'event_queue_id' => $queue,
'hash' => $hash,
'version' => 3,
- );
+ ];
$result = civicrm_api('MailingGroup', 'event_resubscribe', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -243,11 +245,11 @@ public function mailer_event_resubscribe($key, $job, $queue, $hash) {
*/
public function mailer_event_subscribe($key, $email, $domain, $group) {
$this->verify($key);
- $params = array(
+ $params = [
'email' => $email,
'group_id' => $group,
'version' => 3,
- );
+ ];
$result = civicrm_api('MailingGroup', 'event_subscribe', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -263,14 +265,14 @@ public function mailer_event_subscribe($key, $email, $domain, $group) {
*/
public function mailer_event_confirm($key, $contact, $subscribe, $hash) {
$this->verify($key);
- $params = array(
+ $params = [
'contact_id' => $contact,
'subscribe_id' => $subscribe,
'time_stamp' => date('YmdHis'),
'event_subscribe_id' => $subscribe,
'hash' => $hash,
'version' => 3,
- );
+ ];
$result = civicrm_api('Mailing', 'event_confirm', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -290,7 +292,7 @@ public function mailer_event_confirm($key, $contact, $subscribe, $hash) {
*/
public function mailer_event_reply($key, $job, $queue, $hash, $bodyTxt, $rt, $bodyHTML = NULL, $fullEmail = NULL) {
$this->verify($key);
- $params = array(
+ $params = [
'job_id' => $job,
'event_queue_id' => $queue,
'hash' => $hash,
@@ -300,7 +302,7 @@ public function mailer_event_reply($key, $job, $queue, $hash, $bodyTxt, $rt, $bo
'fullEmail' => $fullEmail,
'time_stamp' => date('YmdHis'),
'version' => 3,
- );
+ ];
$result = civicrm_api('Mailing', 'event_reply', $params);
return CRM_Utils_Array::encode_items($result);
}
@@ -317,13 +319,13 @@ public function mailer_event_reply($key, $job, $queue, $hash, $bodyTxt, $rt, $bo
*/
public function mailer_event_forward($key, $job, $queue, $hash, $email) {
$this->verify($key);
- $params = array(
+ $params = [
'job_id' => $job,
'event_queue_id' => $queue,
'hash' => $hash,
'email' => $email,
'version' => 3,
- );
+ ];
$result = civicrm_api('Mailing', 'event_forward', $params);
return CRM_Utils_Array::encode_items($result);
}
diff --git a/CRM/Utils/Sort.php b/CRM/Utils/Sort.php
index 991cced62a1e..a844d3d2d3ea 100644
--- a/CRM/Utils/Sort.php
+++ b/CRM/Utils/Sort.php
@@ -1,9 +1,9 @@
_vars = array();
- $this->_response = array();
+ $this->_vars = [];
+ $this->_response = [];
foreach ($vars as $weight => $value) {
- $this->_vars[$weight] = array(
+ $this->_vars[$weight] = [
'name' => CRM_Utils_Type::validate($value['sort'], 'MysqlColumnNameOrAlias'),
'direction' => CRM_Utils_Array::value('direction', $value),
'title' => $value['name'],
- );
+ ];
}
$this->_currentSortID = 1;
@@ -219,12 +219,12 @@ public function initSortID($defaultSortOrder) {
public function initialize($defaultSortOrder) {
$this->initSortID($defaultSortOrder);
- $this->_response = array();
+ $this->_response = [];
$current = $this->_currentSortID;
foreach ($this->_vars as $index => $item) {
$name = $item['name'];
- $this->_response[$name] = array();
+ $this->_response[$name] = [];
$newDirection = ($item['direction'] == self::ASCENDING) ? self::DESCENDING : self::ASCENDING;
@@ -274,7 +274,7 @@ public function getCurrentSortDirection() {
* (-1 or 1)
*/
public static function cmpFunc($a, $b) {
- $cmp_order = array('weight', 'id', 'title', 'name');
+ $cmp_order = ['weight', 'id', 'title', 'name'];
foreach ($cmp_order as $attribute) {
if (isset($a[$attribute]) && isset($b[$attribute])) {
if ($a[$attribute] < $b[$attribute]) {
diff --git a/CRM/Utils/String.php b/CRM/Utils/String.php
index be6ba732a99f..c740e72a1f38 100644
--- a/CRM/Utils/String.php
+++ b/CRM/Utils/String.php
@@ -1,9 +1,9 @@
'Acl',
'ACL' => 'Acl',
'im' => 'Im',
'IM' => 'Im',
- );
+ ];
if (isset($map[$string])) {
return $map[$string];
}
@@ -120,8 +120,12 @@ public static function convertStringToCamel($string) {
$fragments = explode('_', $string);
foreach ($fragments as & $fragment) {
$fragment = ucfirst($fragment);
+ // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in without underscores)
+ if (strpos($fragment, 'Uf') === 0 && strlen($string) > 2) {
+ $fragment = 'UF' . ucfirst(substr($fragment, 2));
+ }
}
- // Special case: UFGroup, UFJoin, UFMatch, UFField
+ // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in underscore-separated)
if ($fragments[0] === 'Uf') {
$fragments[0] = 'UF';
}
@@ -158,7 +162,7 @@ public static function rename($name, $len = 4) {
* The last component
*/
public static function getClassName($string, $char = '_') {
- $names = array();
+ $names = [];
if (!is_array($string)) {
$names = explode($char, $string);
}
@@ -241,7 +245,7 @@ public static function isAscii($str, $utf8 = TRUE) {
return TRUE;
}
else {
- $order = array('ASCII');
+ $order = ['ASCII'];
if ($utf8) {
$order[] = 'UTF-8';
}
@@ -265,7 +269,7 @@ public static function isAscii($str, $utf8 = TRUE) {
public static function regex($str, $regexRules) {
// redact the regular expressions
if (!empty($regexRules) && isset($str)) {
- static $matches, $totalMatches, $match = array();
+ static $matches, $totalMatches, $match = [];
foreach ($regexRules as $pattern => $replacement) {
preg_match_all($pattern, $str, $matches);
if (!empty($matches[0])) {
@@ -333,7 +337,7 @@ public static function isUtf8($str) {
// iconv('ISO-8859-1', 'UTF-8', $str);
}
else {
- $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
+ $enc = mb_detect_encoding($str, ['UTF-8'], TRUE);
return ($enc !== FALSE);
}
}
@@ -513,7 +517,7 @@ public static function &makeArray($string) {
$string = trim($string);
$values = explode("\n", $string);
- $result = array();
+ $result = [];
foreach ($values as $value) {
list($n, $v) = CRM_Utils_System::explode('=', $value, 2);
if (!empty($v)) {
@@ -534,7 +538,7 @@ public static function &makeArray($string) {
* only the first alternative found (or the text without alternatives)
*/
public static function stripAlternatives($full) {
- $matches = array();
+ $matches = [];
preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
if (isset($matches[1]) &&
@@ -588,7 +592,7 @@ public static function stripPathChars(
}
if ($_searchChars == NULL) {
- $_searchChars = array(
+ $_searchChars = [
'&',
';',
',',
@@ -606,7 +610,7 @@ public static function stripPathChars(
"\r\n",
"\n",
"\t",
- );
+ ];
$_replaceChar = '_';
}
@@ -621,7 +625,6 @@ public static function stripPathChars(
return str_replace($search, $replace, $string);
}
-
/**
* Use HTMLPurifier to clean up a text string and remove any potential
* xss attacks. This is primarily used in public facing pages which
@@ -638,6 +641,7 @@ public static function purifyHTML($string) {
if (!$_filter) {
$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'UTF-8');
+ $config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
// Disable the cache entirely
$config->set('Cache.DefinitionImpl', NULL);
@@ -657,18 +661,10 @@ public static function purifyHTML($string) {
* @return string
*/
public static function ellipsify($string, $maxLen) {
- $len = strlen($string);
- if ($len <= $maxLen) {
+ if (mb_strlen($string, 'UTF-8') <= $maxLen) {
return $string;
}
- else {
- $end = $maxLen - 3;
- while (strlen($string) > $maxLen - 3) {
- $string = mb_substr($string, 0, $end, 'UTF-8');
- $end = $end - 1;
- }
- return $string . '...';
- }
+ return mb_substr($string, 0, $maxLen - 3, 'UTF-8') . '...';
}
/**
@@ -703,10 +699,10 @@ public static function createRandom($len, $alphabet) {
public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
$pos = strpos($string, $delim);
if ($pos === FALSE) {
- return array($defaultPrefix, $string);
+ return [$defaultPrefix, $string];
}
else {
- return array(substr($string, 0, $pos), substr($string, 1 + $pos));
+ return [substr($string, 0, $pos), substr($string, 1 + $pos)];
}
}
@@ -857,10 +853,10 @@ public static function simpleParseUrl($url) {
$port = isset($parts['port']) ? ':' . $parts['port'] : '';
$path = isset($parts['path']) ? $parts['path'] : '';
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
- return array(
+ return [
'host+port' => "$host$port",
'path+query' => "$path$query",
- );
+ ];
}
/**
@@ -921,7 +917,7 @@ public static function endsWith($string, $fragment) {
*/
public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) {
$patterns = (array) $patterns;
- $result = array();
+ $result = [];
foreach ($patterns as $pattern) {
if (!\CRM_Utils_String::endsWith($pattern, '*')) {
if ($allowNew || in_array($pattern, $allStrings)) {
diff --git a/CRM/Utils/System.php b/CRM/Utils/System.php
index b68356c0e587..cdb290383685 100644
--- a/CRM/Utils/System.php
+++ b/CRM/Utils/System.php
@@ -1,9 +1,9 @@
userSystem;
- return call_user_func_array(array($userSystem, $name), $arguments);
+ return call_user_func_array([$userSystem, $name], $arguments);
}
/**
@@ -103,8 +105,7 @@ public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = T
}
}
- return
- self::url(
+ return self::url(
$path,
CRM_Utils_System::getLinksUrl($urlVar, $includeReset, $includeForce),
$absolute
@@ -133,9 +134,9 @@ public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = T
*/
public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
// Sort out query string to prevent messy urls
- $querystring = array();
- $qs = array();
- $arrays = array();
+ $querystring = [];
+ $qs = [];
+ $arrays = [];
if (!empty($_SERVER['QUERY_STRING'])) {
$qs = explode('&', str_replace('&', '&', $_SERVER['QUERY_STRING']));
@@ -215,8 +216,7 @@ public static function theme(
$print = FALSE,
$maintenance = FALSE
) {
- $config = &CRM_Core_Config::singleton();
- return $config->userSystem->theme($content, $print, $maintenance);
+ return CRM_Core_Config::singleton()->userSystem->theme($content, $print, $maintenance);
}
/**
@@ -433,8 +433,10 @@ public static function getClassName($object) {
*
* @param string $url
* The URL to provide to the browser via the Location header.
+ * @param array $context
+ * Optional additional information for the hook.
*/
- public static function redirect($url = NULL) {
+ public static function redirect($url = NULL, $context = []) {
if (!$url) {
$url = self::url('civicrm/dashboard', 'reset=1');
}
@@ -442,12 +444,18 @@ public static function redirect($url = NULL) {
// this is kinda hackish but not sure how to do it right
$url = str_replace('&', '&', $url);
+ $context['output'] = CRM_Utils_Array::value('snippet', $_GET);
+
+ $parsedUrl = CRM_Utils_Url::parseUrl($url);
+ CRM_Utils_Hook::alterRedirect($parsedUrl, $context);
+ $url = CRM_Utils_Url::unparseUrl($parsedUrl);
+
// If we are in a json context, respond appropriately
- if (CRM_Utils_Array::value('snippet', $_GET) === 'json') {
- CRM_Core_Page_AJAX::returnJsonResponse(array(
+ if ($context['output'] === 'json') {
+ CRM_Core_Page_AJAX::returnJsonResponse([
'status' => 'redirect',
'userContext' => $url,
- ));
+ ]);
}
self::setHttpHeader('Location', $url);
@@ -619,7 +627,7 @@ public static function authenticateScript($abort = TRUE, $name = NULL, $pass = N
list($userID, $ufID, $randomNumber) = $result;
if ($userID && $ufID) {
$config = CRM_Core_Config::singleton();
- $config->userSystem->setUserSession(array($userID, $ufID));
+ $config->userSystem->setUserSession([$userID, $ufID]);
}
else {
return self::authenticateAbort(
@@ -680,7 +688,6 @@ public static function setUFMessage($message) {
return $config->userSystem->setMessage($message);
}
-
/**
* Determine whether a value is null-ish.
*
@@ -741,7 +748,7 @@ private static function parsePHPModules() {
$s = preg_replace('/