Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-03-03-17-36-50
[civicrm-core.git] / CRM / Export / BAO / Export.php
index 94a0a4975c5e41722f2dda45c99601aec8c21b97..442aa6c3f011621a0680131a43b9157cb2418b03 100644 (file)
@@ -81,7 +81,6 @@ class CRM_Export_BAO_Export {
     $queryMode  = $relationField = NULL;
 
     $allCampaigns = array();
-    $exportCampaign = FALSE;
 
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
@@ -157,12 +156,9 @@ class CRM_Export_BAO_Export {
         elseif ($fieldName == 'im') {
           $imProviderId = CRM_Utils_Array::value(3, $value);
         }
-        elseif (substr($fieldName, -8) == 'campaign') {
-          $exportCampaign = TRUE;
-        }
 
         if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
-          if (CRM_Utils_Array::value(2, $value)) {
+          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);
@@ -178,7 +174,7 @@ class CRM_Export_BAO_Export {
               $relIMProviderId = CRM_Utils_Array::value(4, $value);
             }
           }
-          elseif (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') {
@@ -236,12 +232,6 @@ class CRM_Export_BAO_Export {
           }
           else {
             $returnProperties[$fieldName] = 1;
-
-            //campaign field export.
-            if (substr($fieldName, -8) == 'campaign') {
-              $fldNames = explode('_', $fieldName);
-              $returnProperties["{$fldNames[0]}_campaign_id"] = 1;
-            }
           }
         }
       }
@@ -252,7 +242,7 @@ class CRM_Export_BAO_Export {
       }
       elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
         $returnProperties['participant_id'] = 1;
