3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class previews the uploaded file and returns summary
40 class CRM_Contact_Import_Form_Preview
extends CRM_Import_Form_Preview
{
43 * Function to set variables up before form is built
48 public function preProcess() {
49 //get the data from the session
50 $dataValues = $this->get('dataValues');
51 $mapper = $this->get('mapper');
52 $invalidRowCount = $this->get('invalidRowCount');
53 $conflictRowCount = $this->get('conflictRowCount');
54 $mismatchCount = $this->get('unMatchCount');
55 $columnNames = $this->get('columnNames');
58 $this->assign('columnNames', $columnNames);
60 //get the mapping name displayed if the mappingId is set
61 $mappingId = $this->get('loadMappingId');
63 $mapDAO = new CRM_Core_DAO_Mapping();
64 $mapDAO->id
= $mappingId;
66 $this->assign('loadedMapping', $mappingId);
67 $this->assign('savedName', $mapDAO->name
);
70 $this->assign('rowDisplayCount', 2);
72 $groups = CRM_Core_PseudoConstant
::group();
73 $this->set('groups', $groups);
75 $tag = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
77 $this->set('tag', $tag);
80 if ($invalidRowCount) {
81 $urlParams = 'type=' . CRM_Import_Parser
::ERROR
. '&parser=CRM_Contact_Import_Parser';
82 $this->set('downloadErrorRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
85 if ($conflictRowCount) {
86 $urlParams = 'type=' . CRM_Import_Parser
::CONFLICT
. '&parser=CRM_Contact_Import_Parser';
87 $this->set('downloadConflictRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
91 $urlParams = 'type=' . CRM_Import_Parser
::NO_MATCH
. '&parser=CRM_Contact_Import_Parser';
92 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
96 'mapper', 'locations', 'phones', 'ims',
97 'dataValues', 'columnCount',
98 'totalRowCount', 'validRowCount',
99 'invalidRowCount', 'conflictRowCount',
100 'downloadErrorRecordsUrl',
101 'downloadConflictRecordsUrl',
102 'downloadMismatchRecordsUrl',
103 'related', 'relatedContactDetails', 'relatedContactLocType',
104 'relatedContactPhoneType', 'relatedContactImProvider', 'websites',
105 'relatedContactWebsiteType',
108 foreach ($properties as $property) {
109 $this->assign($property, $this->get($property));
112 $statusID = $this->get('statusID');
114 $statusID = md5(uniqid(rand(), TRUE));
115 $this->set('statusID', $statusID);
117 $statusUrl = CRM_Utils_System
::url('civicrm/ajax/status', "id={$statusID}", FALSE, NULL, FALSE);
118 $this->assign('statusUrl', $statusUrl);
120 $showColNames = TRUE;
121 if ('CRM_Import_DataSource_CSV' == $this->get('dataSource') &&
122 !$this->get('skipColumnHeader')
124 $showColNames = FALSE;
126 $this->assign('showColNames', $showColNames);
130 * Function to actually build the form
135 public function buildQuickForm() {
136 $this->addElement('text', 'newGroupName', ts('Name for new group'));
137 $this->addElement('text', 'newGroupDesc', ts('Description of new group'));
139 $groups = $this->get('groups');
141 if (!empty($groups)) {
142 $this->addElement('select', 'groups', ts('Add imported records to existing group(s)'), $groups, array('multiple' => "multiple", 'size' => 5));
146 $this->addElement('text', 'newTagName', ts('Tag'));
147 $this->addElement('text', 'newTagDesc', ts('Description'));
149 $tag = $this->get('tag');
151 foreach ($tag as $tagID => $tagName) {
152 $this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
156 $path = "_qf_MapField_display=true";
157 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String', $form);
158 if (CRM_Utils_Rule
::qfKey($qfKey)) {
159 $path .= "&qfKey=$qfKey";
162 $previousURL = CRM_Utils_System
::url('civicrm/import/contact', $path, FALSE, NULL, FALSE);
163 $cancelURL = CRM_Utils_System
::url('civicrm/import/contact', 'reset=1');
168 'name' => ts('<< Previous'),
169 'js' => array('onclick' => "location.href='{$previousURL}'; return false;"),
173 'name' => ts('Import Now >>'),
174 'spacing' => ' ',
176 'js' => array('onclick' => "return verify( );"),
180 'name' => ts('Cancel'),
181 'js' => array('onclick' => "location.href='{$cancelURL}'; return false;"),
185 $this->addButtons($buttons);
187 $this->addFormRule(array('CRM_Contact_Import_Form_Preview', 'formRule'), $this);
191 * global validation rules for the form
193 * @param array $fields posted values of the form
195 * @return array list of errors to be posted back to the form
199 static function formRule($fields, $files, $self) {
201 $invalidTagName = $invalidGroupName = FALSE;
203 if (!empty($fields['newTagName'])) {
204 if (!CRM_Utils_Rule
::objectExists(trim($fields['newTagName']),
205 array('CRM_Core_DAO_Tag')
207 $errors['newTagName'] = ts('Tag \'%1\' already exists.',
208 array(1 => $fields['newTagName'])
210 $invalidTagName = TRUE;
214 if (!empty($fields['newGroupName'])) {
215 $title = trim($fields['newGroupName']);
216 $name = CRM_Utils_String
::titleToVar($title);
217 $query = 'select count(*) from civicrm_group where name like %1 OR title like %2';
218 $grpCnt = CRM_Core_DAO
::singleValueQuery(
221 1 => array($name, 'String'),
222 2 => array($title, 'String'),
226 $invalidGroupName = TRUE;
227 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
231 $self->assign('invalidTagName', $invalidTagName);
232 $self->assign('invalidGroupName', $invalidGroupName);
234 return empty($errors) ?
TRUE : $errors;
238 * Process the mapped fields and map it into the uploaded file
239 * preview the file and extract some summary statistics
244 public function postProcess() {
246 $importJobParams = array(
247 'doGeocodeAddress' => $this->controller
->exportValue('DataSource', 'doGeocodeAddress'),
248 'invalidRowCount' => $this->get('invalidRowCount'),
249 'conflictRowCount' => $this->get('conflictRowCount'),
250 'onDuplicate' => $this->get('onDuplicate'),
251 'dedupe' => $this->get('dedupe'),
252 'newGroupName' => $this->controller
->exportValue($this->_name
, 'newGroupName'),
253 'newGroupDesc' => $this->controller
->exportValue($this->_name
, 'newGroupDesc'),
254 'groups' => $this->controller
->exportValue($this->_name
, 'groups'),
255 'allGroups' => $this->get('groups'),
256 'newTagName' => $this->controller
->exportValue($this->_name
, 'newTagName'),
257 'newTagDesc' => $this->controller
->exportValue($this->_name
, 'newTagDesc'),
258 'tag' => $this->controller
->exportValue($this->_name
, 'tag'),
259 'allTags' => $this->get('tag'),
260 'mapper' => $this->controller
->exportValue('MapField', 'mapper'),
261 'mapFields' => $this->get('fields'),
262 'contactType' => $this->get('contactType'),
263 'contactSubType' => $this->get('contactSubType'),
264 'primaryKeyName' => $this->get('primaryKeyName'),
265 'statusFieldName' => $this->get('statusFieldName'),
266 'statusID' => $this->get('statusID'),
267 'totalRowCount' => $this->get('totalRowCount'),
270 $tableName = $this->get('importTableName');
271 $importJob = new CRM_Contact_Import_ImportJob($tableName);
272 $importJob->setJobParams($importJobParams);
274 // If ACL applies to the current user, update cache before running the import.
275 if (!CRM_Core_Permission
::check('view all contacts')) {
276 $session = CRM_Core_Session
::singleton();
277 $userID = $session->get('userID');
278 CRM_ACL_BAO_Cache
::updateEntry($userID);
282 $importJob->runImport($this);
284 // update cache after we done with runImport
285 if (!CRM_Core_Permission
::check('view all contacts')) {
286 CRM_ACL_BAO_Cache
::updateEntry($userID);
290 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
292 // add all the necessary variables to the form
293 $importJob->setFormVariables($this);
295 // check if there is any error occured
296 $errorStack = CRM_Core_Error
::singleton();
297 $errors = $errorStack->getErrors();
298 $errorMessage = array();
300 if (is_array($errors)) {
301 foreach ($errors as $key => $value) {
302 $errorMessage[] = $value['message'];
305 // there is no fileName since this is a sql import
307 $config = CRM_Core_Config
::singleton();
308 $errorFile = $config->uploadDir
. "sqlImport.error.log";
309 if ($fd = fopen($errorFile, 'w')) {
310 fwrite($fd, implode('\n', $errorMessage));
314 $this->set('errorFile', $errorFile);
316 $urlParams = 'type=' . CRM_Import_Parser
::ERROR
. '&parser=CRM_Contact_Import_Parser';
317 $this->set('downloadErrorRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
319 $urlParams = 'type=' . CRM_Import_Parser
::CONFLICT
. '&parser=CRM_Contact_Import_Parser';
320 $this->set('downloadConflictRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
322 $urlParams = 'type=' . CRM_Import_Parser
::NO_MATCH
. '&parser=CRM_Contact_Import_Parser';
323 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
327 //if job complete drop table.
328 $importJob->isComplete(TRUE);
332 * Process the mapped fields and map it into the uploaded file
333 * preview the file and extract some summary statistics
338 public function postProcessOld() {
340 $doGeocodeAddress = $this->controller
->exportValue('DataSource', 'doGeocodeAddress');
341 $invalidRowCount = $this->get('invalidRowCount');
342 $conflictRowCount = $this->get('conflictRowCount');
343 $onDuplicate = $this->get('onDuplicate');
344 $newGroupName = $this->controller
->exportValue($this->_name
, 'newGroupName');
345 $newGroupDesc = $this->controller
->exportValue($this->_name
, 'newGroupDesc');
346 $groups = $this->controller
->exportValue($this->_name
, 'groups');
347 $allGroups = $this->get('groups');
348 $newTagName = $this->controller
->exportValue($this->_name
, 'newTagName');
349 $newTagDesc = $this->controller
->exportValue($this->_name
, 'newTagDesc');
350 $tag = $this->controller
->exportValue($this->_name
, 'tag');
351 $allTags = $this->get('tag');
353 $mapper = $this->controller
->exportValue('MapField', 'mapper');
355 $mapperKeys = array();
356 $mapperLocTypes = array();
357 $mapperPhoneTypes = array();
358 $mapperRelated = array();
359 $mapperRelatedContactType = array();
360 $mapperRelatedContactDetails = array();
361 $mapperRelatedContactLocType = array();
362 $mapperRelatedContactPhoneType = array();
364 foreach ($mapper as $key => $value) {
365 $mapperKeys[$key] = $mapper[$key][0];
366 if (is_numeric($mapper[$key][1])) {
367 $mapperLocTypes[$key] = $mapper[$key][1];
370 $mapperLocTypes[$key] = NULL;
373 if (CRM_Utils_Array
::value($key, $mapperKeys) == 'phone') {
374 $mapperPhoneTypes[$key] = $mapper[$key][2];
377 $mapperPhoneTypes[$key] = NULL;
380 list($id, $first, $second) = explode('_', $mapper[$key][0]);
381 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
382 $relationType = new CRM_Contact_DAO_RelationshipType();
383 $relationType->id
= $id;
384 $relationType->find(TRUE);
385 $fieldName = "contact_type_$second";
386 $mapperRelatedContactType[$key] = $relationType->$fieldName;
387 $mapperRelated[$key] = $mapper[$key][0];
388 $mapperRelatedContactDetails[$key] = $mapper[$key][1];
389 $mapperRelatedContactLocType[$key] = $mapper[$key][2];
390 $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
393 $mapperRelated[$key] = NULL;
394 $mapperRelatedContactType[$key] = NULL;
395 $mapperRelatedContactDetails[$key] = NULL;
396 $mapperRelatedContactLocType[$key] = NULL;
397 $mapperRelatedContactPhoneType[$key] = NULL;
401 $parser = new CRM_Contact_Import_Parser_Contact($mapperKeys, $mapperLocTypes,
402 $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType,
403 $mapperRelatedContactDetails, $mapperRelatedContactLocType,
404 $mapperRelatedContactPhoneType
407 $mapFields = $this->get('fields');
409 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
410 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
412 foreach ($mapper as $key => $value) {
414 list($id, $first, $second) = explode('_', $mapper[$key][0]);
415 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
416 $relationType = new CRM_Contact_DAO_RelationshipType();
417 $relationType->id
= $id;
418 $relationType->find(TRUE);
420 $header[] = $relationType->name_a_b
;
421 $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
423 if (isset($mapper[$key][2])) {
424 $header[] = $locationTypes[$mapper[$key][2]];
426 if (isset($mapper[$key][3])) {
427 $header[] = $phoneTypes[$mapper[$key][3]];
431 if (isset($mapFields[$mapper[$key][0]])) {
432 $header[] = $mapFields[$mapper[$key][0]];
433 if (isset($mapper[$key][1])) {
434 $header[] = $locationTypes[$mapper[$key][1]];
436 if (isset($mapper[$key][2])) {
437 $header[] = $phoneTypes[$mapper[$key][2]];
441 $mapperFields[] = implode(' - ', $header);
444 $tableName = $this->get('importTableName');
445 //print "Running parser on table: $tableName<br/>";
446 $parser->run($tableName, $mapperFields,
447 CRM_Import_Parser
::MODE_IMPORT
,
448 $this->get('contactType'),
449 $this->get('primaryKeyName'),
450 $this->get('statusFieldName'),
452 $this->get('statusID'),
453 $this->get('totalRowCount'),
455 CRM_Contact_Import_Parser
::DEFAULT_TIMEOUT
,
456 $this->get('contactSubType'),
460 // add the new contacts to selected groups
461 $contactIds = &$parser->getImportedContacts();
463 // add the new related contacts to selected groups
464 $relatedContactIds = &$parser->getRelatedImportedContacts();
466 $this->set('relatedCount', count($relatedContactIds));
469 //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
471 /* Create a new group */
474 'name' => $newGroupName,
475 'title' => $newGroupName,
476 'description' => $newGroupDesc,
479 $group = CRM_Contact_BAO_Group
::create($gParams);
480 $groups[] = $newGroupId = $group->id
;
483 if (is_array($groups)) {
484 $groupAdditions = array();
485 foreach ($groups as $groupId) {
486 $addCount = CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
487 if (!empty($relatedContactIds)) {
488 $addRelCount = CRM_Contact_BAO_GroupContact
::addContactsToGroup($relatedContactIds, $groupId);
490 $totalCount = $addCount[1] +
$addRelCount[1];
491 if ($groupId == $newGroupId) {
492 $name = $newGroupName;
496 $name = $allGroups[$groupId];
499 $groupAdditions[] = array(
500 'url' => CRM_Utils_System
::url('civicrm/group/search',
501 'reset=1&force=1&context=smog&gid=' . $groupId
504 'added' => $totalCount,
505 'notAdded' => $addCount[2] +
$addRelCount[2],
509 $this->set('groupAdditions', $groupAdditions);
514 /* Create a new Tag */
517 'name' => $newTagName,
518 'title' => $newTagName,
519 'description' => $newTagDesc,
523 $addedTag = CRM_Core_BAO_Tag
::add($tagParams, $id);
524 $tag[$addedTag->id
] = 1;
528 if (is_array($tag)) {
530 $tagAdditions = array();
531 foreach ($tag as $tagId => $val) {
532 $addTagCount = CRM_Core_BAO_EntityTag
::addContactsToTag($contactIds, $tagId);
533 if (!empty($relatedContactIds)) {
534 $addRelTagCount = CRM_Core_BAO_EntityTag
::addContactsToTag($relatedContactIds, $tagId);
536 $totalTagCount = $addTagCount[1] +
$addRelTagCount[1];
537 if ($tagId == $addedTag->id
) {
538 $tagName = $newTagName;
542 $tagName = $allTags[$tagId];
545 $tagAdditions[] = array(
546 'url' => CRM_Utils_System
::url('civicrm/contact/search',
547 'reset=1&force=1&context=smog&id=' . $tagId
550 'added' => $totalTagCount,
551 'notAdded' => $addTagCount[2] +
$addRelTagCount[2],
555 $this->set('tagAdditions', $tagAdditions);
558 // add all the necessary variables to the form
559 $parser->set($this, CRM_Import_Parser
::MODE_IMPORT
);
561 // check if there is any error occured
563 $errorStack = CRM_Core_Error
::singleton();
564 $errors = $errorStack->getErrors();
565 $errorMessage = array();
567 if (is_array($errors)) {
568 foreach ($errors as $key => $value) {
569 $errorMessage[] = $value['message'];
572 // there is no fileName since this is a sql import
574 $config = CRM_Core_Config
::singleton();
575 $errorFile = $config->uploadDir
. "sqlImport.error.log";
576 if ($fd = fopen($errorFile, 'w')) {
577 fwrite($fd, implode('\n', $errorMessage));
581 $this->set('errorFile', $errorFile);
583 $urlParams = 'type=' . CRM_Import_Parser
::ERROR
. '&parser=CRM_Contact_Import_Parser';
584 $this->set('downloadErrorRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlparams));
586 $urlParams = 'type=' . CRM_Import_Parser
::CONFLICT
. '&parser=CRM_Contact_Import_Parser';
587 $this->set('downloadConflictRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));
589 $urlParams = 'type=' . CRM_Import_Parser
::NO_MATCH
. '&parser=CRM_Contact_Import_Parser';
590 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System
::url('civicrm/export', $urlParams));