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