bulk comment fix
[civicrm-core.git] / CRM / Contact / Import / Form / Preview.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 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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class previews the uploaded file and returns summary
38 * statistics
39 */
f532671f 40class CRM_Contact_Import_Form_Preview extends CRM_Import_Form_Preview {
6a488035
TO
41
42 /**
43 * Function to set variables up before form is built
44 *
45 * @return void
46 * @access public
47 */
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');
56
57 //assign column names
58 $this->assign('columnNames', $columnNames);
59
60 //get the mapping name displayed if the mappingId is set
61 $mappingId = $this->get('loadMappingId');
62 if ($mappingId) {
63 $mapDAO = new CRM_Core_DAO_Mapping();
64 $mapDAO->id = $mappingId;
65 $mapDAO->find(TRUE);
66 $this->assign('loadedMapping', $mappingId);
67 $this->assign('savedName', $mapDAO->name);
68 }
69
70 $this->assign('rowDisplayCount', 2);
71
72 $groups = CRM_Core_PseudoConstant::group();
73 $this->set('groups', $groups);
74
cd43c5e3 75 $tag = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
6a488035
TO
76 if ($tag) {
77 $this->set('tag', $tag);
78 }
79
80 if ($invalidRowCount) {
a05662ef 81 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
82 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
83 }
84
85 if ($conflictRowCount) {
a05662ef 86 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
87 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
88 }
89
90 if ($mismatchCount) {
a05662ef 91 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
92 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
93 }
94
95 $properties = array(
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',
106 );
107
108 foreach ($properties as $property) {
109 $this->assign($property, $this->get($property));
110 }
111
112 $statusID = $this->get('statusID');
113 if (!$statusID) {
114 $statusID = md5(uniqid(rand(), TRUE));
115 $this->set('statusID', $statusID);
116 }
117 $statusUrl = CRM_Utils_System::url('civicrm/ajax/status', "id={$statusID}", FALSE, NULL, FALSE);
118 $this->assign('statusUrl', $statusUrl);
119
120 $showColNames = TRUE;
121 if ('CRM_Import_DataSource_CSV' == $this->get('dataSource') &&
122 !$this->get('skipColumnHeader')
123 ) {
124 $showColNames = FALSE;
125 }
126 $this->assign('showColNames', $showColNames);
127 }
128
129 /**
130 * Function to actually build the form
131 *
355ba699 132 * @return void
6a488035
TO
133 * @access public
134 */
135 public function buildQuickForm() {
136 $this->addElement('text', 'newGroupName', ts('Name for new group'));
137 $this->addElement('text', 'newGroupDesc', ts('Description of new group'));
138
139 $groups = $this->get('groups');
140
141 if (!empty($groups)) {
142 $this->addElement('select', 'groups', ts('Add imported records to existing group(s)'), $groups, array('multiple' => "multiple", 'size' => 5));
143 }
144
145 //display new tag
146 $this->addElement('text', 'newTagName', ts('Tag'));
147 $this->addElement('text', 'newTagDesc', ts('Description'));
148
149 $tag = $this->get('tag');
150 if (!empty($tag)) {
151 foreach ($tag as $tagID => $tagName) {
152 $this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
153 }
154 }
155
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";
160 }
161
162 $previousURL = CRM_Utils_System::url('civicrm/import/contact', $path, FALSE, NULL, FALSE);
163 $cancelURL = CRM_Utils_System::url('civicrm/import/contact', 'reset=1');
164
165 $buttons = array(
166 array(
167 'type' => 'back',
168 'name' => ts('<< Previous'),
169 'js' => array('onclick' => "location.href='{$previousURL}'; return false;"),
170 ),
171 array(
172 'type' => 'next',
173 'name' => ts('Import Now >>'),
174 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
175 'isDefault' => TRUE,
176 'js' => array('onclick' => "return verify( );"),
177 ),
178 array(
179 'type' => 'cancel',
180 'name' => ts('Cancel'),
181 'js' => array('onclick' => "location.href='{$cancelURL}'; return false;"),
182 ),
183 );
184
185 $this->addButtons($buttons);
186
719a6fec 187 $this->addFormRule(array('CRM_Contact_Import_Form_Preview', 'formRule'), $this);
6a488035
TO
188 }
189
190 /**
191 * global validation rules for the form
192 *
193 * @param array $fields posted values of the form
194 *
195 * @return array list of errors to be posted back to the form
196 * @static
197 * @access public
198 */
199 static function formRule($fields, $files, $self) {
200 $errors = array();
201 $invalidTagName = $invalidGroupName = FALSE;
202
a7488080 203 if (!empty($fields['newTagName'])) {
6a488035
TO
204 if (!CRM_Utils_Rule::objectExists(trim($fields['newTagName']),
205 array('CRM_Core_DAO_Tag')
206 )) {
207 $errors['newTagName'] = ts('Tag \'%1\' already exists.',
208 array(1 => $fields['newTagName'])
209 );
210 $invalidTagName = TRUE;
211 }
212 }
213
a7488080 214 if (!empty($fields['newGroupName'])) {
6a488035
TO
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';
0e6e8724
DL
218 $grpCnt = CRM_Core_DAO::singleValueQuery(
219 $query,
220 array(
221 1 => array($name, 'String'),
6a488035 222 2 => array($title, 'String'),
0e6e8724
DL
223 )
224 );
6a488035
TO
225 if ($grpCnt) {
226 $invalidGroupName = TRUE;
227 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
228 }
229 }
230
231 $self->assign('invalidTagName', $invalidTagName);
232 $self->assign('invalidGroupName', $invalidGroupName);
233
234 return empty($errors) ? TRUE : $errors;
235 }
236
6a488035
TO
237 /**
238 * Process the mapped fields and map it into the uploaded file
239 * preview the file and extract some summary statistics
240 *
241 * @return void
242 * @access public
243 */
244 public function postProcess() {
245
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'),
268 );
269
270 $tableName = $this->get('importTableName');
719a6fec 271 $importJob = new CRM_Contact_Import_ImportJob($tableName);
6a488035
TO
272 $importJob->setJobParams($importJobParams);
273
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);
279 }
280
281 // run the import
282 $importJob->runImport($this);
283
284 // update cache after we done with runImport
285 if (!CRM_Core_Permission::check('view all contacts')) {
286 CRM_ACL_BAO_Cache::updateEntry($userID);
287 }
288
289 // clear all caches
290 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
291
292 // add all the necessary variables to the form
293 $importJob->setFormVariables($this);
294
295 // check if there is any error occured
296 $errorStack = CRM_Core_Error::singleton();
297 $errors = $errorStack->getErrors();
298 $errorMessage = array();
299
300 if (is_array($errors)) {
301 foreach ($errors as $key => $value) {
302 $errorMessage[] = $value['message'];
303 }
304
305 // there is no fileName since this is a sql import
306 // so fudge it
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));
311 }
312 fclose($fd);
313
314 $this->set('errorFile', $errorFile);
315
a05662ef 316 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
317 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
318
a05662ef 319 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
320 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
321
a05662ef 322 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
323 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
324 }
325
326 //hack to clean db
327 //if job complete drop table.
328 $importJob->isComplete(TRUE);
329 }
330
331 /**
332 * Process the mapped fields and map it into the uploaded file
333 * preview the file and extract some summary statistics
334 *
335 * @return void
336 * @access public
337 */
338 public function postProcessOld() {
339
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');
352
353 $mapper = $this->controller->exportValue('MapField', 'mapper');
354
355 $mapperKeys = array();
356 $mapperLocTypes = array();
357 $mapperPhoneTypes = array();
358 $mapperRelated = array();
359 $mapperRelatedContactType = array();
360 $mapperRelatedContactDetails = array();
361 $mapperRelatedContactLocType = array();
362 $mapperRelatedContactPhoneType = array();
363
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];
368 }
369 else {
370 $mapperLocTypes[$key] = NULL;
371 }
372
373 if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') {
374 $mapperPhoneTypes[$key] = $mapper[$key][2];
375 }
376 else {
377 $mapperPhoneTypes[$key] = NULL;
378 }
379
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);
0e6e8724
DL
385 $fieldName = "contact_type_$second";
386 $mapperRelatedContactType[$key] = $relationType->$fieldName;
6a488035
TO
387 $mapperRelated[$key] = $mapper[$key][0];
388 $mapperRelatedContactDetails[$key] = $mapper[$key][1];
389 $mapperRelatedContactLocType[$key] = $mapper[$key][2];
390 $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
391 }
392 else {
393 $mapperRelated[$key] = NULL;
394 $mapperRelatedContactType[$key] = NULL;
395 $mapperRelatedContactDetails[$key] = NULL;
396 $mapperRelatedContactLocType[$key] = NULL;
397 $mapperRelatedContactPhoneType[$key] = NULL;
398 }
399 }
400
719a6fec 401 $parser = new CRM_Contact_Import_Parser_Contact($mapperKeys, $mapperLocTypes,
6a488035
TO
402 $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType,
403 $mapperRelatedContactDetails, $mapperRelatedContactLocType,
404 $mapperRelatedContactPhoneType
405 );
406
407 $mapFields = $this->get('fields');
408
b2b0530a 409 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
b4f964d9 410 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
6a488035
TO
411
412 foreach ($mapper as $key => $value) {
413 $header = array();
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);
419
420 $header[] = $relationType->name_a_b;
421 $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
422
423 if (isset($mapper[$key][2])) {
424 $header[] = $locationTypes[$mapper[$key][2]];
425 }
426 if (isset($mapper[$key][3])) {
427 $header[] = $phoneTypes[$mapper[$key][3]];
428 }
429 }
430 else {
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]];
435 }
436 if (isset($mapper[$key][2])) {
437 $header[] = $phoneTypes[$mapper[$key][2]];
438 }
439 }
440 }
441 $mapperFields[] = implode(' - ', $header);
442 }
443
444 $tableName = $this->get('importTableName');
445 //print "Running parser on table: $tableName<br/>";
446 $parser->run($tableName, $mapperFields,
a05662ef 447 CRM_Import_Parser::MODE_IMPORT,
6a488035
TO
448 $this->get('contactType'),
449 $this->get('primaryKeyName'),
450 $this->get('statusFieldName'),
451 $onDuplicate,
452 $this->get('statusID'),
453 $this->get('totalRowCount'),
454 $doGeocodeAddress,
719a6fec 455 CRM_Contact_Import_Parser::DEFAULT_TIMEOUT,
6a488035
TO
456 $this->get('contactSubType'),
457 $this->get('dedupe')
458 );
459
460 // add the new contacts to selected groups
461 $contactIds = &$parser->getImportedContacts();
462
463 // add the new related contacts to selected groups
464 $relatedContactIds = &$parser->getRelatedImportedContacts();
465
466 $this->set('relatedCount', count($relatedContactIds));
467 $newGroupId = NULL;
468
469 //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
470 if ($newGroupName) {
471 /* Create a new group */
472
473 $gParams = array(
474 'name' => $newGroupName,
475 'title' => $newGroupName,
476 'description' => $newGroupDesc,
477 'is_active' => TRUE,
478 );
479 $group = CRM_Contact_BAO_Group::create($gParams);
480 $groups[] = $newGroupId = $group->id;
481 }
482
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);
489 }
490 $totalCount = $addCount[1] + $addRelCount[1];
491 if ($groupId == $newGroupId) {
492 $name = $newGroupName;
493 $new = TRUE;
494 }
495 else {
496 $name = $allGroups[$groupId];
497 $new = FALSE;
498 }
499 $groupAdditions[] = array(
500 'url' => CRM_Utils_System::url('civicrm/group/search',
501 'reset=1&force=1&context=smog&gid=' . $groupId
502 ),
503 'name' => $name,
504 'added' => $totalCount,
505 'notAdded' => $addCount[2] + $addRelCount[2],
506 'new' => $new,
507 );
508 }
509 $this->set('groupAdditions', $groupAdditions);
510 }
511
512 $newTagId = NULL;
513 if ($newTagName) {
514 /* Create a new Tag */
515
516 $tagParams = array(
517 'name' => $newTagName,
518 'title' => $newTagName,
519 'description' => $newTagDesc,
520 'is_active' => TRUE,
521 );
522 $id = array();
523 $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id);
524 $tag[$addedTag->id] = 1;
525 }
526 //add Tag to Import
527
528 if (is_array($tag)) {
529
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);
535 }
536 $totalTagCount = $addTagCount[1] + $addRelTagCount[1];
537 if ($tagId == $addedTag->id) {
538 $tagName = $newTagName;
539 $new = TRUE;
540 }
541 else {
542 $tagName = $allTags[$tagId];
543 $new = FALSE;
544 }
545 $tagAdditions[] = array(
546 'url' => CRM_Utils_System::url('civicrm/contact/search',
547 'reset=1&force=1&context=smog&id=' . $tagId
548 ),
549 'name' => $tagName,
550 'added' => $totalTagCount,
551 'notAdded' => $addTagCount[2] + $addRelTagCount[2],
552 'new' => $new,
553 );
554 }
555 $this->set('tagAdditions', $tagAdditions);
556 }
557
558 // add all the necessary variables to the form
a05662ef 559 $parser->set($this, CRM_Import_Parser::MODE_IMPORT);
6a488035
TO
560
561 // check if there is any error occured
562
563 $errorStack = CRM_Core_Error::singleton();
564 $errors = $errorStack->getErrors();
565 $errorMessage = array();
566
567 if (is_array($errors)) {
568 foreach ($errors as $key => $value) {
569 $errorMessage[] = $value['message'];
570 }
571
572 // there is no fileName since this is a sql import
573 // so fudge it
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));
578 }
579 fclose($fd);
580
581 $this->set('errorFile', $errorFile);
582
a05662ef 583 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
584 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlparams));
585
a05662ef 586 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
587 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
588
a05662ef 589 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser';
6a488035
TO
590 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
591 }
592 }
593}
594