INFRA-132 - CRM/Activity - Convert single-line @param to multi-line
[civicrm-core.git] / CRM / Activity / Import / Parser / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 require_once 'api/api.php';
37
38 /**
39 * class to parse activity csv files
40 */
41 class CRM_Activity_Import_Parser_Activity extends CRM_Activity_Import_Parser {
42
43 protected $_mapperKeys;
44
45 private $_contactIdIndex;
46 private $_activityTypeIndex;
47 private $_activityLabelIndex;
48 private $_activityDateIndex;
49
50 /**
51 * Array of successfully imported activity id's
52 *
53 * @array
54 */
55 protected $_newActivity;
56
57 /**
58 * Class constructor
59 */
60 public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
61 parent::__construct();
62 $this->_mapperKeys = &$mapperKeys;
63 }
64
65 /**
66 * The initializer code, called before the processing
67 *
68 * @return void
69 */
70 public function init() {
71 $activityContact = CRM_Activity_BAO_ActivityContact::import();
72 $activityTarget['target_contact_id'] = $activityContact['contact_id'];
73 $fields = array_merge(CRM_Activity_BAO_Activity::importableFields(),
74 $activityTarget
75 );
76
77 $fields = array_merge($fields, array(
78 'source_contact_id' => array(
79 'title' => ts('Source Contact'),
80 'headerPattern' => '/Source.Contact?/i',
81 ),
82 'activity_label' => array(
83 'title' => ts('Activity Type Label'),
84 'headerPattern' => '/(activity.)?type label?/i',
85 )
86 ));
87
88 foreach ($fields as $name => $field) {
89 $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
90 $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
91 $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
92 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
93 }
94
95 $this->_newActivity = array();
96
97 $this->setActiveFields($this->_mapperKeys);
98
99 // FIXME: we should do this in one place together with Form/MapField.php
100 $this->_contactIdIndex = -1;
101 $this->_activityTypeIndex = -1;
102 $this->_activityLabelIndex = -1;
103 $this->_activityDateIndex = -1;
104
105 $index = 0;
106 foreach ($this->_mapperKeys as $key) {
107 switch ($key) {
108 case 'target_contact_id':
109 case 'external_identifier':
110 $this->_contactIdIndex = $index;
111 break;
112
113 case 'activity_label':
114 $this->_activityLabelIndex = $index;
115 break;
116
117 case 'activity_type_id':
118 $this->_activityTypeIndex = $index;
119 break;
120
121 case 'activity_date_time':
122 $this->_activityDateIndex = $index;
123 break;
124 }
125 $index++;
126 }
127 }
128
129 /**
130 * Handle the values in mapField mode
131 *
132 * @param array $values
133 * The array of values belonging to this line.
134 *
135 * @return boolean
136 */
137 public function mapField(&$values) {
138 return CRM_Import_Parser::VALID;
139 }
140
141 /**
142 * Handle the values in preview mode
143 *
144 * @param array $values
145 * The array of values belonging to this line.
146 *
147 * @return boolean the result of this processing
148 */
149 public function preview(&$values) {
150 return $this->summary($values);
151 }
152
153 /**
154 * Handle the values in summary mode
155 *
156 * @param array $values
157 * The array of values belonging to this line.
158 *
159 * @return boolean the result of this processing
160 */
161 public function summary(&$values) {
162 $erroneousField = NULL;
163 $response = $this->setActiveFieldValues($values, $erroneousField);
164 $index = -1;
165 $errorRequired = FALSE;
166
167 if ($this->_activityTypeIndex > -1 && $this->_activityLabelIndex > -1) {
168 array_unshift($values, ts('Please select either Activity Type ID OR Activity Type Label.'));
169 return CRM_Import_Parser::ERROR;
170 }
171 elseif ($this->_activityLabelIndex > -1) {
172 $index = $this->_activityLabelIndex;
173 }
174 elseif ($this->_activityTypeIndex > -1) {
175 $index = $this->_activityTypeIndex;
176 }
177
178 if ($index < 0 or $this->_activityDateIndex < 0) {
179 $errorRequired = TRUE;
180 }
181 else {
182 $errorRequired = !CRM_Utils_Array::value($index, $values) || !CRM_Utils_Array::value($this->_activityDateIndex, $values);
183 }
184
185 if ($errorRequired) {
186 array_unshift($values, ts('Missing required fields'));
187 return CRM_Import_Parser::ERROR;
188 }
189
190 $params = &$this->getActiveFieldParams();
191
192 $errorMessage = NULL;
193
194 //for date-Formats
195 $session = CRM_Core_Session::singleton();
196 $dateType = $session->get('dateTypes');
197 if (!isset($params['source_contact_id'])) {
198 $params['source_contact_id'] = $session->get('userID');
199 }
200 foreach ($params as $key => $val) {
201 if ($key == 'activity_date_time') {
202 if ($val) {
203 $dateValue = CRM_Utils_Date::formatDate($val, $dateType);
204 if ($dateValue) {
205 $params[$key] = $dateValue;
206 }
207 else {
208 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity date', $errorMessage);
209 }
210 }
211 }
212 elseif ($key == 'activity_engagement_level' && $val &&
213 !CRM_Utils_Rule::positiveInteger($val)
214 ) {
215 CRM_Contact_Import_Parser_Contact::addToErrorMsg('Activity Engagement Index', $errorMessage);
216 }
217 }
218 //date-Format part ends
219
220 //checking error in custom data
221 $params['contact_type'] = isset($this->_contactType) ? $this->_contactType : 'Activity';
222
223 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
224
225 if ($errorMessage) {
226 $tempMsg = "Invalid value for field(s) : $errorMessage";
227 array_unshift($values, $tempMsg);
228 $errorMessage = NULL;
229 return CRM_Import_Parser::ERROR;
230 }
231
232 return CRM_Import_Parser::VALID;
233 }
234
235 /**
236 * Handle the values in import mode
237 *
238 * @param int $onDuplicate
239 * The code for what action to take on duplicates.
240 * @param array $values
241 * The array of values belonging to this line.
242 *
243 * @return boolean the result of this processing
244 */
245 public function import($onDuplicate, &$values) {
246 // first make sure this is a valid line
247 $response = $this->summary($values);
248
249 if ($response != CRM_Import_Parser::VALID) {
250 return $response;
251 }
252 $params = &$this->getActiveFieldParams();
253 $activityLabel = array_search('activity_label', $this->_mapperKeys);
254 if ($activityLabel) {
255 $params = array_merge($params, array('activity_label' => $values[$activityLabel]));
256 }
257 //for date-Formats
258 $session = CRM_Core_Session::singleton();
259 $dateType = $session->get('dateTypes');
260 if (!isset($params['source_contact_id'])) {
261 $params['source_contact_id'] = $session->get('userID');
262 }
263 $formatted = array();
264 $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
265
266 foreach ($params as $key => $val) {
267 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
268 if ($key == 'activity_date_time' && $val) {
269 $params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
270 }
271 elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Date') {
272 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
273 }
274 elseif (!empty($customFields[$customFieldID]) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
275 $params[$key] = CRM_Utils_String::strtoboolstr($val);
276 }
277 }
278 elseif ($key == 'activity_date_time') {
279 $params[$key] = CRM_Utils_Date::formatDate($val, $dateType);
280 }
281 elseif ($key == 'activity_subject') {
282 $params['subject'] = $val;
283 }
284 }
285 //date-Format part ends
286 require_once 'CRM/Utils/DeprecatedUtils.php';
287 $formatError = _civicrm_api3_deprecated_activity_formatted_param($params, $params, TRUE);
288
289 if ($formatError) {
290 array_unshift($values, $formatError['error_message']);
291 return CRM_Import_Parser::ERROR;
292 }
293
294 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
295 CRM_Core_DAO::$_nullObject,
296 NULL,
297 'Activity'
298 );
299
300 if ($this->_contactIdIndex < 0) {
301
302 //retrieve contact id using contact dedupe rule.
303 //since we are support only individual's activity import.
304 $params['contact_type'] = 'Individual';
305 $params['version'] = 3;
306 $error = _civicrm_api3_deprecated_duplicate_formatted_contact($params);
307
308 if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
309 $matchedIDs = explode(',', $error['error_message']['params'][0]);
310 if (count($matchedIDs) > 1) {
311 array_unshift($values, 'Multiple matching contact records detected for this row. The activity was not imported');
312 return CRM_Import_Parser::ERROR;
313 }
314 else {
315 $cid = $matchedIDs[0];
316 $params['target_contact_id'] = $cid;
317 $params['version'] = 3;
318 $newActivity = civicrm_api('activity', 'create', $params);
319 if (!empty($newActivity['is_error'])) {
320 array_unshift($values, $newActivity['error_message']);
321 return CRM_Import_Parser::ERROR;
322 }
323
324 $this->_newActivity[] = $newActivity['id'];
325 return CRM_Import_Parser::VALID;
326 }
327 }
328 else {
329 // Using new Dedupe rule.
330 $ruleParams = array(
331 'contact_type' => 'Individual',
332 'used' => 'Unsupervised',
333 );
334 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
335
336 $disp = NULL;
337 foreach ($fieldsArray as $value) {
338 if (array_key_exists(trim($value), $params)) {
339 $paramValue = $params[trim($value)];
340 if (is_array($paramValue)) {
341 $disp .= $params[trim($value)][0][trim($value)] . " ";
342 }
343 else {
344 $disp .= $params[trim($value)] . " ";
345 }
346 }
347 }
348
349 if (!empty($params['external_identifier'])) {
350 if ($disp) {
351 $disp .= "AND {$params['external_identifier']}";
352 }
353 else {
354 $disp = $params['external_identifier'];
355 }
356 }
357
358 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
359 return CRM_Import_Parser::ERROR;
360 }
361 }
362 else {
363 if (!empty($params['external_identifier'])) {
364 $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
365 $params['external_identifier'], 'id', 'external_identifier'
366 );
367
368 if (!empty($params['target_contact_id']) &&
369 $params['target_contact_id'] != $targetContactId
370 ) {
371 array_unshift($values, 'Mismatch of External identifier :' . $params['external_identifier'] . ' and Contact Id:' . $params['target_contact_id']);
372 return CRM_Import_Parser::ERROR;
373 }
374 elseif ($targetContactId) {
375 $params['target_contact_id'] = $targetContactId;
376 }
377 else {
378 array_unshift($values, 'No Matching Contact for External identifier :' . $params['external_identifier']);
379 return CRM_Import_Parser::ERROR;
380 }
381 }
382
383 $params['version'] = 3;
384 $newActivity = civicrm_api('activity', 'create', $params);
385 if (!empty($newActivity['is_error'])) {
386 array_unshift($values, $newActivity['error_message']);
387 return CRM_Import_Parser::ERROR;
388 }
389
390 $this->_newActivity[] = $newActivity['id'];
391 return CRM_Import_Parser::VALID;
392 }
393 }
394
395 /**
396 * The initializer code, called before the processing
397 *
398 * @return void
399 */
400 public function fini() {}
401
402 }