3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 * Class to parse activity csv files.
22 class CRM_Activity_Import_Parser_Activity
extends CRM_Activity_Import_Parser
{
24 protected $_mapperKeys;
26 private $_contactIdIndex;
29 * Array of successfully imported activity id's
33 protected $_newActivity;
38 * @param array $mapperKeys
40 public function __construct($mapperKeys) {
41 parent
::__construct();
42 $this->_mapperKeys
= $mapperKeys;
46 * Function of undocumented functionality required by the interface.
48 protected function fini() {}
51 * The initializer code, called before the processing.
53 public function init() {
54 $activityContact = CRM_Activity_BAO_ActivityContact
::import();
55 $activityTarget['target_contact_id'] = $activityContact['contact_id'];
56 $fields = array_merge(CRM_Activity_BAO_Activity
::importableFields(),
60 $fields = array_merge($fields, [
61 'source_contact_id' => [
62 'title' => ts('Source Contact'),
63 'headerPattern' => '/Source.Contact?/i',
66 'title' => ts('Activity Type Label'),
67 'headerPattern' => '/(activity.)?type label?/i',
71 foreach ($fields as $name => $field) {
72 $field['type'] = CRM_Utils_Array
::value('type', $field, CRM_Utils_Type
::T_INT
);
73 $field['dataPattern'] = CRM_Utils_Array
::value('dataPattern', $field, '//');
74 $field['headerPattern'] = CRM_Utils_Array
::value('headerPattern', $field, '//');
75 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
78 $this->_newActivity
= [];
80 $this->setActiveFields($this->_mapperKeys
);
82 // FIXME: we should do this in one place together with Form/MapField.php
83 $this->_contactIdIndex
= -1;
86 foreach ($this->_mapperKeys
as $key) {
88 case 'target_contact_id':
89 case 'external_identifier':
90 $this->_contactIdIndex
= $index;
98 * Handle the values in mapField mode.
100 * @param array $values
101 * The array of values belonging to this line.
105 public function mapField(&$values) {
106 return CRM_Import_Parser
::VALID
;
110 * Handle the values in preview mode.
112 * @param array $values
113 * The array of values belonging to this line.
116 * the result of this processing
118 public function preview(&$values) {
119 return $this->summary($values);
123 * Handle the values in summary mode.
125 * @param array $values
126 * The array of values belonging to this line.
129 * the result of this processing
131 public function summary(&$values) {
133 // Check required fields if this is not an update.
134 if (!$this->getFieldValue($values, 'activity_id')) {
135 if (!$this->getFieldValue($values, 'activity_label')
136 && !$this->getFieldValue($values, 'activity_type_id')) {
137 throw new CRM_Core_Exception(ts('Missing required fields: Activity type label or Activity type ID'));
139 if (!$this->getFieldValue($values, 'activity_date_time')) {
140 throw new CRM_Core_Exception(ts('Missing required fields'));
144 $this->validateActivityTypeIDAndLabel($values);
145 if ($this->getFieldValue($values, 'activity_date_time')
146 && !$this->isValidDate($this->getFieldValue($values, 'activity_date_time'))) {
147 throw new CRM_Core_Exception(ts('Invalid Activity Date'));
150 if ($this->getFieldValue($values, 'activity_engagement_level')
151 && !CRM_Utils_Rule
::positiveInteger($this->getFieldValue($values, 'activity_engagement_level'))) {
152 throw new CRM_Core_Exception(ts('Activity Engagement Index'));
154 $this->validateCustomFields($values);
156 catch (CRM_Core_Exception
$e) {
157 return $this->addError($values, [$e->getMessage()]);
160 return CRM_Import_Parser
::VALID
;
164 * Handle the values in import mode.
166 * @param int $onDuplicate
167 * The code for what action to take on duplicates.
168 * @param array $values
169 * The array of values belonging to this line.
172 * the result of this processing
173 * @throws \CRM_Core_Exception
175 public function import($onDuplicate, &$values) {
176 // First make sure this is a valid line
177 $response = $this->summary($values);
179 if ($response != CRM_Import_Parser
::VALID
) {
182 $params = $this->getActiveFieldParams();
183 $activityLabel = array_search('activity_label', $this->_mapperKeys
);
184 if ($activityLabel) {
185 $params = array_merge($params, ['activity_label' => $values[$activityLabel]]);
188 $session = CRM_Core_Session
::singleton();
189 $dateType = $session->get('dateTypes');
190 if (!isset($params['source_contact_id'])) {
191 $params['source_contact_id'] = $session->get('userID');
194 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity');
196 foreach ($params as $key => $val) {
197 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
198 if (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Date') {
199 CRM_Contact_Import_Parser_Contact
::formatCustomDate($params, $params, $dateType, $key);
201 elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
202 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
205 elseif ($key === 'activity_date_time') {
206 $params[$key] = CRM_Utils_Date
::formatDate($val, $dateType);
208 elseif ($key === 'activity_subject') {
209 $params['subject'] = $val;
212 // Date-Format part ends.
213 $formatError = $this->deprecated_activity_formatted_param($params, $params, TRUE);
216 array_unshift($values, $formatError['error_message']);
217 return CRM_Import_Parser
::ERROR
;
220 if ($this->_contactIdIndex
< 0) {
222 // Retrieve contact id using contact dedupe rule.
223 // Since we are supporting only individual's activity import.
224 $params['contact_type'] = 'Individual';
225 $params['version'] = 3;
226 $error = _civicrm_api3_deprecated_duplicate_formatted_contact($params);
228 if (CRM_Core_Error
::isAPIError($error, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
229 $matchedIDs = explode(',', $error['error_message']['params'][0]);
230 if (count($matchedIDs) > 1) {
231 array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported');
232 return CRM_Import_Parser
::ERROR
;
234 $cid = $matchedIDs[0];
235 $params['target_contact_id'] = $cid;
236 $params['version'] = 3;
237 $newActivity = civicrm_api('activity', 'create', $params);
238 if (!empty($newActivity['is_error'])) {
239 array_unshift($values, $newActivity['error_message']);
240 return CRM_Import_Parser
::ERROR
;
243 $this->_newActivity
[] = $newActivity['id'];
244 return CRM_Import_Parser
::VALID
;
247 // Using new Dedupe rule.
249 'contact_type' => 'Individual',
250 'used' => 'Unsupervised',
252 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
255 foreach ($fieldsArray as $value) {
256 if (array_key_exists(trim($value), $params)) {
257 $paramValue = $params[trim($value)];
258 if (is_array($paramValue)) {
259 $disp .= $params[trim($value)][0][trim($value)] . " ";
262 $disp .= $params[trim($value)] . " ";
267 if (!empty($params['external_identifier'])) {
269 $disp .= "AND {$params['external_identifier']}";
272 $disp = $params['external_identifier'];
276 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
277 return CRM_Import_Parser
::ERROR
;
279 if (!empty($params['external_identifier'])) {
280 $targetContactId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
281 $params['external_identifier'], 'id', 'external_identifier'
284 if (!empty($params['target_contact_id']) &&
285 $params['target_contact_id'] != $targetContactId
287 array_unshift($values, 'Mismatch of External ID:' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
288 return CRM_Import_Parser
::ERROR
;
290 if ($targetContactId) {
291 $params['target_contact_id'] = $targetContactId;
294 array_unshift($values, 'No Matching Contact for External ID:' . $params['external_identifier']);
295 return CRM_Import_Parser
::ERROR
;
299 $params['version'] = 3;
300 $newActivity = civicrm_api('activity', 'create', $params);
301 if (!empty($newActivity['is_error'])) {
302 array_unshift($values, $newActivity['error_message']);
303 return CRM_Import_Parser
::ERROR
;
306 $this->_newActivity
[] = $newActivity['id'];
307 return CRM_Import_Parser
::VALID
;
311 * take the input parameter list as specified in the data model and
312 * convert it into the same format that we use in QF and BAO object
314 * @param array $params
315 * Associative array of property name/value.
316 * pairs to insert in new contact.
317 * @param array $values
318 * The reformatted properties that we can use internally.
320 * @param array|bool $create Is the formatted Values array going to
321 * be used for CRM_Activity_BAO_Activity::create()
323 * @return array|CRM_Error
325 protected function deprecated_activity_formatted_param(&$params, &$values, $create = FALSE) {
326 // copy all the activity fields as is
327 $fields = CRM_Activity_DAO_Activity
::fields();
328 _civicrm_api3_store_values($fields, $params, $values);
330 foreach ($params as $key => $value) {
331 // ignore empty values or empty arrays etc
332 if (CRM_Utils_System
::isNull($value)) {
336 if ($key == 'target_contact_id') {
337 if (!CRM_Utils_Rule
::integer($value)) {
338 return civicrm_api3_create_error("contact_id not valid: $value");
340 $contactID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value");
342 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
351 * Get the value for the given field from the row of values.
354 * @param string $fieldName
356 * @return null|string
358 protected function getFieldValue(array $row, string $fieldName) {
359 if (!is_numeric($this->getFieldIndex($fieldName))) {
362 return $row[$this->getFieldIndex($fieldName)] ??
NULL;
366 * Get the index for the given field.
368 * @param string $fieldName
372 protected function getFieldIndex(string $fieldName) {
373 return array_search($fieldName, $this->_mapperKeys
, TRUE);
378 * Add an error to the values.
380 * @param array $values
381 * @param array $error
385 protected function addError(array &$values, array $error): int {
386 array_unshift($values, implode(';', $error));
387 return CRM_Import_Parser
::ERROR
;
391 * Validate that the activity type id does not conflict with the label.
393 * @param array $values
396 * @throws \CRM_Core_Exception
398 protected function validateActivityTypeIDAndLabel(array $values): void
{
399 $activityLabel = $this->getFieldValue($values, 'activity_label');
400 $activityTypeID = $this->getFieldValue($values, 'activity_type_id');
401 if ($activityLabel && $activityTypeID
402 && $activityLabel !== CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $activityTypeID)) {
403 throw new CRM_Core_Exception(ts('Activity type label and Activity type ID are in conflict'));
408 * Is the supplied date field valid based on selected date format.
410 * @param string $value
414 protected function isValidDate(string $value): bool {
415 return (bool) CRM_Utils_Date
::formatDate($value, CRM_Core_Session
::singleton()->get('dateTypes'));
419 * Validate custom fields.
421 * @param array $values
423 * @throws \CRM_Core_Exception
425 protected function validateCustomFields($values):void
{
426 $this->setActiveFieldValues($values);
427 $params = $this->getActiveFieldParams();
428 $errorMessage = NULL;
429 // Checking error in custom data.
430 $params['contact_type'] = 'Activity';
431 CRM_Contact_Import_Parser_Contact
::isErrorInCustomData($params, $errorMessage);
433 throw new CRM_Core_Exception('Invalid value for field(s) : ' . $errorMessage);