Merge branch '5.34' of https://github.com/civicrm/civicrm-core into upit
[civicrm-core.git] / CRM / Activity / Import / Parser / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18
19 /**
20 * Class to parse activity csv files.
21 */
22 class CRM_Activity_Import_Parser_Activity extends CRM_Activity_Import_Parser {
23
24 protected $_mapperKeys;
25
26 private $_contactIdIndex;
27
28 /**
29 * Array of successfully imported activity id's
30 *
31 * @var array
32 */
33 protected $_newActivity;
34
35 /**
36 * Class constructor.
37 *
38 * @param array $mapperKeys
39 */
40 public function __construct($mapperKeys) {
41 parent::__construct();
42 $this->_mapperKeys = $mapperKeys;
43 }
44
45 /**
46 * Function of undocumented functionality required by the interface.
47 */
48 protected function fini() {}
49
50 /**
51 * The initializer code, called before the processing.
52 */
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(),
57 $activityTarget
58 );
59
60 $fields = array_merge($fields, [
61 'source_contact_id' => [
62 'title' => ts('Source Contact'),
63 'headerPattern' => '/Source.Contact?/i',
64 ],
65 'activity_label' => [
66 'title' => ts('Activity Type Label'),
67 'headerPattern' => '/(activity.)?type label?/i',
68 ],
69 ]);
70
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']);
76 }
77
78 $this->_newActivity = [];
79
80 $this->setActiveFields($this->_mapperKeys);
81
82 // FIXME: we should do this in one place together with Form/MapField.php
83 $this->_contactIdIndex = -1;
84
85 $index = 0;
86 foreach ($this->_mapperKeys as $key) {
87 switch ($key) {
88 case 'target_contact_id':
89 case 'external_identifier':
90 $this->_contactIdIndex = $index;
91 break;
92 }
93 $index++;
94 }
95 }
96
97 /**
98 * Handle the values in mapField mode.
99 *
100 * @param array $values
101 * The array of values belonging to this line.
102 *
103 * @return bool
104 */
105 public function mapField(&$values) {
106 return CRM_Import_Parser::VALID;
107 }
108
109 /**
110 * Handle the values in preview mode.
111 *
112 * @param array $values
113 * The array of values belonging to this line.
114 *
115 * @return bool
116 * the result of this processing
117 */
118 public function preview(&$values) {
119 return $this->summary($values);
120 }
121
122 /**
123 * Handle the values in summary mode.
124 *
125 * @param array $values
126 * The array of values belonging to this line.
127 *
128 * @return bool
129 * the result of this processing
130 */
131 public function summary(&$values) {
132 $this->setActiveFieldValues($values);
133
134 try {
135 // Check required fields if this is not an update.
136 if (!$this->getFieldValue($values, 'activity_id')) {
137 if (!$this->getFieldValue($values, 'activity_label')
138 && !$this->getFieldValue($values, 'activity_type_id')) {
139 throw new CRM_Core_Exception(ts('Missing required fields: Activity type label or Activity type ID'));
140 }
141 if (!$this->getFieldValue($values, 'activity_date_time')) {
142 throw new CRM_Core_Exception(ts('Missing required fields'));
143 }
144 }
145
146 $this->validateActivityTypeIDAndLabel($values);
147 if ($this->getFieldValue($values, 'activity_date_time')
148 && !$this->isValidDate($this->getFieldValue($values, 'activity_date_time'))) {
149 throw new CRM_Core_Exception(ts('Invalid Activity Date'));
150 }
151 }
152 catch (CRM_Core_Exception $e) {
153 return $this->addError($values, [$e->getMessage()]);
154 }
155
156 $params = $this->getActiveFieldParams();
157
158 $errorMessage = NULL;
159
160 foreach ($params as $key => $val) {
161 if ($key == 'activity_engagement_level' && $val &&
162 !CRM_Utils_Rule::positiveInteger($val)
163 ) {
164 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity Engagement Index', $errorMessage);
165 }
166 }
167 // Date-Format part ends.
168
169 // Checking error in custom data.
170 $params['contact_type'] = $this->_contactType ?? 'Activity';
171
172 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
173
174 if ($errorMessage) {
175 $tempMsg = "Invalid value for field(s) : $errorMessage";
176 array_unshift($values, $tempMsg);
177 $errorMessage = NULL;
178 return CRM_Import_Parser::ERROR;
179 }
180
181 return CRM_Import_Parser::VALID;
182 }
183
184 /**
185 * Handle the values in import mode.
186 *
187 * @param int $onDuplicate
188 * The code for what action to take on duplicates.
189 * @param array $values
190 * The array of values belonging to this line.
191 *
192 * @return bool
193 * the result of this processing
194 * @throws \CRM_Core_Exception
195 */
196 public function import($onDuplicate, &$values) {
197 // First make sure this is a valid line
198 $response = $this->summary($values);
199
200 if ($response != CRM_Import_Parser::VALID) {
201 return $response;
202 }
203 $params = $this->getActiveFieldParams();
204 $activityLabel = array_search('activity_label', $this->_mapperKeys);
205 if ($activityLabel) {
206 $params = array_merge($params, ['activity_label' => $values[$activityLabel]]);
207 }
208 // For date-Formats.
209 $session = CRM_Core_Session::singleton();
210 $dateType = $session->get('dateTypes');
211 if (!isset($params['source_contact_id'])) {
212 $params['source_contact_id'] = $session->get('userID');
213 }
214
215 $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
216
217 foreach ($params as $key => $val) {
218 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
219 if (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Date') {
220 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
221 }
222 elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
223 $params[$key] = CRM_Utils_String::strtoboolstr($val);
224 }
225 }
226 elseif ($key === 'activity_date_time') {
227 $params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
228 }
229 elseif ($key === 'activity_subject') {
230 $params['subject'] = $val;
231 }
232 }
233 // Date-Format part ends.
234 $formatError = $this->deprecated_activity_formatted_param($params, $params, TRUE);
235
236 if ($formatError) {
237 array_unshift($values, $formatError['error_message']);
238 return CRM_Import_Parser::ERROR;
239 }
240
241 if ($this->_contactIdIndex < 0) {
242
243 // Retrieve contact id using contact dedupe rule.
244 // Since we are supporting only individual's activity import.
245 $params['contact_type'] = 'Individual';
246 $params['version'] = 3;
247 $error = _civicrm_api3_deprecated_duplicate_formatted_contact($params);
248
249 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
250 $matchedIDs = explode(',', $error['error_message']['params'][0]);
251 if (count($matchedIDs) > 1) {
252 array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported');
253 return CRM_Import_Parser::ERROR;
254 }
255 $cid = $matchedIDs[0];
256 $params['target_contact_id'] = $cid;
257 $params['version'] = 3;
258 $newActivity = civicrm_api('activity', 'create', $params);
259 if (!empty($newActivity['is_error'])) {
260 array_unshift($values, $newActivity['error_message']);
261 return CRM_Import_Parser::ERROR;
262 }
263
264 $this->_newActivity[] = $newActivity['id'];
265 return CRM_Import_Parser::VALID;
266
267 }
268 // Using new Dedupe rule.
269 $ruleParams = [
270 'contact_type' => 'Individual',
271 'used' => 'Unsupervised',
272 ];
273 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
274
275 $disp = NULL;
276 foreach ($fieldsArray as $value) {
277 if (array_key_exists(trim($value), $params)) {
278 $paramValue = $params[trim($value)];
279 if (is_array($paramValue)) {
280 $disp .= $params[trim($value)][0][trim($value)] . " ";
281 }
282 else {
283 $disp .= $params[trim($value)] . " ";
284 }
285 }
286 }
287
288 if (!empty($params['external_identifier'])) {
289 if ($disp) {
290 $disp .= "AND {$params['external_identifier']}";
291 }
292 else {
293 $disp = $params['external_identifier'];
294 }
295 }
296
297 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
298 return CRM_Import_Parser::ERROR;
299 }
300 if (!empty($params['external_identifier'])) {
301 $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
302 $params['external_identifier'], 'id', 'external_identifier'
303 );
304
305 if (!empty($params['target_contact_id']) &&
306 $params['target_contact_id'] != $targetContactId
307 ) {
308 array_unshift($values, 'Mismatch of External ID:' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
309 return CRM_Import_Parser::ERROR;
310 }
311 if ($targetContactId) {
312 $params['target_contact_id'] = $targetContactId;
313 }
314 else {
315 array_unshift($values, 'No Matching Contact for External ID:' . $params['external_identifier']);
316 return CRM_Import_Parser::ERROR;
317 }
318 }
319
320 $params['version'] = 3;
321 $newActivity = civicrm_api('activity', 'create', $params);
322 if (!empty($newActivity['is_error'])) {
323 array_unshift($values, $newActivity['error_message']);
324 return CRM_Import_Parser::ERROR;
325 }
326
327 $this->_newActivity[] = $newActivity['id'];
328 return CRM_Import_Parser::VALID;
329 }
330
331 /**
332 * take the input parameter list as specified in the data model and
333 * convert it into the same format that we use in QF and BAO object
334 *
335 * @param array $params
336 * Associative array of property name/value.
337 * pairs to insert in new contact.
338 * @param array $values
339 * The reformatted properties that we can use internally.
340 *
341 * @param array|bool $create Is the formatted Values array going to
342 * be used for CRM_Activity_BAO_Activity::create()
343 *
344 * @return array|CRM_Error
345 */
346 protected function deprecated_activity_formatted_param(&$params, &$values, $create = FALSE) {
347 // copy all the activity fields as is
348 $fields = CRM_Activity_DAO_Activity::fields();
349 _civicrm_api3_store_values($fields, $params, $values);
350
351 foreach ($params as $key => $value) {
352 // ignore empty values or empty arrays etc
353 if (CRM_Utils_System::isNull($value)) {
354 continue;
355 }
356
357 if ($key == 'target_contact_id') {
358 if (!CRM_Utils_Rule::integer($value)) {
359 return civicrm_api3_create_error("contact_id not valid: $value");
360 }
361 $contactID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value");
362 if (!$contactID) {
363 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
364 }
365 }
366 }
367 return NULL;
368 }
369
370 /**
371 *
372 * Get the value for the given field from the row of values.
373 *
374 * @param array $row
375 * @param string $fieldName
376 *
377 * @return null|string
378 */
379 protected function getFieldValue(array $row, string $fieldName) {
380 if (!is_numeric($this->getFieldIndex($fieldName))) {
381 return NULL;
382 }
383 return $row[$this->getFieldIndex($fieldName)] ?? NULL;
384 }
385
386 /**
387 * Get the index for the given field.
388 *
389 * @param string $fieldName
390 *
391 * @return false|int
392 */
393 protected function getFieldIndex(string $fieldName) {
394 return array_search($fieldName, $this->_mapperKeys, TRUE);
395
396 }
397
398 /**
399 * Add an error to the values.
400 *
401 * @param array $values
402 * @param array $error
403 *
404 * @return int
405 */
406 protected function addError(array &$values, array $error): int {
407 array_unshift($values, implode(';', $error));
408 return CRM_Import_Parser::ERROR;
409 }
410
411 /**
412 * Validate that the activity type id does not conflict with the label.
413 *
414 * @param array $values
415 *
416 * @return void
417 * @throws \CRM_Core_Exception
418 */
419 protected function validateActivityTypeIDAndLabel(array $values): void {
420 $activityLabel = $this->getFieldValue($values, 'activity_label');
421 $activityTypeID = $this->getFieldValue($values, 'activity_type_id');
422 if ($activityLabel && $activityTypeID
423 && $activityLabel !== CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $activityTypeID)) {
424 throw new CRM_Core_Exception(ts('Activity type label and Activity type ID are in conflict'));
425 }
426 }
427
428 /**
429 * Is the supplied date field valid based on selected date format.
430 *
431 * @param string $value
432 *
433 * @return bool
434 */
435 protected function isValidDate(string $value): bool {
436 return (bool) CRM_Utils_Date::formatDate($value, CRM_Core_Session::singleton()->get('dateTypes'));
437 }
438
439 }