Merge pull request #3886 from monishdeb/CRM-15150
[civicrm-core.git] / CRM / Contact / Import / ImportJob.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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 2009. |
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class acts like a psuedo-BAO for transient import job tables
38 */
719a6fec 39class CRM_Contact_Import_ImportJob {
6a488035
TO
40
41 protected $_tableName;
42 protected $_primaryKeyName;
43 protected $_statusFieldName;
44
45 protected $_doGeocodeAddress;
46 protected $_invalidRowCount;
47 protected $_conflictRowCount;
48 protected $_onDuplicate;
49 protected $_dedupe;
50 protected $_newGroupName;
51 protected $_newGroupDesc;
52 protected $_groups;
53 protected $_allGroups;
54 protected $_newTagName;
55 protected $_newTagDesc;
56 protected $_tag;
57 protected $_allTags;
58
59 protected $_mapper;
60 protected $_mapperKeys;
61 protected $_mapperLocTypes;
62 protected $_mapperPhoneTypes;
63 protected $_mapperImProviders;
64 protected $_mapperWebsiteTypes;
65 protected $_mapperRelated;
66 protected $_mapperRelatedContactType;
67 protected $_mapperRelatedContactDetails;
68 protected $_mapperRelatedContactLocType;
69 protected $_mapperRelatedContactPhoneType;
70 protected $_mapperRelatedContactImProvider;
71 protected $_mapperRelatedContactWebsiteType;
72 protected $_mapFields;
73
74 protected $_parser;
75
86538308
EM
76 /**
77 * @param null $tableName
78 * @param null $createSql
79 * @param bool $createTable
80 *
81 * @throws Exception
82 */
6a488035
TO
83 public function __construct($tableName = NULL, $createSql = NULL, $createTable = FALSE) {
84 $dao = new CRM_Core_DAO();
85 $db = $dao->getDatabaseConnection();
86
87 if ($createTable) {
88 if (!$createSql) {
89 CRM_Core_Error::fatal('Either an existing table name or an SQL query to build one are required');
90 }
91
92 // FIXME: we should regen this table's name if it exists rather than drop it
93 if (!$tableName) {
94 $tableName = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE));
95 }
96 $db->query("DROP TABLE IF EXISTS $tableName");
97 $db->query("CREATE TABLE $tableName ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci $createSql");
98 }
99
100 if (!$tableName) {
101 CRM_Core_Error::fatal('Import Table is required.');
102 }
103
104 $this->_tableName = $tableName;
105
106 //initialize the properties.
107 $properties = array(
108 'mapperKeys',
109 'mapperRelated',
110 'mapperLocTypes',
111 'mapperPhoneTypes',
112 'mapperImProviders',
113 'mapperWebsiteTypes',
114 'mapperRelatedContactType',
115 'mapperRelatedContactDetails',
116 'mapperRelatedContactLocType',
117 'mapperRelatedContactPhoneType',
118 'mapperRelatedContactImProvider',
119 'mapperRelatedContactWebsiteType',
120 );
121 foreach ($properties as $property) $this->{"_$property"} = array();
122 }
123
86538308
EM
124 /**
125 * @return null|string
126 */
6a488035
TO
127 public function getTableName() {
128 return $this->_tableName;
129 }
130
86538308
EM
131 /**
132 * @param bool $dropIfComplete
133 *
134 * @return bool
135 * @throws Exception
136 */
6a488035
TO
137 public function isComplete($dropIfComplete = TRUE) {
138 if (!$this->_statusFieldName) {
139 CRM_Core_Error::fatal("Could not get name of the import status field");
140 }
141 $query = "SELECT * FROM $this->_tableName
142 WHERE $this->_statusFieldName = 'NEW' LIMIT 1";
143 $result = CRM_Core_DAO::executeQuery($query);
144 if ($result->fetch()) {
145 return FALSE;
146 }
147 if ($dropIfComplete) {
148 $query = "DROP TABLE $this->_tableName";
149 CRM_Core_DAO::executeQuery($query);
150 }
151 return TRUE;
152 }
153
86538308
EM
154 /**
155 * @param $params
156 */
6a488035
TO
157 public function setJobParams(&$params) {
158 foreach ($params as $param => $value) {
0e6e8724
DL
159 $fldName = "_$param";
160 $this->$fldName = $value;
6a488035
TO
161 }
162 }
163
86538308
EM
164 /**
165 * @param $form
166 * @param int $timeout
167 */
6a488035
TO
168 public function runImport(&$form, $timeout = 55) {
169 $mapper = $this->_mapper;
170 $mapperFields = array();
b4f964d9 171 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
e7e657f0 172 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
cbf48754 173 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
b2b0530a 174 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
175
176 //initialize mapper perperty value.
177 $mapperPeroperties = array(
178 'mapperRelated' => 'mapperRelatedVal',
179 'mapperLocTypes' => 'mapperLocTypesVal',
180 'mapperPhoneTypes' => 'mapperPhoneTypesVal',
181 'mapperImProviders' => 'mapperImProvidersVal',
182 'mapperWebsiteTypes' => 'mapperWebsiteTypesVal',
183 'mapperRelatedContactType' => 'mapperRelatedContactTypeVal',
184 'mapperRelatedContactDetails' => 'mapperRelatedContactDetailsVal',
185 'mapperRelatedContactLocType' => 'mapperRelatedContactLocTypeVal',
186 'mapperRelatedContactPhoneType' => 'mapperRelatedContactPhoneTypeVal',
187 'mapperRelatedContactImProvider' => 'mapperRelatedContactImProviderVal',
188 'mapperRelatedContactWebsiteType' => 'mapperRelatedContactWebsiteTypeVal',
189 );
190
191 foreach ($mapper as $key => $value) {
192 //set respective mapper value to null.
193 foreach (array_values($mapperPeroperties) as $perpertyVal)$$perpertyVal = NULL;
194
6a488035 195 $fldName = CRM_Utils_Array::value(0, $mapper[$key]);
4ba3ef8e 196 $header = array($this->_mapFields[$fldName]);
6a488035
TO
197 $selOne = CRM_Utils_Array::value(1, $mapper[$key]);
198 $selTwo = CRM_Utils_Array::value(2, $mapper[$key]);
199 $selThree = CRM_Utils_Array::value(3, $mapper[$key]);
200 $this->_mapperKeys[$key] = $fldName;
201
202 //need to differentiate non location elements.
203 if ($selOne && is_numeric($selOne)) {
204 if ($fldName == 'url') {
205 $header[] = $websiteTypes[$selOne];
206 $mapperWebsiteTypesVal = $selOne;
207 }
208 else {
209 $header[] = $locationTypes[$selOne];
210 $mapperLocTypesVal = $selOne;
211 if ($selTwo && is_numeric($selTwo)) {
212 if ($fldName == 'phone') {
213 $header[] = $phoneTypes[$selTwo];
214 $mapperPhoneTypesVal = $selTwo;
215 }
216 elseif ($fldName == 'im') {
217 $header[] = $imProviders[$selTwo];
218 $mapperImProvidersVal = $selTwo;
219 }
220 }
221 }
222 }
223
224 $fldNameParts = explode('_', $fldName, 3);
225 $id = $fldNameParts[0];
226 $first = isset($fldNameParts[1]) ? $fldNameParts[1] : NULL;
227 $second = isset($fldNameParts[2]) ? $fldNameParts[2] : NULL;
228 if (($first == 'a' && $second == 'b') ||
229 ($first == 'b' && $second == 'a')
230 ) {
231
232 $header[] = ucwords(str_replace("_", " ", $selOne));
233
234 $relationType = new CRM_Contact_DAO_RelationshipType();
235 $relationType->id = $id;
236 $relationType->find(TRUE);
237 $mapperRelatedContactTypeVal = $relationType->{"contact_type_$second"};
238
239 $mapperRelatedVal = $fldName;
240 if ($selOne) {
241 $mapperRelatedContactDetailsVal = $selOne;
242 if ($selTwo) {
243 if ($selOne == 'url') {
244 $header[] = $websiteTypes[$selTwo];
245 $mapperRelatedContactWebsiteTypeVal = $selTwo;
246 }
247 else {
248 $header[] = $locationTypes[$selTwo];
249 $mapperRelatedContactLocTypeVal = $selTwo;
250 if ($selThree) {
251 if ($selOne == 'phone') {
252 $header[] = $phoneTypes[$selThree];
253 $mapperRelatedContactPhoneTypeVal = $selThree;
254 }
255 elseif ($selOne == 'im') {
256 $header[] = $imProviders[$selThree];
257 $mapperRelatedContactImProviderVal = $selThree;
258 }
259 }
260 }
261 }
262 }
263 }
264 $mapperFields[] = implode(' - ', $header);
265
266 //set the respective mapper param array values.
267 foreach ($mapperPeroperties as $mapperProKey => $mapperProVal) {
268 $this->{"_$mapperProKey"}[$key] = $$mapperProVal;
269 }
270 }
271
719a6fec 272 $this->_parser = new CRM_Contact_Import_Parser_Contact(
6a488035
TO
273 $this->_mapperKeys,
274 $this->_mapperLocTypes,
275 $this->_mapperPhoneTypes,
276 $this->_mapperImProviders,
277 $this->_mapperRelated,
278 $this->_mapperRelatedContactType,
279 $this->_mapperRelatedContactDetails,
280 $this->_mapperRelatedContactLocType,
281 $this->_mapperRelatedContactPhoneType,
282 $this->_mapperRelatedContactImProvider,
283 $this->_mapperWebsiteTypes,
284 $this->_mapperRelatedContactWebsiteType
285 );
286
287 $this->_parser->run($this->_tableName, $mapperFields,
a05662ef 288 CRM_Import_Parser::MODE_IMPORT,
6a488035
TO
289 $this->_contactType,
290 $this->_primaryKeyName,
291 $this->_statusFieldName,
292 $this->_onDuplicate,
293 $this->_statusID,
294 $this->_totalRowCount,
295 $this->_doGeocodeAddress,
719a6fec 296 CRM_Contact_Import_Parser::DEFAULT_TIMEOUT,
6a488035
TO
297 $this->_contactSubType,
298 $this->_dedupe
299 );
300
301 $contactIds = $this->_parser->getImportedContacts();
302
303 //get the related contactIds. CRM-2926
304 $relatedContactIds = $this->_parser->getRelatedImportedContacts();
305 if ($relatedContactIds) {
306 $contactIds = array_merge($contactIds, $relatedContactIds);
307 if ($form) {
308 $form->set('relatedCount', count($relatedContactIds));
309 }
310 }
311
312 if ($this->_newGroupName || count($this->_groups)) {
313 $groupAdditions = $this->_addImportedContactsToNewGroup($contactIds,
314 $this->_newGroupName,
315 $this->_newGroupDesc
316 );
317 if ($form) {
318 $form->set('groupAdditions', $groupAdditions);
319 }
320 }
321
322 if ($this->_newTagName || count($this->_tag)) {
323 $tagAdditions = $this->_tagImportedContactsWithNewTag($contactIds,
324 $this->_newTagName,
325 $this->_newTagDesc
326 );
327 if ($form) {
328 $form->set('tagAdditions', $tagAdditions);
329 }
330 }
331 }
332
86538308
EM
333 /**
334 * @param $form
335 */
6a488035 336 public function setFormVariables($form) {
a05662ef 337 $this->_parser->set($form, CRM_Import_Parser::MODE_IMPORT);
6a488035
TO
338 }
339
86538308
EM
340 /**
341 * @param $contactIds
342 * @param $newGroupName
343 * @param $newGroupDesc
344 *
345 * @return array|bool
346 */
6a488035
TO
347 private function _addImportedContactsToNewGroup($contactIds,
348 $newGroupName, $newGroupDesc
349 ) {
350
351 $newGroupId = NULL;
352
353 if ($newGroupName) {
354 /* Create a new group */
355
356 $gParams = array(
357 'title' => $newGroupName,
358 'description' => $newGroupDesc,
359 'is_active' => TRUE,
360 );
361 $group = CRM_Contact_BAO_Group::create($gParams);
362 $this->_groups[] = $newGroupId = $group->id;
363 }
364
365 if (is_array($this->_groups)) {
366 $groupAdditions = array();
367 foreach ($this->_groups as $groupId) {
368 $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
369 $totalCount = $addCount[1];
370 if ($groupId == $newGroupId) {
371 $name = $newGroupName;
372 $new = TRUE;
373 }
374 else {
375 $name = $this->_allGroups[$groupId];
376 $new = FALSE;
377 }
378 $groupAdditions[] = array(
379 'url' => CRM_Utils_System::url('civicrm/group/search',
380 'reset=1&force=1&context=smog&gid=' . $groupId
381 ),
382 'name' => $name,
383 'added' => $totalCount,
384 'notAdded' => $addCount[2],
385 'new' => $new,
386 );
387 }
388 return $groupAdditions;
389 }
390 return FALSE;
391 }
392
86538308
EM
393 /**
394 * @param $contactIds
395 * @param $newTagName
396 * @param $newTagDesc
397 *
398 * @return array|bool
399 */
6a488035
TO
400 private function _tagImportedContactsWithNewTag($contactIds,
401 $newTagName, $newTagDesc
402 ) {
403
404 $newTagId = NULL;
405 if ($newTagName) {
406 /* Create a new Tag */
407
408 $tagParams = array(
409 'name' => $newTagName,
410 'title' => $newTagName,
411 'description' => $newTagDesc,
412 'is_selectable' => TRUE,
413 'used_for' => 'civicrm_contact',
414 );
415 $id = array();
416 $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id);
417 $this->_tag[$addedTag->id] = 1;
418 }
419 //add Tag to Import
420
421 if (is_array($this->_tag)) {
422 $tagAdditions = array();
423 foreach ($this->_tag as $tagId => $val) {
424 $addTagCount = CRM_Core_BAO_EntityTag::addEntitiesToTag($contactIds, $tagId);
425 $totalTagCount = $addTagCount[1];
426 if (isset($addedTag) && $tagId == $addedTag->id) {
427 $tagName = $newTagName;
428 $new = TRUE;
429 }
430 else {
431 $tagName = $this->_allTags[$tagId];
432 $new = FALSE;
433 }
434 $tagAdditions[] = array(
435 'url' => CRM_Utils_System::url('civicrm/contact/search',
436 'reset=1&force=1&context=smog&id=' . $tagId
437 ),
438 'name' => $tagName,
439 'added' => $totalTagCount,
440 'notAdded' => $addTagCount[2],
441 'new' => $new,
442 );
443 }
444 return $tagAdditions;
445 }
446 return FALSE;
447 }
448
86538308
EM
449 /**
450 * @return array
451 */
6a488035
TO
452 public static function getIncompleteImportTables() {
453 $dao = new CRM_Core_DAO();
454 $database = $dao->database();
455 $query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA
456 WHERE TABLE_SCHEMA = ? AND
457 TABLE_NAME LIKE 'civicrm_import_job_%'
458 ORDER BY TABLE_NAME";
459 $result = CRM_Core_DAO::executeQuery($query, array($database));
460 $incompleteImportTables = array();
461 while ($importTable = $result->fetch()) {
462 if (!$this->isComplete($importTable)) {
463 $incompleteImportTables[] = $importTable;
464 }
465 }
466 return $incompleteImportTables;
467 }
468}
469