Merge pull request #2924 from colemanw/explorer
[civicrm-core.git] / CRM / Contact / BAO / Query.php
index 623b8acd609d1b14e19769701a6d4b612636ce12..b67f445ef695b0d1093d5687caa2a435c5ad00ca 100644 (file)
@@ -1,9 +1,9 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.4                                                |
+ | CiviCRM version 4.5                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2013                                |
+ | Copyright CiviCRM LLC (c) 2004-2014                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2013
+ * @copyright CiviCRM LLC (c) 2004-2014
  * $Id$
  *
  */
@@ -323,6 +323,8 @@ class CRM_Contact_BAO_Query {
    */
   public $_distinctComponentClause;
 
+  public $_rowCountClause;
+
   /**
    * use groupBy component clause for component searches
    *
@@ -338,6 +340,12 @@ class CRM_Contact_BAO_Query {
    */
   public static $_openedPanes = array();
 
+  /**
+   * For search builder - which custom fields are location-dependent
+   * @var array
+   */
+  public $_locationSpecificCustomFields = array();
+
   /**
    * The tables which have a dependency on location and/or address
    *
@@ -541,7 +549,7 @@ class CRM_Contact_BAO_Query {
     }
 
     foreach ($this->_params as $value) {
-      if (!CRM_Utils_Array::value(0, $value)) {
+      if (empty($value[0])) {
         continue;
       }
       $cfID = CRM_Core_BAO_CustomField::getKeyID($value[0]);
@@ -569,7 +577,7 @@ class CRM_Contact_BAO_Query {
   function addSpecialFields() {
     static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
     foreach ($special as $name) {
-      if (CRM_Utils_Array::value($name, $this->_returnProperties)) {
+      if (!empty($this->_returnProperties[$name])) {
         $this->_select[$name] = "contact_a.{$name} as $name";
         $this->_element[$name] = 1;
       }
@@ -634,22 +642,15 @@ class CRM_Contact_BAO_Query {
           }
         }
       }
-      // Fixme: this stuff does not need to be hard-coded, should be retrieved from schema metadata
+
       if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
-        if (
-          // Hack for default search view
-          !empty($this->_returnProperties[$field['pseudoconstant']['optionGroupName']]) ||
-          // Hack for profile search view
-          !empty($this->_returnProperties[$name])
-        ) {
+        if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) {
           $makeException = TRUE;
         }
       }
 
       $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
-      if (
-        CRM_Utils_Array::value($name, $this->_paramLookup) ||
-        CRM_Utils_Array::value($name, $this->_returnProperties) ||
+      if (!empty($this->_paramLookup[$name]) || !empty($this->_returnProperties[$name]) ||
         $makeException
       ) {
         if ($cfID) {
@@ -720,16 +721,20 @@ class CRM_Contact_BAO_Query {
               // also get the id of the tableName
               $tName = substr($tableName, 8);
               if (in_array($tName, array('country', 'state_province', 'county'))) {
-                $pf = ($tName == 'state_province') ? 'state_province_name' : $name;
-                $this->_pseudoConstantsSelect[$pf] =
-                  array('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 ");
-
                 if ($tName == 'state_province') {
+                  $this->_pseudoConstantsSelect['state_province_name'] =
+                    array('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('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('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";
                 $this->_element["{$tName}_id"] = 1;
@@ -759,42 +764,27 @@ class CRM_Contact_BAO_Query {
                 }
                 elseif ($fieldName != 'id') {
                   if ($fieldName == 'prefix_id') {
-                    // Hack - profile views use different field name than normal views!
-                    $this->_pseudoConstantsSelect['prefix_id'] =
-                    $this->_pseudoConstantsSelect['individual_prefix'] = array(
-                      'pseudoField' => 'prefix_id',
-                      'idCol' => "prefix_id",
-                      'bao' => 'CRM_Contact_BAO_Contact'
-                    );
+                    $this->_pseudoConstantsSelect['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
                   }
                   if ($fieldName == 'suffix_id') {
-                    // Hack - profile views use different field name than normal views!
-                    $this->_pseudoConstantsSelect['suffix_id'] =
-                    $this->_pseudoConstantsSelect['individual_suffix'] = array(
-                      'pseudoField' => 'suffix_id',
-                      'idCol' => "suffix_id",
-                      'bao' => 'CRM_Contact_BAO_Contact'
-                    );
+                    $this->_pseudoConstantsSelect['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
                   }
                   if ($fieldName == 'gender_id') {
-                    // Hack - profile views use different field name than normal views!
-                    $this->_pseudoConstantsSelect['gender_id'] =
-                    $this->_pseudoConstantsSelect['gender'] = array(
-                      'pseudoField' => 'gender_id',
-                      'idCol' => "gender_id",
-                      'bao' => 'CRM_Contact_BAO_Contact'
-                    );
+                    $this->_pseudoConstantsSelect['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
+                  }
+                  if ($name == 'communication_style_id') {
+                    $this->_pseudoConstantsSelect['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
                   }
                   $this->_select[$name] = "contact_a.{$fieldName}  as `$name`";
                 }
               }
-              elseif (in_array($tName, array('state_province', 'country', 'county'))) {
-                $this->_pseudoConstantsSelect[$pf]['select'] = "{$field['where']} as `$name`";
-                $this->_pseudoConstantsSelect[$pf]['element'] = $name;
-                if ($tName == 'state_province') {
-                  $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`";
-                  $this->_pseudoConstantsSelect[$tName]['element'] = $name;
-                }
+              elseif (in_array($tName, array('country', 'county'))) {
+                $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`";
+                $this->_pseudoConstantsSelect[$name]['element'] = $name;
+              }
+              elseif ($tName == 'state_province') {
+                $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`";
+                $this->_pseudoConstantsSelect[$tName]['element'] = $name;
               }
               else {
                 $this->_select[$name] = "{$field['where']} as `$name`";
@@ -836,11 +826,9 @@ class CRM_Contact_BAO_Query {
         }
       }
 
-      if ($cfID &&
-        CRM_Utils_Array::value('is_search_range', $field)
-      ) {
+      if ($cfID && !empty($field['is_search_range'])) {
         // this is a custom field with range search enabled, so we better check for two/from values
-        if (CRM_Utils_Array::value($name . '_from', $this->_paramLookup)) {
+        if (!empty($this->_paramLookup[$name . '_from'])) {
           if (!array_key_exists($cfID, $this->_cfIDs)) {
             $this->_cfIDs[$cfID] = array();
           }
@@ -859,7 +847,7 @@ class CRM_Contact_BAO_Query {
             }
           }
         }
-        if (CRM_Utils_Array::value($name . '_to', $this->_paramLookup)) {
+        if (!empty($this->_paramLookup[$name . '_to'])) {
           if (!array_key_exists($cfID, $this->_cfIDs)) {
             $this->_cfIDs[$cfID] = array();
           }
@@ -893,7 +881,7 @@ class CRM_Contact_BAO_Query {
     CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select');
 
     if (!empty($this->_cfIDs)) {
-      $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE);
+      $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->_element = array_merge($this->_element, $this->_customQuery->_element);
@@ -911,7 +899,7 @@ class CRM_Contact_BAO_Query {
    * @access public
    */
   function addHierarchicalElements() {
-    if (!CRM_Utils_Array::value('location', $this->_returnProperties)) {
+    if (empty($this->_returnProperties['location'])) {
       return;
     }
     if (!is_array($this->_returnProperties['location'])) {
@@ -1052,7 +1040,7 @@ class CRM_Contact_BAO_Query {
           }
 
           foreach ($this->_params as $id => $values) {
-            if ($values[0] == $nm ||
+            if ((is_array($values) && $values[0] == $nm) ||
               (in_array($elementName, array('phone', 'im'))
                 && (strpos($values[0], $nm) !== FALSE)
               )
@@ -1116,7 +1104,7 @@ class CRM_Contact_BAO_Query {
               $this->_element["{$name}-{$elementFullName}"] = 1;
             }
 
-            if (!CRM_Utils_Array::value("`$tName`", $processed)) {
+            if (empty($processed["`$tName`"])) {
               $processed["`$tName`"] = 1;
               $newName = $tableName . '_' . $index;
               switch ($tableName) {
@@ -1191,7 +1179,7 @@ class CRM_Contact_BAO_Query {
       if ($addWhereCount) {
         $locClause = array();
         foreach ($this->_whereTables as $tableName => $clause) {
-          if (CRM_Utils_Array::value($tableName, $locationTypeJoin)) {
+          if (!empty($locationTypeJoin[$tableName])) {
             $locClause[] = $locationTypeJoin[$tableName];
           }
         }
@@ -1203,10 +1191,10 @@ class CRM_Contact_BAO_Query {
     }
 
     if (!empty($addressCustomFieldIds)) {
-      $cfIDs = $addressCustomFieldIds;
-      $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
+      $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));
           $fieldName = "$name-custom_{$cfID}";
           $tName = "$name-address-custom-{$cfID}";
           $aName = "`$name-address-custom-{$cfID}`";
@@ -1228,7 +1216,7 @@ class CRM_Contact_BAO_Query {
    * @access public
    */
   function addMultipleElements() {
-    if (!CRM_Utils_Array::value('website', $this->_returnProperties)) {
+    if (empty($this->_returnProperties['website'])) {
       return;
     }
     if (!is_array($this->_returnProperties['website'])) {
@@ -1264,7 +1252,9 @@ class CRM_Contact_BAO_Query {
    */
   function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
     if ($count) {
-      if (isset($this->_distinctComponentClause)) {
+      if (isset($this->_rowCountClause)) {
+        $select = "SELECT {$this->_rowCountClause}";
+      } else if (isset($this->_distinctComponentClause)) {
         // we add distinct to get the right count for components
         // for the more complex result set, we use GROUP BY the same id
         // CRM-9630
@@ -1290,7 +1280,7 @@ class CRM_Contact_BAO_Query {
       $from = $this->_simpleFromClause;
     }
     else {
-      if (CRM_Utils_Array::value('group', $this->_paramLookup)) {
+      if (!empty($this->_paramLookup['group'])) {
         // make sure there is only one element
         // this is used when we are running under smog and need to know
         // how the contact was added (CRM-1203)
@@ -1382,7 +1372,7 @@ class CRM_Contact_BAO_Query {
     foreach ($formValues as $id => $values) {
       if ($id == 'privacy') {
         if (is_array($formValues['privacy'])) {
-          $op = CRM_Utils_Array::value('do_not_toggle', $formValues['privacy']) ? '=' : '!=';
+          $op = !empty($formValues['privacy']['do_not_toggle']) ? '=' : '!=';
           foreach ($formValues['privacy'] as $key => $value) {
             if ($value) {
               $params[] = array($key, $op, $value, 0, 0);
@@ -1648,6 +1638,7 @@ class CRM_Contact_BAO_Query {
       case 'activity_subject':
       case 'test_activities':
       case 'activity_type_id':
+      case 'activity_type':
       case 'activity_survey_id':
       case 'activity_tags':
       case 'activity_taglist':
@@ -1751,7 +1742,7 @@ class CRM_Contact_BAO_Query {
     $this->includeContactIds();
     if (!empty($this->_params)) {
       foreach (array_keys($this->_params) as $id) {
-        if (!CRM_Utils_Array::value(0, $this->_params[$id])) {
+        if (empty($this->_params[$id][0])) {
           continue;
         }
         // check for both id and contact_id
@@ -1831,7 +1822,7 @@ class CRM_Contact_BAO_Query {
     $grouping = CRM_Utils_Array::value(3, $values);
     $wildcard = CRM_Utils_Array::value(4, $values);
 
-    if (isset($grouping) && !CRM_Utils_Array::value($grouping, $this->_where)) {
+    if (isset($grouping) && empty($this->_where[$grouping])) {
       $this->_where[$grouping] = array();
     }
 
@@ -1957,6 +1948,7 @@ class CRM_Contact_BAO_Query {
       }
     }
     elseif ($name === 'world_region') {
+      $field['where'] = 'civicrm_worldregion.id';
       $this->optionValueQuery(
         $name, $op, $value, $grouping,
         CRM_Core_PseudoConstant::worldRegion(),
@@ -2112,7 +2104,7 @@ class CRM_Contact_BAO_Query {
           }
 
           $type = NULL;
-          if (CRM_Utils_Array::value('type', $field)) {
+          if (!empty($field['type'])) {
             $type = CRM_Utils_Type::typeToString($field['type']);
           }
 
@@ -2275,32 +2267,25 @@ class CRM_Contact_BAO_Query {
       return $from;
     }
 
-    if (CRM_Utils_Array::value('civicrm_worldregion', $tables)) {
+    if (!empty($tables['civicrm_worldregion'])) {
       $tables = array_merge(array('civicrm_country' => 1), $tables);
     }
 
-    if ((CRM_Utils_Array::value('civicrm_state_province', $tables) ||
-        CRM_Utils_Array::value('civicrm_country', $tables) ||
+    if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) ||
         CRM_Utils_Array::value('civicrm_county', $tables)
-      ) &&
-      !CRM_Utils_Array::value('civicrm_address', $tables)
-    ) {
+      ) && empty($tables['civicrm_address'])) {
       $tables = array_merge(array('civicrm_address' => 1),
         $tables
       );
     }
 
     // add group_contact table if group table is present
-    if (CRM_Utils_Array::value('civicrm_group', $tables) &&
-      !CRM_Utils_Array::value('civicrm_group_contact', $tables)
-    ) {
+    if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
       $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
     }
 
     // add group_contact and group table is subscription history is present
-    if (CRM_Utils_Array::value('civicrm_subscription_history', $tables)
-      && !CRM_Utils_Array::value('civicrm_group', $tables)
-    ) {
+    if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
       $tables = array_merge(array(
         'civicrm_group' => 1,
           'civicrm_group_contact' => 1,
@@ -2350,10 +2335,10 @@ class CRM_Contact_BAO_Query {
         continue;
       }
 
-      if (CRM_Utils_Array::value($name, $inner)) {
+      if (!empty($inner[$name])) {
         $side = 'INNER';
       }
-      elseif (CRM_Utils_Array::value($name, $right)) {
+      elseif (!empty($right[$name])) {
         $side = 'RIGHT';
       }
       else {
@@ -2658,7 +2643,7 @@ class CRM_Contact_BAO_Query {
       // left join
       $groupIDs = array_keys($value);
 
-      if (CRM_Utils_Array::value(0, $groupIDs) &&
+      if (!empty($groupIDs[0]) &&
         CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
           $groupIDs[0],
           'saved_search_id'
@@ -2724,10 +2709,17 @@ class CRM_Contact_BAO_Query {
     return $this->addGroupContactCache(array_keys($value));
   }
 
+  /**
+   * @param array  $groups
+   * @param string $tableAlias
+   * @param string $joinTable
+   *
+   * @return null|string
+   */
   function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
     $config = CRM_Core_Config::singleton();
 
-    // find all the groups that are part of a saved search
+    // Find all the groups that are part of a saved search.
     $groupIDs = implode(',', $groups);
     if (empty($groupIDs)) {
       return NULL;
@@ -2741,29 +2733,32 @@ WHERE  id IN ( $groupIDs )
    OR    saved_search_id IS NOT NULL
    OR    children IS NOT NULL )
 ";
-    $group = CRM_Core_DAO::executeQuery($sql);
-    $ssWhere = array();
+
+    $group          = CRM_Core_DAO::executeQuery($sql);
+    $groupsFiltered = array();
+
     while ($group->fetch()) {
-      if ($tableAlias == NULL) {
-        $alias = "`civicrm_group_contact_cache_{$group->id}`";
-      }
-      else {
-        $alias = $tableAlias;
-      }
+      $groupsFiltered[] = $group->id;
 
       $this->_useDistinct = TRUE;
 
       if (!$this->_smartGroupCache || $group->cache_date == NULL) {
         CRM_Contact_BAO_GroupContactCache::load($group);
       }
-
-      $this->_tables[$alias] = $this->_whereTables[$alias] = " LEFT JOIN civicrm_group_contact_cache {$alias} ON {$joinTable}.id = {$alias}.contact_id ";
-      $ssWhere[] = "{$alias}.group_id = {$group->id}";
     }
 
-    if (!empty($ssWhere)) {
-      return implode(' OR ', $ssWhere);
+    if (count($groupsFiltered)) {
+      $groupIDsFiltered = implode(',', $groupsFiltered);
+
+      if ($tableAlias == NULL) {
+        $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
+      }
+
+      $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
+
+      return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
     }
+
     return NULL;
   }
 
@@ -3355,7 +3350,7 @@ WHERE  id IN ( $groupIDs )
    */
   function postalCode(&$values) {
     // skip if the fields dont have anything to do with postal_code
-    if (!CRM_Utils_Array::value('postal_code', $this->_fields)) {
+    if (empty($this->_fields['postal_code'])) {
       return;
     }
 
@@ -4056,6 +4051,8 @@ civicrm_relationship.is_permission_a_b = 0
           'last_name' => 1,
           'prefix_id' => 1,
           'suffix_id' => 1,
+          'formal_title' => 1,
+          'communication_style_id' => 1,
           'birth_date' => 1,
           'gender_id' => 1,
           'street_address' => 1,
@@ -4412,7 +4409,6 @@ civicrm_relationship.is_permission_a_b = 0
     if ($returnQuery) {
       return $query;
     }
-
     if ($count) {
       return CRM_Core_DAO::singleValueQuery($query);
     }
@@ -4551,6 +4547,32 @@ SELECT COUNT( conts.total_amount ) as total_count,
       $summary['total']['amount'] = $summary['total']['avg'] = 0;
     }
 
+    // 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(',&nbsp;', $summary['soft_credit']['amount']);
+        $summary['soft_credit']['avg'] = implode(',&nbsp;', $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 (
@@ -4639,6 +4661,8 @@ SELECT COUNT( conts.total_amount ) as cancel_count,
         'last_name' => 1,
         'prefix_id' => 1,
         'suffix_id' => 1,
+        'formal_title' => 1,
+        'communication_style_id' => 1,
         'email_greeting' => 1,
         'postal_greeting' => 1,
         'addressee' => 1,
@@ -5106,7 +5130,7 @@ AND   displayRelType.is_active = 1
       $qill = $value;
     }
 
-    $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id');
+    $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
 
     if (is_numeric($value)) {
       $qill = $selectValues[(int ) $value];
@@ -5140,7 +5164,7 @@ AND   displayRelType.is_active = 1
     }
 
     if (in_array($name, $pseudoFields)) {
-      if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id'))) {
+      if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
         $wc = "contact_a.{$name}_id";
       }
       $dataType = 'Positive';
@@ -5196,7 +5220,6 @@ AND   displayRelType.is_active = 1
 
   /**
    * convert the pseudo constants id's to their names
-   * FIXME: Get rid of hard-coded references to fields, should be retrievable from schema metadata
    *
    * @param  reference parameter $dao
    * @param bool $return
@@ -5209,7 +5232,7 @@ AND   displayRelType.is_active = 1
     }
     $values = array();
     foreach ($this->_pseudoConstantsSelect as $key => $value) {
-      if (CRM_Utils_Array::value('sorting', $this->_pseudoConstantsSelect[$key])) {
+      if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) {
         continue;
       }
 
@@ -5223,7 +5246,7 @@ AND   displayRelType.is_active = 1
           //preserve id value
           $idColumn = "{$key}_id";
           $dao->$idColumn = $val;
-          $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
+          $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
         }
         elseif ($value['pseudoField'] == 'state_province_abbreviation') {
           $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
@@ -5270,7 +5293,7 @@ AND   displayRelType.is_active = 1
     $present = array();
 
     foreach ($this->_pseudoConstantsSelect as $name => $value) {
-      if (CRM_Utils_Array::value('table', $value)) {
+      if (!empty($value['table'])) {
         $regex = "/({$value['table']}\.|{$name})/";
         if (preg_match($regex, $sort)) {
           $this->_elemnt[$value['element']] = 1;