Merge pull request #4851 from totten/master-createtest-bao
[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
55 * The array of values belonging to this line.
56 *
57 * @return boolean
58 */
59 public function mapField(&$values) {
60 return CRM_Import_Parser::VALID;
61 }
62
63 /**
64 * Handle the values in preview mode
65 *
66 * @param array $values
67 * The array of values belonging to this line.
68 *
69 * @return boolean the result of this processing
70 */
71 public function preview(&$values) {
72 return $this->summary($values);
73 }
74
75 /**
76 * @param array $values
77 * The array of values belonging to this line.
78 *
79 * @return boolean the result of this processing
80 * It is called from both the preview & the import actions
81 * (non-PHPdoc)
82 * @see CRM_Custom_Import_Parser_BaseClass::summary()
83 */
84 public function summary(&$values) {
85 $erroneousField = NULL;
86 $response = $this->setActiveFieldValues($values, $erroneousField);
87 $errorRequired = FALSE;
88 $missingField = '';
89 $this->_params = &$this->getActiveFieldParams();
90
91 $formatted = $this->_params;
92 $this->_updateWithId = FALSE;
93 $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
94
95 $this->_params = $this->getActiveFieldParams();
96 foreach ($this->_requiredFields as $requiredField) {
97 if (empty($this->_params[$requiredField])) {
98 $errorRequired = TRUE;
99 $missingField .= ' ' . $requiredField;
100 CRM_Contact_Import_Parser_Contact::addToErrorMsg($this->_entity, $requiredField);
101 }
102 }
103
104 if ($errorRequired) {
105 array_unshift($values, ts('Missing required field(s) :') . $missingField);
106 return CRM_Import_Parser::ERROR;
107 }
108
109 $errorMessage = NULL;
110
111 $contactType = $this->_contactType ? $this->_contactType : 'Organization';
112 CRM_Contact_Import_Parser_Contact::isErrorInCustomData($this->_params, $errorMessage, $contactType, NULL);
113
114 // pseudoconstants
115 if ($errorMessage) {
116 $tempMsg = "Invalid value for field(s) : $errorMessage";
117 array_unshift($values, $tempMsg);
118 $errorMessage = NULL;
119 return CRM_Import_Parser::ERROR;
120 }
121 return CRM_Import_Parser::VALID;
122 }
123
124 /**
125 * Handle the values in import mode
126 *
127 * @param int $onDuplicate
128 * The code for what action to take on duplicates.
129 * @param array $values
130 * The array of values belonging to this line.
131 *
132 * @return boolean the result of this processing
133 */
134 public function import($onDuplicate, &$values) {
135 $response = $this->summary($values);
136 if ($response != CRM_Import_Parser::VALID) {
137 $importRecordParams = array(
138 $statusFieldName => 'INVALID',
139 "${statusFieldName}Msg" => "Invalid (Error Code: $response)",
140 );
141 return $response;
142 }
143
144 $this->_updateWithId = FALSE;
145 $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE);
146
147 $params = $this->getActiveFieldParams();
148 $contactType = $this->_contactType ? $this->_contactType : 'Organization';
149 $formatted = array(
150 'contact_type' => $contactType,
151 );
152 $session = CRM_Core_Session::singleton();
153 $dateType = $session->get('dateTypes');
154
155 $formatted['id'] = $this->_params['contact_id'];
156 $setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
157
158 CRM_Contact_Import_Parser_Contact::formatCommonData($this->_params, $formatted, $formatted);
159 foreach ($formatted['custom'] as $key => $val) {
160 $this->_params['custom_' . $key] = $val[-1]['value'];
161 }
162 $this->_params['skipRecentView'] = TRUE;
163 $this->_params['check_permissions'] = TRUE;
164 $this->_params['entity_id'] = $formatted['id'];
165 try{
166 civicrm_api3('custom_value', 'create', $this->_params);
167 }
168 catch(CiviCRM_API3_Exception $e) {
169 $error = $e->getMessage();
170 array_unshift($values, $error);
171 return CRM_Import_Parser::ERROR;
172 }
173 }
174
175 /**
176 * Format Date params
177 *
178 * Although the api will accept any strtotime valid string CiviCRM accepts at least one date format
179 * not supported by strtotime so we should run this through a conversion
180 */
181 public function formatDateParams() {
182 $session = CRM_Core_Session::singleton();
183 $dateType = $session->get('dateTypes');
184 $setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
185
186 foreach ($setDateFields as $key => $value) {
187 CRM_Utils_Date::convertToDefaultDate($this->_params, $dateType, $key);
188 $this->_params[$key] = CRM_Utils_Date::processDate($this->_params[$key]);
189 }
190 }
191
192 /**
193 * Set import entity
194 * @param string $entity
195 */
196 public function setEntity($entity) {
197 $this->_entity = $entity;
198 $this->_multipleCustomData = $entity;
199 }
200
201 /**
202 * The initializer code, called before the processing
203 *
204 * @return void
205 */
206 public function fini() {
207 }
208
209 /**
210 * Return the field ids and names (with groups) for import purpose.
211 *
212 * @param int $id
213 * Custom group ID.
214 *
215 * @return array $importableFields
216 *
217 * @static
218 */
219 public function getGroupFieldsForImport($id) {
220 $importableFields = array();
221 $params = array('custom_group_id' => $id);
222 $allFields = civicrm_api3('custom_field', 'get', $params);
223 $fields = $allFields['values'];
224 foreach ($fields as $id => $values) {
225 $datatype = CRM_Utils_Array::value('data_type', $values);
226 if ($datatype == 'File') {
227 continue;
228 }
229 /* generate the key for the fields array */
230 $key = "custom_$id";
231 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
232 $importableFields[$key] = array(
233 'name' => $key,
234 'title' => CRM_Utils_Array::value('label', $values),
235 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
236 'import' => 1,
237 'custom_field_id' => $id,
238 'options_per_line' => CRM_Utils_Array::value('options_per_line', $values),
239 'data_type' => CRM_Utils_Array::value('data_type', $values),
240 'html_type' => CRM_Utils_Array::value('html_type', $values),
241 'is_search_range' => CRM_Utils_Array::value('is_search_range', $values),
242 );
243 if (CRM_Utils_Array::value('html_type', $values) == 'Select Date') {
244 $importableFields[$key]['date_format'] = CRM_Utils_Array::value('date_format', $values);
245 $importableFields[$key]['time_format'] = CRM_Utils_Array::value('time_format', $values);
246 $this->_dateFields[] = $key;
247 }
248 }
249 return $importableFields;
250 }
251 }