Merge pull request #7047 from johanv/CRM-17430-dont_change_domain_version_1st_attempt
[civicrm-core.git] / CRM / Utils / Migrate / Import.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 */
33 class CRM_Utils_Migrate_Import {
34 /**
35 * Class constructor.
36 */
37 public function __construct() {
38 }
39
40 /**
41 * Import custom-data from an XML file.
42 *
43 * @param string $file
44 * Path to an XML file.
45 *
46 * @throws CRM_Core_Exception
47 */
48 public function run($file) {
49 // read xml file
50 $dom = new DomDocument();
51 if (!$dom->load($file)) {
52 throw new CRM_Core_Exception("Failed to parse XML file \"$file\"");
53 }
54 $dom->xinclude();
55 $xml = simplexml_import_dom($dom);
56 return $this->runXmlElement($xml);
57 }
58
59 /**
60 * Import custom-data from an XML element.
61 *
62 * @param SimpleXMLElement $xml
63 */
64 public function runXmlElement($xml) {
65 $idMap = array(
66 'custom_group' => array(),
67 'option_group' => array(),
68 );
69
70 // first create option groups and values if any
71 $this->optionGroups($xml, $idMap);
72 $this->optionValues($xml, $idMap);
73
74 $this->relationshipTypes($xml);
75 $this->contributionTypes($xml);
76
77 // now create custom groups
78 $this->customGroups($xml, $idMap);
79 $this->customFields($xml, $idMap);
80
81 // now create profile groups
82 $this->profileGroups($xml, $idMap);
83 $this->profileFields($xml, $idMap);
84 $this->profileJoins($xml, $idMap);
85
86 // create DB Template String sample data
87 $this->dbTemplateString($xml, $idMap);
88
89 // clean up all caches etc
90 CRM_Core_Config::clearDBCache();
91 }
92
93 /**
94 * @param CRM_Core_DAO $dao
95 * @param $xml
96 * @param bool $save
97 * @param null $keyName
98 *
99 * @return bool
100 */
101 public function copyData(&$dao, &$xml, $save = FALSE, $keyName = NULL) {
102 if ($keyName) {
103 if (isset($xml->$keyName)) {
104 $dao->$keyName = (string ) $xml->$keyName;
105 if ($dao->find(TRUE)) {
106 CRM_Core_Session::setStatus(ts("Found %1, %2, %3",
107 array(
108 1 => $keyName,
109 2 => $dao->$keyName,
110 3 => $dao->__table,
111 )
112 ), '', 'info');
113 return FALSE;
114 }
115 }
116 }
117
118 $fields = &$dao->fields();
119 foreach ($fields as $name => $dontCare) {
120 if (isset($xml->$name)) {
121 $value = (string ) $xml->$name;
122 $value = str_replace(CRM_Utils_Migrate_Export::XML_VALUE_SEPARATOR,
123 CRM_Core_DAO::VALUE_SEPARATOR,
124 $value
125 );
126 $dao->$name = $value;
127 }
128 }
129 if ($save) {
130 $dao->save();
131 }
132 return TRUE;
133 }
134
135 /**
136 * @param $xml
137 * @param $idMap
138 */
139 public function optionGroups(&$xml, &$idMap) {
140 foreach ($xml->OptionGroups as $optionGroupsXML) {
141 foreach ($optionGroupsXML->OptionGroup as $optionGroupXML) {
142 $optionGroup = new CRM_Core_DAO_OptionGroup();
143 $this->copyData($optionGroup, $optionGroupXML, TRUE, 'name');
144 $idMap['option_group'][$optionGroup->name] = $optionGroup->id;
145 }
146 }
147 }
148
149 /**
150 * @param $xml
151 * @param $idMap
152 */
153 public function optionValues(&$xml, &$idMap) {
154 foreach ($xml->OptionValues as $optionValuesXML) {
155 foreach ($optionValuesXML->OptionValue as $optionValueXML) {
156 $optionValue = new CRM_Core_DAO_OptionValue();
157 $optionValue->option_group_id = $idMap['option_group'][(string ) $optionValueXML->option_group_name];
158 $this->copyData($optionValue, $optionValueXML, FALSE, 'label');
159 if (!isset($optionValue->value)) {
160 $sql = "
161 SELECT MAX(ROUND(v.value)) + 1
162 FROM civicrm_option_value v
163 WHERE v.option_group_id = %1
164 ";
165 $params = array(1 => array($optionValue->option_group_id, 'Integer'));
166 $optionValue->value = CRM_Core_DAO::singleValueQuery($sql, $params);
167 }
168 $optionValue->save();
169 }
170 }
171 }
172
173 /**
174 * @param $xml
175 */
176 public function relationshipTypes(&$xml) {
177
178 foreach ($xml->RelationshipTypes as $relationshipTypesXML) {
179 foreach ($relationshipTypesXML->RelationshipType as $relationshipTypeXML) {
180 $relationshipType = new CRM_Contact_DAO_RelationshipType();
181 $this->copyData($relationshipType, $relationshipTypeXML, TRUE, 'name_a_b');
182 }
183 }
184 }
185
186 /**
187 * @param $xml
188 */
189 public function contributionTypes(&$xml) {
190
191 foreach ($xml->ContributionTypes as $contributionTypesXML) {
192 foreach ($contributionTypesXML->ContributionType as $contributionTypeXML) {
193 $contributionType = new CRM_Financial_DAO_FinancialType();
194 $this->copyData($contributionType, $contributionTypeXML, TRUE, 'name');
195 }
196 }
197 }
198
199 /**
200 * @param $xml
201 * @param $idMap
202 */
203 public function customGroups(&$xml, &$idMap) {
204 foreach ($xml->CustomGroups as $customGroupsXML) {
205 foreach ($customGroupsXML->CustomGroup as $customGroupXML) {
206 $customGroup = new CRM_Core_DAO_CustomGroup();
207 if (!$this->copyData($customGroup, $customGroupXML, TRUE, 'name')) {
208 $idMap['custom_group'][$customGroup->name] = $customGroup->id;
209 continue;
210 }
211
212 $saveAgain = FALSE;
213 if (!isset($customGroup->table_name) ||
214 empty($customGroup->table_name)
215 ) {
216 // fix table name
217 $customGroup->table_name = "civicrm_value_" . strtolower(CRM_Utils_String::munge($customGroup->title, '_', 32)) . "_{$customGroup->id}";
218
219 $saveAgain = TRUE;
220 }
221
222 // fix extends stuff if it exists
223 if (isset($customGroupXML->extends_entity_column_value_option_group) &&
224 isset($customGroupXML->extends_entity_column_value)
225 ) {
226 $valueIDs = array();
227 $optionValues = explode(",", $customGroupXML->extends_entity_column_value);
228 $optValues = implode("','", $optionValues);
229 if (trim($customGroup->extends) != 'Participant') {
230 if ($customGroup->extends == 'Relationship') {
231 foreach ($optionValues as $key => $value) {
232 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_BAO_RelationshipType', $value, 'id', 'name_a_b');
233 $valueIDs[] = $relTypeId;
234 }
235 }
236 elseif (in_array($customGroup->extends, array('Individual', 'Organization', 'Household'))) {
237 $valueIDs = $optionValues;
238 }
239 else {
240 $sql = "
241 SELECT v.value
242 FROM civicrm_option_value v
243 INNER JOIN civicrm_option_group g ON g.id = v.option_group_id
244 WHERE g.name = %1
245 AND v.name IN ('$optValues')
246 ";
247 $params = array(
248 1 => array(
249 (string ) $customGroupXML->extends_entity_column_value_option_group,
250 'String',
251 ),
252 );
253 $dao = &CRM_Core_DAO::executeQuery($sql, $params);
254
255 while ($dao->fetch()) {
256 $valueIDs[] = $dao->value;
257 }
258 }
259 if (!empty($valueIDs)) {
260 $customGroup->extends_entity_column_value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
261 $valueIDs
262 ) . CRM_Core_DAO::VALUE_SEPARATOR;
263
264 unset($valueIDs);
265
266 // Note: No need to set extends_entity_column_id here.
267
268 $saveAgain = TRUE;
269 }
270 }
271 else {
272 // when custom group extends 'Participant'
273 $sql = "
274 SELECT v.value
275 FROM civicrm_option_value v
276 INNER JOIN civicrm_option_group g ON g.id = v.option_group_id
277 WHERE g.name = 'custom_data_type'
278 AND v.name = %1
279 ";
280 $params = array(
281 1 => array(
282 (string ) $customGroupXML->extends_entity_column_value_option_group,
283 'String',
284 ),
285 );
286 $valueID = (int ) CRM_Core_DAO::singleValueQuery($sql, $params);
287 if ($valueID) {
288 $customGroup->extends_entity_column_id = $valueID;
289 }
290
291 $optionIDs = array();
292 switch ($valueID) {
293 case 1:
294 // ParticipantRole
295 $condition = "AND v.name IN ( '{$optValues}' )";
296 $optionIDs = CRM_Core_OptionGroup::values('participant_role', FALSE, FALSE, FALSE, $condition, 'name');
297 break;
298
299 case 2:
300 // ParticipantEventName
301 $condition = "( is_template IS NULL OR is_template != 1 ) AND title IN( '{$optValues}' )";
302 $optionIDs = CRM_Event_PseudoConstant::event(NULL, FALSE, $condition);
303 break;
304
305 case 3:
306 // ParticipantEventType
307 $condition = "AND v.name IN ( '{$optValues}' )";
308 $optionIDs = CRM_Core_OptionGroup::values('event_type', FALSE, FALSE, FALSE, $condition, 'name');
309 break;
310 }
311
312 if (is_array($optionIDs) && !empty($optionIDs)) {
313 $customGroup->extends_entity_column_value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
314 array_keys($optionIDs)
315 ) . CRM_Core_DAO::VALUE_SEPARATOR;
316
317 $saveAgain = TRUE;
318 }
319 }
320 }
321
322 if ($saveAgain) {
323 $customGroup->save();
324 }
325
326 CRM_Core_BAO_CustomGroup::createTable($customGroup);
327 $idMap['custom_group'][$customGroup->name] = $customGroup->id;
328 }
329 }
330 }
331
332 /**
333 * @param $xml
334 * @param $idMap
335 */
336 public function customFields(&$xml, &$idMap) {
337 // Re-index by group id so we can build out the custom fields one table
338 // at a time, and then rebuild the table triggers at the end, rather than
339 // rebuilding the table triggers after each field is added (which is
340 // painfully slow).
341 $fields_indexed_by_group_id = array();
342 foreach ($xml->CustomFields as $customFieldsXML) {
343 $total = count($customFieldsXML->CustomField);
344 foreach ($customFieldsXML->CustomField as $customFieldXML) {
345 $id = $idMap['custom_group'][(string ) $customFieldXML->custom_group_name];
346 $fields_indexed_by_group_id[$id][] = $customFieldXML;
347 }
348 }
349 while (list($group_id, $fields) = each($fields_indexed_by_group_id)) {
350 $total = count($fields);
351 $count = 0;
352 while (list(, $customFieldXML) = each($fields)) {
353 $count++;
354 $customField = new CRM_Core_DAO_CustomField();
355 $customField->custom_group_id = $group_id;
356 $skipStore = FALSE;
357 if (!$this->copyData($customField, $customFieldXML, FALSE, 'label')) {
358 $skipStore = TRUE;
359 }
360
361 if (empty($customField->option_group_id) &&
362 isset($customFieldXML->option_group_name)
363 ) {
364 $customField->option_group_id = $idMap['option_group'][(string ) $customFieldXML->option_group_name];
365 }
366 if ($skipStore) {
367 continue;
368 }
369 $customField->save();
370
371 // Only rebuild the table's trigger on the last field added to avoid un-necessary
372 // and slow rebuilds when adding many fields at the same time.
373 $triggerRebuild = FALSE;
374 if ($count == $total) {
375 $triggerRebuild = TRUE;
376 }
377 $indexExist = FALSE;
378 CRM_Core_BAO_CustomField::createField($customField, 'add', $indexExist, $triggerRebuild);
379 }
380 }
381 }
382
383 /**
384 * @param $xml
385 * @param $idMap
386 */
387 public function dbTemplateString(&$xml, &$idMap) {
388 foreach ($xml->Persistent as $persistentXML) {
389 foreach ($persistentXML->Persistent as $persistent) {
390 $persistentObj = new CRM_Core_DAO_Persistent();
391
392 if ($persistent->is_config == 1) {
393 $persistent->data = serialize(explode(',', $persistent->data));
394 }
395 $this->copyData($persistentObj, $persistent, TRUE, 'context');
396 }
397 }
398 }
399
400 /**
401 * @param $xml
402 * @param $idMap
403 */
404 public function profileGroups(&$xml, &$idMap) {
405 foreach ($xml->ProfileGroups as $profileGroupsXML) {
406 foreach ($profileGroupsXML->ProfileGroup as $profileGroupXML) {
407 $profileGroup = new CRM_Core_DAO_UFGroup();
408 $this->copyData($profileGroup, $profileGroupXML, TRUE, 'title');
409 $idMap['profile_group'][$profileGroup->name] = $profileGroup->id;
410 $idMap['profile_group'][$profileGroup->title] = $profileGroup->id;
411 }
412 }
413 }
414
415 /**
416 * @param $xml
417 * @param $idMap
418 *
419 * @throws Exception
420 */
421 public function profileFields(&$xml, &$idMap) {
422 foreach ($xml->ProfileFields as $profileFieldsXML) {
423 foreach ($profileFieldsXML->ProfileField as $profileFieldXML) {
424 $profileField = new CRM_Core_DAO_UFField();
425 $profileField->uf_group_id = $idMap['profile_group'][(string ) $profileFieldXML->profile_group_name];
426 $this->copyData($profileField, $profileFieldXML, FALSE, 'field_name');
427
428 // fix field name
429 if (substr($profileField->field_name, 0, 7) == 'custom.') {
430 list($dontCare, $tableName, $columnName) = explode('.', $profileField->field_name);
431 $sql = "
432 SELECT f.id
433 FROM civicrm_custom_field f
434 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
435 WHERE g.table_name = %1
436 AND f.column_name = %2
437 ";
438 $params = array(
439 1 => array($tableName, 'String'),
440 2 => array($columnName, 'String'),
441 );
442 $cfID = CRM_Core_DAO::singleValueQuery($sql, $params);
443 if (!$cfID) {
444 CRM_Core_Error::fatal(ts("Could not find custom field for %1, %2, %3",
445 array(
446 1 => $profileField->field_name,
447 2 => $tableName,
448 3 => $columnName,
449 )
450 ) . "<br />");
451 }
452 $profileField->field_name = "custom_{$cfID}";
453 }
454 $profileField->save();
455 }
456 }
457 }
458
459 /**
460 * @param $xml
461 * @param $idMap
462 */
463 public function profileJoins(&$xml, &$idMap) {
464 foreach ($xml->ProfileJoins as $profileJoinsXML) {
465 foreach ($profileJoinsXML->ProfileJoin as $profileJoinXML) {
466 $profileJoin = new CRM_Core_DAO_UFJoin();
467 $profileJoin->uf_group_id = $idMap['profile_group'][(string ) $profileJoinXML->profile_group_name];
468 $this->copyData($profileJoin, $profileJoinXML, FALSE, 'module');
469 $profileJoin->save();
470 }
471 }
472 }
473
474 }