Import from SVN (r45945, r596)
[civicrm-core.git] / CRM / Import / Form / Preview.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36/**
37 * This class previews the uploaded file and returns summary
38 * statistics
39 */
40class CRM_Import_Form_Preview extends CRM_Core_Form {
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
75 $tag = CRM_Core_PseudoConstant::tag();
76 if ($tag) {
77 $this->set('tag', $tag);
78 }
79
80 if ($invalidRowCount) {
81 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Import_Parser';
82 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
83 }
84
85 if ($conflictRowCount) {
86 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Import_Parser';
87 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
88 }
89
90 if ($mismatchCount) {
91 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Import_Parser';
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 *
132 * @return None
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
187 $this->addFormRule(array('CRM_Import_Form_Preview', 'formRule'), $this);
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
203 if (CRM_Utils_Array::value('newTagName', $fields)) {
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
214 if (CRM_Utils_Array::value('newGroupName', $fields)) {
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($query, array(1 => array($name, 'String'),
219 2 => array($title, 'String'),
220 ));
221 if ($grpCnt) {
222 $invalidGroupName = TRUE;
223 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
224 }
225 }
226
227 $self->assign('invalidTagName', $invalidTagName);
228 $self->assign('invalidGroupName', $invalidGroupName);
229
230 return empty($errors) ? TRUE : $errors;
231 }
232
233 /**
234 * Return a descriptive name for the page, used in wizard header
235 *
236 * @return string
237 * @access public
238 */
239 public function getTitle() {
240 return ts('Preview');
241 }
242
243 /**
244 * Process the mapped fields and map it into the uploaded file
245 * preview the file and extract some summary statistics
246 *
247 * @return void
248 * @access public
249 */
250 public function postProcess() {
251
252 $importJobParams = array(
253 'doGeocodeAddress' => $this->controller->exportValue('DataSource', 'doGeocodeAddress'),
254 'invalidRowCount' => $this->get('invalidRowCount'),
255 'conflictRowCount' => $this->get('conflictRowCount'),
256 'onDuplicate' => $this->get('onDuplicate'),
257 'dedupe' => $this->get('dedupe'),
258 'newGroupName' => $this->controller->exportValue($this->_name, 'newGroupName'),
259 'newGroupDesc' => $this->controller->exportValue($this->_name, 'newGroupDesc'),
260 'groups' => $this->controller->exportValue($this->_name, 'groups'),
261 'allGroups' => $this->get('groups'),
262 'newTagName' => $this->controller->exportValue($this->_name, 'newTagName'),
263 'newTagDesc' => $this->controller->exportValue($this->_name, 'newTagDesc'),
264 'tag' => $this->controller->exportValue($this->_name, 'tag'),
265 'allTags' => $this->get('tag'),
266 'mapper' => $this->controller->exportValue('MapField', 'mapper'),
267 'mapFields' => $this->get('fields'),
268 'contactType' => $this->get('contactType'),
269 'contactSubType' => $this->get('contactSubType'),
270 'primaryKeyName' => $this->get('primaryKeyName'),
271 'statusFieldName' => $this->get('statusFieldName'),
272 'statusID' => $this->get('statusID'),
273 'totalRowCount' => $this->get('totalRowCount'),
274 );
275
276 $tableName = $this->get('importTableName');
277 $importJob = new CRM_Import_ImportJob($tableName);
278 $importJob->setJobParams($importJobParams);
279
280 // If ACL applies to the current user, update cache before running the import.
281 if (!CRM_Core_Permission::check('view all contacts')) {
282 $session = CRM_Core_Session::singleton();
283 $userID = $session->get('userID');
284 CRM_ACL_BAO_Cache::updateEntry($userID);
285 }
286
287 // run the import
288 $importJob->runImport($this);
289
290 // update cache after we done with runImport
291 if (!CRM_Core_Permission::check('view all contacts')) {
292 CRM_ACL_BAO_Cache::updateEntry($userID);
293 }
294
295 // clear all caches
296 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
297
298 // add all the necessary variables to the form
299 $importJob->setFormVariables($this);
300
301 // check if there is any error occured
302 $errorStack = CRM_Core_Error::singleton();
303 $errors = $errorStack->getErrors();
304 $errorMessage = array();
305
306 if (is_array($errors)) {
307 foreach ($errors as $key => $value) {
308 $errorMessage[] = $value['message'];
309 }
310
311 // there is no fileName since this is a sql import
312 // so fudge it
313 $config = CRM_Core_Config::singleton();
314 $errorFile = $config->uploadDir . "sqlImport.error.log";
315 if ($fd = fopen($errorFile, 'w')) {
316 fwrite($fd, implode('\n', $errorMessage));
317 }
318 fclose($fd);
319
320 $this->set('errorFile', $errorFile);
321
322 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Import_Parser';
323 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
324
325 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Import_Parser';
326 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
327
328 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Import_Parser';
329 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
330 }
331
332 //hack to clean db
333 //if job complete drop table.
334 $importJob->isComplete(TRUE);
335 }
336
337 /**
338 * Process the mapped fields and map it into the uploaded file
339 * preview the file and extract some summary statistics
340 *
341 * @return void
342 * @access public
343 */
344 public function postProcessOld() {
345
346 $doGeocodeAddress = $this->controller->exportValue('DataSource', 'doGeocodeAddress');
347 $invalidRowCount = $this->get('invalidRowCount');
348 $conflictRowCount = $this->get('conflictRowCount');
349 $onDuplicate = $this->get('onDuplicate');
350 $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName');
351 $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc');
352 $groups = $this->controller->exportValue($this->_name, 'groups');
353 $allGroups = $this->get('groups');
354 $newTagName = $this->controller->exportValue($this->_name, 'newTagName');
355 $newTagDesc = $this->controller->exportValue($this->_name, 'newTagDesc');
356 $tag = $this->controller->exportValue($this->_name, 'tag');
357 $allTags = $this->get('tag');
358
359 $mapper = $this->controller->exportValue('MapField', 'mapper');
360
361 $mapperKeys = array();
362 $mapperLocTypes = array();
363 $mapperPhoneTypes = array();
364 $mapperRelated = array();
365 $mapperRelatedContactType = array();
366 $mapperRelatedContactDetails = array();
367 $mapperRelatedContactLocType = array();
368 $mapperRelatedContactPhoneType = array();
369
370 foreach ($mapper as $key => $value) {
371 $mapperKeys[$key] = $mapper[$key][0];
372 if (is_numeric($mapper[$key][1])) {
373 $mapperLocTypes[$key] = $mapper[$key][1];
374 }
375 else {
376 $mapperLocTypes[$key] = NULL;
377 }
378
379 if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') {
380 $mapperPhoneTypes[$key] = $mapper[$key][2];
381 }
382 else {
383 $mapperPhoneTypes[$key] = NULL;
384 }
385
386 list($id, $first, $second) = explode('_', $mapper[$key][0]);
387 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
388 $relationType = new CRM_Contact_DAO_RelationshipType();
389 $relationType->id = $id;
390 $relationType->find(TRUE);
391 eval('$mapperRelatedContactType[$key] = $relationType->contact_type_' . $second . ';');
392 $mapperRelated[$key] = $mapper[$key][0];
393 $mapperRelatedContactDetails[$key] = $mapper[$key][1];
394 $mapperRelatedContactLocType[$key] = $mapper[$key][2];
395 $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
396 }
397 else {
398 $mapperRelated[$key] = NULL;
399 $mapperRelatedContactType[$key] = NULL;
400 $mapperRelatedContactDetails[$key] = NULL;
401 $mapperRelatedContactLocType[$key] = NULL;
402 $mapperRelatedContactPhoneType[$key] = NULL;
403 }
404 }
405
406 $parser = new CRM_Import_Parser_Contact($mapperKeys, $mapperLocTypes,
407 $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType,
408 $mapperRelatedContactDetails, $mapperRelatedContactLocType,
409 $mapperRelatedContactPhoneType
410 );
411
412 $mapFields = $this->get('fields');
413
414 $locationTypes = CRM_Core_PseudoConstant::locationType();
415 $phoneTypes = CRM_Core_PseudoConstant::phoneType();
416
417 foreach ($mapper as $key => $value) {
418 $header = array();
419 list($id, $first, $second) = explode('_', $mapper[$key][0]);
420 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
421 $relationType = new CRM_Contact_DAO_RelationshipType();
422 $relationType->id = $id;
423 $relationType->find(TRUE);
424
425 $header[] = $relationType->name_a_b;
426 $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
427
428 if (isset($mapper[$key][2])) {
429 $header[] = $locationTypes[$mapper[$key][2]];
430 }
431 if (isset($mapper[$key][3])) {
432 $header[] = $phoneTypes[$mapper[$key][3]];
433 }
434 }
435 else {
436 if (isset($mapFields[$mapper[$key][0]])) {
437 $header[] = $mapFields[$mapper[$key][0]];
438 if (isset($mapper[$key][1])) {
439 $header[] = $locationTypes[$mapper[$key][1]];
440 }
441 if (isset($mapper[$key][2])) {
442 $header[] = $phoneTypes[$mapper[$key][2]];
443 }
444 }
445 }
446 $mapperFields[] = implode(' - ', $header);
447 }
448
449 $tableName = $this->get('importTableName');
450 //print "Running parser on table: $tableName<br/>";
451 $parser->run($tableName, $mapperFields,
452 CRM_Import_Parser::MODE_IMPORT,
453 $this->get('contactType'),
454 $this->get('primaryKeyName'),
455 $this->get('statusFieldName'),
456 $onDuplicate,
457 $this->get('statusID'),
458 $this->get('totalRowCount'),
459 $doGeocodeAddress,
460 CRM_Import_Parser::DEFAULT_TIMEOUT,
461 $this->get('contactSubType'),
462 $this->get('dedupe')
463 );
464
465 // add the new contacts to selected groups
466 $contactIds = &$parser->getImportedContacts();
467
468 // add the new related contacts to selected groups
469 $relatedContactIds = &$parser->getRelatedImportedContacts();
470
471 $this->set('relatedCount', count($relatedContactIds));
472 $newGroupId = NULL;
473
474 //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
475 if ($newGroupName) {
476 /* Create a new group */
477
478 $gParams = array(
479 'name' => $newGroupName,
480 'title' => $newGroupName,
481 'description' => $newGroupDesc,
482 'is_active' => TRUE,
483 );
484 $group = CRM_Contact_BAO_Group::create($gParams);
485 $groups[] = $newGroupId = $group->id;
486 }
487
488 if (is_array($groups)) {
489 $groupAdditions = array();
490 foreach ($groups as $groupId) {
491 $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
492 if (!empty($relatedContactIds)) {
493 $addRelCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId);
494 }
495 $totalCount = $addCount[1] + $addRelCount[1];
496 if ($groupId == $newGroupId) {
497 $name = $newGroupName;
498 $new = TRUE;
499 }
500 else {
501 $name = $allGroups[$groupId];
502 $new = FALSE;
503 }
504 $groupAdditions[] = array(
505 'url' => CRM_Utils_System::url('civicrm/group/search',
506 'reset=1&force=1&context=smog&gid=' . $groupId
507 ),
508 'name' => $name,
509 'added' => $totalCount,
510 'notAdded' => $addCount[2] + $addRelCount[2],
511 'new' => $new,
512 );
513 }
514 $this->set('groupAdditions', $groupAdditions);
515 }
516
517 $newTagId = NULL;
518 if ($newTagName) {
519 /* Create a new Tag */
520
521 $tagParams = array(
522 'name' => $newTagName,
523 'title' => $newTagName,
524 'description' => $newTagDesc,
525 'is_active' => TRUE,
526 );
527 $id = array();
528 $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id);
529 $tag[$addedTag->id] = 1;
530 }
531 //add Tag to Import
532
533 if (is_array($tag)) {
534
535 $tagAdditions = array();
536 foreach ($tag as $tagId => $val) {
537 $addTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId);
538 if (!empty($relatedContactIds)) {
539 $addRelTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($relatedContactIds, $tagId);
540 }
541 $totalTagCount = $addTagCount[1] + $addRelTagCount[1];
542 if ($tagId == $addedTag->id) {
543 $tagName = $newTagName;
544 $new = TRUE;
545 }
546 else {
547 $tagName = $allTags[$tagId];
548 $new = FALSE;
549 }
550 $tagAdditions[] = array(
551 'url' => CRM_Utils_System::url('civicrm/contact/search',
552 'reset=1&force=1&context=smog&id=' . $tagId
553 ),
554 'name' => $tagName,
555 'added' => $totalTagCount,
556 'notAdded' => $addTagCount[2] + $addRelTagCount[2],
557 'new' => $new,
558 );
559 }
560 $this->set('tagAdditions', $tagAdditions);
561 }
562
563 // add all the necessary variables to the form
564 $parser->set($this, CRM_Import_Parser::MODE_IMPORT);
565
566 // check if there is any error occured
567
568 $errorStack = CRM_Core_Error::singleton();
569 $errors = $errorStack->getErrors();
570 $errorMessage = array();
571
572 if (is_array($errors)) {
573 foreach ($errors as $key => $value) {
574 $errorMessage[] = $value['message'];
575 }
576
577 // there is no fileName since this is a sql import
578 // so fudge it
579 $config = CRM_Core_Config::singleton();
580 $errorFile = $config->uploadDir . "sqlImport.error.log";
581 if ($fd = fopen($errorFile, 'w')) {
582 fwrite($fd, implode('\n', $errorMessage));
583 }
584 fclose($fd);
585
586 $this->set('errorFile', $errorFile);
587
588 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Import_Parser';
589 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlparams));
590
591 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Import_Parser';
592 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
593
594 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Import_Parser';
595 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
596 }
597 }
598}
599