Merge pull request #4818 from pratikshad/CRM-15770
[civicrm-core.git] / CRM / Custom / Import / Parser / Api.php
1 <?php
2
3 /**
4 * Class CRM_Custom_Import_Parser_Api
5 */
6 class CRM_Custom_Import_Parser_Api extends CRM_Custom_Import_Parser {
7
8 protected $_entity = '';
9 protected $_fields = array();
10 protected $_requiredFields = array();
11 protected $_dateFields = array();
12 protected $_multipleCustomData = '';
13
14 /**
15 * Params for the current entity being prepared for the api
16 * @var array
17 */
18 protected $_params = array();
19 /**
20 * Class constructor
21 */
22 public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
23 parent::__construct();
24 $this->_mapperKeys = &$mapperKeys;
25 }
26 public function setFields() {
27 $customGroupID = $this->_multipleCustomData;
28 $importableFields = $this->getGroupFieldsForImport($customGroupID, $this);
29 $this->_fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -')), 'contact_id' => array('title' => ts('Contact ID'))), $importableFields);
30 }
31
32 /**
33 * The initializer code, called before the processing
34 *
35 * @return void
36 */
37 public function init() {
38 $this->setFields();
39 $fields = $this->_fields;
40 $hasLocationType = FALSE;
41
42 foreach ($fields as $name => $field) {
43 $field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
44 $field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
45 $field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
46 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern'], $hasLocationType);
47 }
48 $this->setActiveFields($this->_mapperKeys);
49 }
50
51 /**
52 * Handle the values in mapField mode
53 *
54 * @param array $values the array of values belonging to this line
55 *
56 * @return boolean
57 */
58 public function mapField(&$values) {
59 return CRM_Import_Parser::VALID;
60 }
61
62 /**
63 * Handle the values in preview mode
64 *
65 * @param array $values the array of values belonging to this line
66 *
67 * @return boolean the result of this processing
68 */
69 public function preview(&$values) {
70 return $this->summary($values);
71 }
72
73 /**
74 * @param array $values the array of values belonging to this line
75 *
76 * @return boolean the result of this processing
77 * It is called from both the preview & the import actions
78 * (non-PHPdoc)
79 * @see CRM_Custom_Import_Parser_BaseClass::summary()
80 */
81 public function summary(&$values) {
82 $erroneousField = NULL;
83 $response = $this->setActiveFieldValues($values, $erroneousField);
84 $errorRequired = FALSE;
85 $missingField = '';
86 $this->_params = &$this->getActiveFieldParams();
87
88 $formatted = $this->_params;
89 $this->_updateWithId = FALSE;
90 $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
91
92 $this->_params = $this->getActiveFieldParams();
93 foreach ($this->_requiredFields as $requiredField) {
94 if (empty($this->_params[$requiredField])) {
95 $errorRequired = TRUE;
96 $missingField .= ' ' . $requiredField;
97 CRM_Contact_Import_Parser_Contact::addToErrorMsg($this->_entity, $requiredField);
98 }
99 }
100
101 if ($errorRequired) {
102 array_unshift($values, ts('Missing required field(s) :') . $missingField);
103 return CRM_Import_Parser::ERROR;
104 }
105
106 $errorMessage = NULL;
107
108 $contactType = $this->_contactType ? $this->_contactType : 'Organization';
109 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($this->_params , $errorMessage, $contactType, NULL);
110
111 // pseudoconstants
112 if ($errorMessage) {
113 $tempMsg = "Invalid value for field(s) : $errorMessage";
114 array_unshift($values, $tempMsg);
115 $errorMessage = NULL;
116 return CRM_Import_Parser::ERROR;
117 }
118 return CRM_Import_Parser::VALID;
119 }
120
121 /**
122 * Handle the values in import mode
123 *
124 * @param int $onDuplicate the code for what action to take on duplicates
125 * @param array $values the array of values belonging to this line
126 *
127 * @return boolean the result of this processing
128 */
129 public function import($onDuplicate, &$values) {
130 $response = $this->summary($values);
131 if ($response != CRM_Import_Parser::VALID) {
132 $importRecordParams = array(
133 $statusFieldName => 'INVALID',
134 "${statusFieldName}Msg" => "Invalid (Error Code: $response)",
135 );
136 return $response;
137 }
138
139 $this->_updateWithId = FALSE;
140 $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
141
142 $params = $this->getActiveFieldParams();
143 $contactType = $this->_contactType ? $this->_contactType : 'Organization';
144 $formatted = array(
145 'contact_type' => $contactType,
146 );
147 $session = CRM_Core_Session::singleton();
148 $dateType = $session->get('dateTypes');
149
150 $formatted['id'] = $this->_params['contact_id'];
151 $setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
152
153 CRM_Contact_Import_Parser_Contact::formatCommonData($this->_params, $formatted, $formatted) ;
154 foreach($formatted['custom'] as $key => $val) {
155 $this->_params['custom_'.$key] = $val[-1]['value'];
156 }
157 $this->_params['skipRecentView'] = TRUE;
158 $this->_params['check_permissions'] = TRUE;
159 $this->_params['entity_id'] = $formatted['id'];
160 try{
161 civicrm_api3('custom_value', 'create', $this->_params);
162 }
163 catch(CiviCRM_API3_Exception $e) {
164 $error = $e->getMessage();
165 array_unshift($values, $error);
166 return CRM_Import_Parser::ERROR;
167 }
168 }
169
170 /**
171 * Format Date params
172 *
173 * Although the api will accept any strtotime valid string CiviCRM accepts at least one date format
174 * not supported by strtotime so we should run this through a conversion
175 */
176 public function formatDateParams() {
177 $session = CRM_Core_Session::singleton();
178 $dateType = $session->get('dateTypes');
179 $setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
180
181 foreach ($setDateFields as $key => $value) {
182 CRM_Utils_Date::convertToDefaultDate($this->_params, $dateType, $key);
183 $this->_params[$key] = CRM_Utils_Date::processDate($this->_params[$key]);
184 }
185 }
186
187 /**
188 * Set import entity
189 * @param string $entity
190 */
191 public function setEntity($entity) {
192 $this->_entity = $entity;
193 $this->_multipleCustomData = $entity;
194 }
195
196 /**
197 * The initializer code, called before the processing
198 *
199 * @return void
200 */
201 public function fini() {}
202
203 /**
204 * Return the field ids and names (with groups) for import purpose.
205 *
206 * @param int $id Custom group ID
207 *
208 * @return array $importableFields
209 *
210 * @static
211 */
212 public function getGroupFieldsForImport( $id ) {
213 $importableFields = array();
214 $params = array('custom_group_id' => $id);
215 $allFields = civicrm_api3('custom_field', 'get', $params);
216 $fields = $allFields['values'];
217 foreach ($fields as $id => $values) {
218 $datatype = CRM_Utils_Array::value('data_type', $values);
219 if ( $datatype == 'File' ) {
220 continue;
221 }
222 /* generate the key for the fields array */
223 $key = "custom_$id";
224 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
225 $importableFields[$key] = array(
226 'name' => $key,
227 'title' => CRM_Utils_Array::value('label', $values),
228 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
229 'import' => 1,
230 'custom_field_id' => $id,
231 'options_per_line' => CRM_Utils_Array::value('options_per_line', $values),
232 'data_type' => CRM_Utils_Array::value('data_type', $values),
233 'html_type' => CRM_Utils_Array::value('html_type', $values),
234 'is_search_range' => CRM_Utils_Array::value('is_search_range', $values),
235 );
236 if (CRM_Utils_Array::value('html_type', $values) == 'Select Date') {
237 $importableFields[$key]['date_format'] = CRM_Utils_Array::value('date_format', $values);
238 $importableFields[$key]['time_format'] = CRM_Utils_Array::value('time_format', $values);
239 $this->_dateFields[] = $key;
240 }
241 }
242 return $importableFields;
243 }
244 }