-        if (CRM_Utils_Array::value('participant_role', $returnProperties)) {
+        if (!empty($returnProperties['participant_role'])) {
           unset($returnProperties['participant_role']);
           $returnProperties['participant_role_id'] = 1;
         }
@@ -318,17 +308,6 @@ class CRM_Export_BAO_Export {
 
       if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
         $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
-
-        $campaignReturnProperties = array();;
-        foreach ($componentReturnProperties as $fld => $true) {
-          $campaignReturnProperties[$fld] = $true;
-          if (substr($fld, -11) == 'campaign_id') {
-            $exportCampaign = TRUE;
-            $campaignReturnProperties[substr($fld, 0, -3)] = 1;
-          }
-        }
-        $componentReturnProperties = $campaignReturnProperties;
-
         $returnProperties = array_merge($returnProperties, $componentReturnProperties);
 
         if (!empty($extraReturnProperties)) {
@@ -370,7 +349,7 @@ class CRM_Export_BAO_Export {
       }
     }
 
-    if (!$selectAll && $componentTable && CRM_Utils_Array::value('additional_group', $exportParams)) {
+    if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
       // If an Additional Group is selected, then all contacts in that group are
       // added to the export set (filtering out duplicates).
       $query = "
@@ -380,7 +359,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
 
     if ($moreReturnProperties) {
       // fix for CRM-7066
-      if (CRM_Utils_Array::value('group', $moreReturnProperties)) {
+      if (!empty($moreReturnProperties['group'])) {
         unset($moreReturnProperties['group']);
         $moreReturnProperties['groups'] = 1;
       }
@@ -527,7 +506,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
     // 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
     // ones that are part of a group
-    if (CRM_Utils_Array::value('groups', $returnProperties)) {
+    if (!empty($returnProperties['groups'])) {
       $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
       $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
       // total hack for export, CRM-3618
@@ -549,11 +528,24 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
       }
     }
 
+    // CRM-13982 - check if is deleted
+    $excludeTrashed = TRUE;
+    foreach ($params as $value) {
+      if ($value[0] == 'contact_is_deleted') {
+        $excludeTrashed = FALSE;
+      }
+    }
+    if (empty($where) && $excludeTrashed) {
+      $where = "WHERE contact_a.is_deleted != 1";
+    }
+    elseif ($excludeTrashed) {
+      $where .= " AND contact_a.is_deleted != 1";
+    }
+
     $queryString = "$select $from $where $having";
 
     $groupBy = "";
-    if (CRM_Utils_Array::value('tags', $returnProperties) ||
-      CRM_Utils_Array::value('groups', $returnProperties) ||
+    if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
       CRM_Utils_Array::value('notes', $returnProperties) ||
       // CRM-9552
       ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
@@ -561,6 +553,20 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
       $groupBy = " GROUP BY contact_a.id";
     }
 
+    switch ($exportMode) {
+      case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
+        $groupBy = 'GROUP BY civicrm_contribution.id';
+        break;
+
+      case CRM_Export_Form_Select::EVENT_EXPORT:
+        $groupBy = 'GROUP BY civicrm_participant.id';
+        break;
+
+      case CRM_Export_Form_Select::MEMBER_EXPORT:
+        $groupBy = " GROUP BY civicrm_membership.id";
+        break;
+    }
+
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
       $groupBy = " GROUP BY civicrm_activity.id ";
     }
@@ -568,7 +574,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
     if ($order) {
       list($field, $dir) = explode(' ', $order, 2);
       $field = trim($field);
-      if (CRM_Utils_Array::value($field, $returnProperties)) {
+      if (!empty($returnProperties[$field])) {
         // $queryString .= " ORDER BY $order";
       }
     }
@@ -600,8 +606,18 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
       $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
     }
 
+    // Split campaign into 2 fields for id and title
+    $campaignReturnProperties = array();
+    foreach ($returnProperties as $fld => $true) {
+      $campaignReturnProperties[$fld] = $true;
+      if (substr($fld, -11) == 'campaign_id') {
+        $exportCampaign = TRUE;
+        $campaignReturnProperties[substr($fld, 0, -3)] = 1;
+      }
+    }
+    $returnProperties = $campaignReturnProperties;
     //get all campaigns.
-    if ($exportCampaign) {
+    if (isset($exportCampaign)) {
       $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     }
 
@@ -638,7 +654,14 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
           //we should set header only once
           if ($setHeader) {
             $sqlDone = FALSE;
-            if (isset($query->_fields[$field]['title'])) {
+            // Split campaign into 2 fields for id and title
+            if (substr($field, -8) == 'campaign') {
+              $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') {
@@ -654,7 +677,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
                   $type = explode('-', $fld);
                   $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
 
-                  if (CRM_Utils_Array::value(1, $type)) {
+                  if (!empty($type[1])) {
                     if (CRM_Utils_Array::value(0, $type) == 'phone') {
                       $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                     }
@@ -720,7 +743,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
 
                       $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
 
-                      if (CRM_Utils_Array::value(1, $type)) {
+                      if (!empty($type[1])) {
                         if (CRM_Utils_Array::value(0, $type) == 'phone') {
                           $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                         }
@@ -806,29 +829,33 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
               foreach (array_keys($val) as $fld) {
                 $type = explode('-', $fld);
                 $fldValue = "{$ltype}-" . $type[0];
+                // CRM-14076 - fix label to work as the query object expects
+                // FIXME: We should not be using labels as keys!
+                $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
 
-                if (CRM_Utils_Array::value(1, $type)) {
+                if (!empty($type[1])) {
                   $fldValue .= "-" . $type[1];
+                  $daoField .= "-" . $type[1];
                 }
 
                 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                 switch ($fld) {
                   case 'country':
                   case 'world_region':
-                    $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'country'));
+                    $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'country'));
                     break;
 
                   case 'state_province':
-                    $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'province'));
+                    $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'province'));
                     break;
 
                   case 'im_provider':
-                    $imFieldvalue = $fldValue . "-provider_id";
+                    $imFieldvalue = $daoField . "-provider_id";
                     $row[$fldValue] = CRM_Utils_Array::value($dao->$imFieldvalue, $imProviders);
                     break;
 
                   default:
-                    $row[$fldValue] = $dao->$fldValue;
+                    $row[$fldValue] = $dao->$daoField;
                     break;
                 }
               }
@@ -846,18 +873,33 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
                   $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;
-                            } else  if ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
+              }
+              elseif ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
                 foreach ($relationValue as $ltype => $val) {
                   foreach (array_keys($val) as $fld) {
                     $type = explode('-', $fld);
                     $fldValue = "{$ltype}-" . $type[0];
-                    if (CRM_Utils_Array::value(1, $type)) {
+                    if (!empty($type[1])) {
                       $fldValue .= "-" . $type[1];
                     }
                     // CRM-3157: localise country, region (both have ‘country’ context)
@@ -894,12 +936,6 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
                     $relationQuery[$field]->_options
                   );
                 }
-                elseif (in_array($relationField, array(
-                  'email_greeting', 'postal_greeting', 'addressee'))) {
-                  //special case for greeting replacement
-                  $fldValue = "{$relationField}_display";
-                  $row[$field . $relationField] = $relDAO->$fldValue;
-                }
                 else {
                   //normal relationship fields
                   // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
@@ -1033,7 +1069,7 @@ INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_c
           }
         }
         //remove organization name for individuals if it is set for current employer
-        if (CRM_Utils_Array::value('contact_type', $row) &&
+        if (!empty($row['contact_type']) &&
           $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
         ) {
           $row['organization_name'] = '';
@@ -1522,7 +1558,7 @@ WHERE  id IN ( $deleteIDString )
       'addressee',
     );
     foreach ($greetingFields as $greeting) {
-      if (CRM_Utils_Array::value($greeting, $exportParams)) {
+      if (!empty($exportParams[$greeting])) {
         $greetingLabel = $exportParams[$greeting];
         if (empty($contact)) {
           $values = array(
@@ -1531,7 +1567,7 @@ WHERE  id IN ( $deleteIDString )
           );
           $contact = civicrm_api('contact', 'get', $values);
 
-          if (CRM_Utils_Array::value('is_error', $contact)) {
+          if (!empty($contact['is_error'])) {
             return $greetings;
           }
           $contact = $contact['values'][$contact['id']];
@@ -1553,7 +1589,7 @@ WHERE  id IN ( $deleteIDString )
   static function _trimNonTokens(&$parsedString, $defaultGreeting,
     $addressMergeGreetings, $greetingType = 'postal_greeting'
   ) {
-    if (CRM_Utils_Array::value($greetingType, $addressMergeGreetings)) {
+    if (!empty($addressMergeGreetings[$greetingType])) {
       $greetingLabel = $addressMergeGreetings[$greetingType];
     }
     $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
@@ -1629,7 +1665,7 @@ WHERE  id IN ( $deleteIDString )
 
       if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
 
-        if (CRM_Utils_Array::value('postal_greeting_other', $exportParams) &&
+        if (!empty($exportParams['postal_greeting_other']) &&
           count($merge[$masterID]['copy']) >= 1
         ) {
           // use static greetings specified if no of contacts > 2
@@ -1645,7 +1681,7 @@ WHERE  id IN ( $deleteIDString )
           $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
         }
 
-        if (CRM_Utils_Array::value('addressee_other', $exportParams) &&
+        if (!empty($exportParams['addressee_other']) &&
           count($merge[$masterID]['copy']) >= 1
         ) {
           // use static greetings specified if no of contacts > 2
@@ -1699,7 +1735,7 @@ WHERE  id IN ( $deleteIDString )
       else {
         $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
 
-        if (CRM_Utils_Array::value($householdColName, $sqlColumns)) {
+        if (!empty($sqlColumns[$householdColName])) {
           $replaced[$columnNames] = $householdColName;
         }
       }
@@ -1833,7 +1869,7 @@ LIMIT $offset, $limit
         $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
           'address_options', TRUE, NULL, TRUE
         );
-        if (CRM_Utils_Array::value('supplemental_address_1', $addressOptions)) {
+        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 )";