Move remaining validation into the validation section
[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 try {
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'));
138 }
139 if (!$this->getFieldValue($values, 'activity_date_time')) {
140 throw new CRM_Core_Exception(ts('Missing required fields'));
141 }
142 }
143
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'));
148 }
149
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'));
153 }
154 $this->validateCustomFields($values);
155 }
156 catch (CRM_Core_Exception $e) {
157 return $this->addError($values, [$e->getMessage()]);
158 }
159
160 return CRM_Import_Parser::VALID;
161 }
162
163 /**
164 * Handle the values in import mode.
165 *
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.
170 *
171 * @return bool
172 * the result of this processing
173 * @throws \CRM_Core_Exception
174 */
175 public function import($onDuplicate, &$values) {
176 // First make sure this is a valid line
177 $response = $this->summary($values);
178
179 if ($response != CRM_Import_Parser::VALID) {
180 return $response;
181 }
182 $params = $this->getActiveFieldParams();
183 $activityLabel = array_search('activity_label', $this->_mapperKeys);
184 if ($activityLabel) {
185 $params = array_merge($params, ['activity_label' => $values[$activityLabel]]);
186 }
187 // For date-Formats.
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');
192 }
193
194 $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
195
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);
200 }
201 elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
202 $params[$key] = CRM_Utils_String::strtoboolstr($val);
203 }
204 }
205 elseif ($key === 'activity_date_time') {
206 $params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
207 }
208 elseif ($key === 'activity_subject') {
209 $params['subject'] = $val;
210 }
211 }
212 // Date-Format part ends.
213 $formatError = $this->deprecated_activity_formatted_param($params, $params, TRUE);
214
215 if ($formatError) {
216 array_unshift($values, $formatError['error_message']);
217 return CRM_Import_Parser::ERROR;
218 }
219
220 if ($this->_contactIdIndex < 0) {
221
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);
227
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;
233 }
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;
241 }
242
243 $this->_newActivity[] = $newActivity['id'];
244 return CRM_Import_Parser::VALID;
245
246 }
247 // Using new Dedupe rule.
248 $ruleParams = [
249 'contact_type' => 'Individual',
250 'used' => 'Unsupervised',
251 ];
252 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
253
254 $disp = NULL;
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)] . " ";
260 }
261 else {
262 $disp .= $params[trim($value)] . " ";
263 }
264 }
265 }
266
267 if (!empty($params['external_identifier'])) {
268 if ($disp) {
269 $disp .= "AND {$params['external_identifier']}";
270 }
271 else {
272 $disp = $params['external_identifier'];
273 }
274 }
275
276 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
277 return CRM_Import_Parser::ERROR;
278 }
279 if (!empty($params['external_identifier'])) {
280 $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
281 $params['external_identifier'], 'id', 'external_identifier'
282 );
283
284 if (!empty($params['target_contact_id']) &&
285 $params['target_contact_id'] != $targetContactId
286 ) {
287 array_unshift($values, 'Mismatch of External ID:' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
288 return CRM_Import_Parser::ERROR;
289 }
290 if ($targetContactId) {
291 $params['target_contact_id'] = $targetContactId;
292 }
293 else {
294 array_unshift($values, 'No Matching Contact for External ID:' . $params['external_identifier']);
295 return CRM_Import_Parser::ERROR;
296 }
297 }
298
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;
304 }
305
306 $this->_newActivity[] = $newActivity['id'];
307 return CRM_Import_Parser::VALID;
308 }
309
310 /**
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
313 *
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.
319 *
320 * @param array|bool $create Is the formatted Values array going to
321 * be used for CRM_Activity_BAO_Activity::create()
322 *
323 * @return array|CRM_Error
324 */
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);
329
330 foreach ($params as $key => $value) {
331 // ignore empty values or empty arrays etc
332 if (CRM_Utils_System::isNull($value)) {
333 continue;
334 }
335
336 if ($key == 'target_contact_id') {
337 if (!CRM_Utils_Rule::integer($value)) {
338 return civicrm_api3_create_error("contact_id not valid: $value");
339 }
340 $contactID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value");
341 if (!$contactID) {
342 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
343 }
344 }
345 }
346 return NULL;
347 }
348
349 /**
350 *
351 * Get the value for the given field from the row of values.
352 *
353 * @param array $row
354 * @param string $fieldName
355 *
356 * @return null|string
357 */
358 protected function getFieldValue(array $row, string $fieldName) {
359 if (!is_numeric($this->getFieldIndex($fieldName))) {
360 return NULL;
361 }
362 return $row[$this->getFieldIndex($fieldName)] ?? NULL;
363 }
364
365 /**
366 * Get the index for the given field.
367 *
368 * @param string $fieldName
369 *
370 * @return false|int
371 */
372 protected function getFieldIndex(string $fieldName) {
373 return array_search($fieldName, $this->_mapperKeys, TRUE);
374
375 }
376
377 /**
378 * Add an error to the values.
379 *
380 * @param array $values
381 * @param array $error
382 *
383 * @return int
384 */
385 protected function addError(array &$values, array $error): int {
386 array_unshift($values, implode(';', $error));
387 return CRM_Import_Parser::ERROR;
388 }
389
390 /**
391 * Validate that the activity type id does not conflict with the label.
392 *
393 * @param array $values
394 *
395 * @return void
396 * @throws \CRM_Core_Exception
397 */
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'));
404 }
405 }
406
407 /**
408 * Is the supplied date field valid based on selected date format.
409 *
410 * @param string $value
411 *
412 * @return bool
413 */
414 protected function isValidDate(string $value): bool {
415 return (bool) CRM_Utils_Date::formatDate($value, CRM_Core_Session::singleton()->get('dateTypes'));
416 }
417
418 /**
419 * Validate custom fields.
420 *
421 * @param array $values
422 *
423 * @throws \CRM_Core_Exception
424 */
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);
432 if ($errorMessage) {
433 throw new CRM_Core_Exception('Invalid value for field(s) : ' . $errorMessage);
434 }
435 }
436
437 }