-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathding_kultunaut_import.module
631 lines (549 loc) · 16.9 KB
/
ding_kultunaut_import.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
<?php
/**
* @file
* Handling events import from Kultunaut service.
*/
const EVENT_CATEGORY_FORMAT = 'ding_wysiwyg';
/**
* Implements hook_menu().
*/
function ding_kultunaut_import_menu() {
$items = array();
$items['admin/config/ding_event/event_import'] = array(
'title' => 'Kultunaut events import settings',
'description' => 'Settings page for events import.',
'page callback' => 'drupal_get_form',
'page arguments' => array('ding_kultunaut_import_settings_form'),
'access arguments' => array('administer site configuration'),
'type' => MENU_NORMAL_ITEM,
'file' => 'ding_kultunaut_import.admin.inc',
);
$items['admin/config/ding_event/event_import/cleanup'] = array(
'title' => 'Delete broken imported events',
'page callback' => 'ding_kultunaut_import_cleanup_callback',
'access arguments' => array('administer site configuration'),
'type' => MENU_CALLBACK,
);
$items['admin/config/ding_event/event_import/delete'] = array(
'title' => 'Delete imported events',
'page callback' => 'ding_kultunaut_import_event_delete_callback',
'access arguments' => array('administer site configuration'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Tries to load and read xml feed.
*
* @param string $url
* URL endpoint.
*
* @return bool|\SimpleXMLElement
* XML object or FALSE on failure.
*/
function ding_kultunaut_load_feed($url) {
$response = drupal_http_request($url);
if ((int) $response->code !== 200 || empty($response->data) || !$xml = simplexml_load_string($response->data)) {
watchdog(
'kultunaut',
'Failed parsing xml feed from url: <pre>!url</pre>Http code: <pre>@code</pre>Response: <pre>!response</pre>',
array(
'!url' => l($url, $url, array('external' => TRUE)),
'@code' => $response->code,
'!response' => htmlentities(var_export($response, TRUE)),
)
);
return FALSE;
}
return $xml;
}
/**
* Copies events with repeated event time as separate event entities.
*
* @param \SimpleXMLElement $xml
* Parsed event feed xml object.
*/
function ding_kultunaut_import_expand_events(SimpleXMLElement $xml) {
$additional_events = [];
foreach ($xml->arrlist->arr as $item) {
$time = preg_split('/,|&/', $item->tid, -1, PREG_SPLIT_NO_EMPTY);
// One occurrence means there's only one time and no event copy is needed.
if (count($time) == 1) {
continue;
}
$time = array_map(function ($value) {
return trim($value);
}, $time);
// Original event receives first time occurrence.
$item->tid = reset($time);
// Assign other time values to event copies.
while ($next_time = next($time)) {
$new_event = clone $item;
// Make an unique id for an event clone so it doesn't mess up
// with original event. Event id and it's time are picked as the
// unique values for this particular event.
$new_event->eventid = (string) $item->eventid . '-' . sha1((string) $item->eventid . $next_time);
$new_event->tid = 'kl. ' . $next_time;
$additional_events[] = $new_event;
}
}
// Since SimpleXML is unable to deep clone an element, append new elements
// to initial set by iterating element properties.
foreach ($additional_events as $additional_event) {
$arr_item = $xml->arrlist->addChild('arr');
foreach ((array) $additional_event as $property_name => $property_value) {
$arr_item->addChild($property_name, $property_value);
}
}
}
/**
* Check if "on-site" event wasn't deleted from feed.
*
* @param \SimpleXMLElement $xml
* Parsed event feed xml object.
*
* @throws \Exception
*/
function ding_kultunaut_import_check_diff_db_feed(SimpleXMLElement $xml) {
$feed_ids_array = [];
foreach ($xml->arrlist->arr as $item) {
$feed_ids_array[] = (string) $item->eventid;
}
$feed_ids_db = db_select('imported_events', 'i')
->fields('i', array('eid'))
->execute()
->fetchCol();
$data_diff = drupal_array_diff_assoc_recursive($feed_ids_db, $feed_ids_array);
$cleanup_node_ids = [];
foreach ($data_diff as $event_id) {
$nid = db_select('imported_events', 'i')
->fields('i', ['nid'])
->condition('eid', $event_id, '=')
->execute()
->fetchField();
$node = node_load($nid);
// For various reasons, the node might be gone.
// Cleanup in that case.
if (empty($node)) {
$cleanup_node_ids[] = $nid;
continue;
}
$event_date_data = field_get_items('node', $node, 'field_ding_event_date');
$date = new DateTime();
$event_date_object = $date::createFromFormat('Y-m-d H:i:s', $event_date_data[0]['value']);
$event_date_timestamp = $event_date_object->getTimestamp();
$now = new DateTime();
$current_timestamp = $now->getTimestamp();
if ($event_date_timestamp > $current_timestamp) {
node_delete($nid);
}
}
if (!empty($cleanup_node_ids)) {
db_delete('imported_events')
->condition('nid', $cleanup_node_ids, 'IN')
->execute();
}
}
/**
* Implements hook_cron().
*
* @throws \Exception
*/
function ding_kultunaut_import_cron() {
$xml = ding_kultunaut_load_feed(variable_get('ding_kultunaut_import_url', ''));
if (!$xml) {
return;
}
ding_kultunaut_import_expand_events($xml);
ding_kultunaut_import_check_diff_db_feed($xml);
$importCount = 0;
foreach ($xml->arrlist->arr as $item) {
$event_id = (string) $item->eventid;
$node_exists = db_select('imported_events', 'i')
->fields('i', array('eid'))
->condition('eid', $event_id, '=')
->execute()
->fetchField();
if ($node_exists) {
continue;
}
$node = new stdClass();
$node->uid = 0;
$node->type = 'ding_event';
$node->language = LANGUAGE_NONE;
$node->promote = 1;
$node->title = (string) $item->overskrift;
$image = _ding_kultunaut_import_fetch_image((string) $item->billede);
$image = (array) $image;
$node->field_ding_event_title_image[LANGUAGE_NONE][] = $image;
$node->field_ding_event_list_image[LANGUAGE_NONE][] = $image;
$node->field_ding_event_lead[LANGUAGE_NONE]['0']['value'] = (string) $item->beskrivelse;
if (!empty($item->langbeskriv)) {
$node->field_ding_event_body[LANGUAGE_NONE]['0'] = array(
'value' => (string) $item->langbeskriv,
'format' => EVENT_CATEGORY_FORMAT,
);
}
$node->field_ding_event_category[LANGUAGE_NONE]['0']['tid'] = _ding_kultunaut_import_taxonomy((string) $item->kategori, 'event_category');
$node->field_ding_event_target[LANGUAGE_NONE]['0']['tid'] = _ding_kultunaut_import_taxonomy((string) $item->maalgruppe, 'event_target');
$node->field_ding_event_date[LANGUAGE_NONE][] = _ding_kultunaut_import_event_date($item->startdato, $item->slutdato, $item->tid);
$node->og_group_ref[LANGUAGE_NONE][0]['target_id'] = _ding_kultunaut_import_assign_library((string) $item->sted);
$node->field_ding_event_ticket_link[LANGUAGE_NONE][0]['url'] = (string) $item->billet;
if (!empty((string) $item->pris)) {
$price = '0';
$feed_price = (string) $item->pris;
// Check for numerical value.
$matches = [];
preg_match_all('/Entré|\d+/', $feed_price, $matches);
$matches = reset($matches);
if (count($matches) > 1) {
// Long phrase with price somewhere in it.
$price = $matches[1];
}
elseif ($matches[0] == 'Entré') {
// The price is received as "Entré", then save it as "-1" in db.
$price = '-1';
}
elseif (is_numeric($feed_price)) {
// Given clear price.
$price = $feed_price;
}
$node->field_ding_event_price[LANGUAGE_NONE][0]['value'] = $price;
}
if (module_exists('culture_frontend')) {
$item = [
'category_library' =>
array(
'check' => 1,
'amount' => '3',
),
'similar' =>
array(
'check' => 0,
'amount' => '3',
),
'category' =>
array(
'check' => 1,
'amount' => '3',
),
'day' =>
array(
'check' => 1,
'amount' => '3',
),
'library' =>
array(
'check' => 0,
'amount' => '3',
),
'manually' =>
array(
'check' => 0,
'nids' =>
array(
'fieldset_multifield_nids' =>
array(
'headline' => '',
'multifield_nids' =>
array(
0 =>
array(
'value' => '',
'weight' => '0',
),
),
'culture_frontend_multifield_add_more' => 'Add one more',
),
),
),
];
$node->field_culture_lists_control[LANGUAGE_NONE][0]['wrapper']['lists_options'] = $item;
}
if (module_exists('domain')) {
$domains = variable_get('ding_kultunaut_import_domains', array());
$node->domain_site = FALSE;
$node->domains = $domains;
}
if (module_exists('ding_place2book')) {
$defaults = variable_get('ding_place2book_event_nodes', array());
$node->place2book['maintain_copy'] = !empty($defaults['defaults']['maintain_copy']) ? 1 : 0;
$node->place2book['kultunaut_export'] = !empty($defaults['defaults']['kultunaut_export']) ? 1 : 0;
$node->place2book['passive'] = !empty($defaults['defaults']['passive']) ? 1 : 0;
$node->capacity = isset($defaults['capacity']) ? $defaults['capacity'] : 0;
$node->ticket_type = $defaults['ticket_type'];
}
node_save($node);
db_insert('imported_events')
->fields(array(
'nid' => $node->nid,
'eid' => $event_id,
))
->execute();
$importCount++;
}
watchdog('kultunaut', '@count events were imported.', array('@count' => $importCount));
}
/**
* Callback for preparing library field for imported node.
*
* @param string $item
* String form <sted> field of feed. This string contain venue name where the
* event will take place.
*
* @return int
* Node ID of library node.
*
* @throws \Exception
*/
function _ding_kultunaut_import_assign_library($item) {
// Preparing <sted> string.
$string = drupal_strtolower($item);
// Fetching mapping of libraries.
$mapping = variable_get('ding_kultunaut_library_mapping', array());
// Processing mappings.
foreach ($mapping as $checked) {
$match = strpos($string, drupal_strtolower($checked['searched_string']));
if ($match !== FALSE) {
$library_nid = $checked['library'];
break;
}
}
if (empty($library_nid)) {
// Getting "Other" library nid, if not exist - create this.
$query = db_select('node', 'n')
->fields('n', array('nid'))
->condition('type', 'ding_library', '=')
->condition('title', 'Other', '=')
->execute();
$result = $query->fetchField();
if (!$result) {
$node = new stdClass();
$node->type = 'ding_library';
$node->title = 'Other';
node_save($node);
$other_library = $node->nid;
}
else {
$other_library = $result;
}
$library_nid = $other_library;
}
// Return matched library nid.
return $library_nid;
}
/**
* Handler for event date creation.
*
* @param string $startdate
* Event's start date.
* @param string $enddate
* Event's end date.
* @param string $time
* Event's time.
*
* @return array
* Array of values to be saved in event date field.
*/
function _ding_kultunaut_import_event_date($startdate, $enddate, $time) {
$startdate = DateTime::createFromFormat('Y-m-d', $startdate);
$enddate = DateTime::createFromFormat('Y-m-d', $enddate);
$enddate->setTime('0', '00');
$tostrip = array(
'kl. ' => '',
'kl ' => '',
);
$time = strtr($time, $tostrip);
switch ($startdate) {
case (drupal_strlen($time) == 2):
$startdate->setTime($time, '00');
$enddate->setTime($time, '00');
break;
case (drupal_strlen($time) == 5):
// Dot (.) delimiter.
if (strpos($time, '.')) {
$time = str_replace('.', ':', $time);
$time = explode(':', $time);
$startdate->setTime($time[0], $time[1]);
$enddate->setTime($time[0], $time[1]);
}
// Minus (-) delimiter.
elseif (strpos($time, '-')) {
$period = explode('-', $time);
$start = $period[0];
$end = $period[1];
$startdate->setTime($start, '00');
$enddate->setTime($end, '00');
}
break;
default:
$startdate->setTime('0', '00');
$enddate->setTime('0', '00');
break;
}
// Changing timezone for correct time saving into DB.
$startdate->setTimezone(new DateTimeZone("UTC"));
$enddate->setTimezone(new DateTimeZone("UTC"));
$startdate = $startdate->format('Y-m-d H:i');
$enddate = $enddate->format('Y-m-d H:i');
$dates = array(
'value' => $startdate,
'value2' => $enddate,
);
return $dates;
}
/**
* Handler for category field.
*
* @param string $term_name
* Category term name.
* @param string $vocabulary_name
* Vocabulary name.
*
* @return int
* Term ID.
*/
function _ding_kultunaut_import_taxonomy($term_name, $vocabulary_name) {
$arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary_name);
$vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
if (!empty($arr_terms)) {
$tid = key($arr_terms);
}
else {
$term = new stdClass();
$term->name = $term_name;
$term->vid = $vocabulary->vid;
$term->format = EVENT_CATEGORY_FORMAT;
taxonomy_term_save($term);
$tid = $term->tid;
}
return $tid;
}
/**
* Get and save image.
*
* @param string $url
* URL to image from XML.
*
* @return object
* Image file object.
*/
function _ding_kultunaut_import_fetch_image($url) {
$destination = file_default_scheme() . "://imported_events/" . md5($url) . ".jpg";
// Get the folder for the final location of image.
$directory = dirname($destination);
// Build the destination folder tree if it doesn't already exist.
if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
watchdog(
'kultunaut',
'Failed to create image directory: %directory',
array('%directory' => $directory),
WATCHDOG_ERROR
);
return FALSE;
}
// Download image.
$result = drupal_http_request($url);
// Return false if HTTP request failed.
if ($result->code != 200 || empty($result->data)) {
watchdog(
'kultunaut',
"'Can't download image %image into file",
array('%image' => $url),
WATCHDOG_DEBUG
);
return FALSE;
}
$file = file_save_data($result->data, $destination, FILE_EXISTS_REPLACE);
return $file;
}
/**
* Implements hook_node_delete().
*/
function ding_kultunaut_import_node_delete($node) {
db_delete('imported_events')
->condition('nid', $node->nid)
->execute();
}
/**
* Theme function for fields settings form.
*
* @throws \Exception
*/
function theme_ding_kultunaut_import_mapping_table(&$variables) {
$rows = array();
$form = $variables['form'];
$header = $form['#header'];
foreach (element_children($form) as $id) {
if (is_numeric($id)) {
$row = array();
foreach (element_children($form[$id]) as $child_id) {
if ($child_id == 'values') {
$row[] = drupal_render($form[$id][$child_id]['type']) . drupal_render($form[$id][$child_id]['list']);
}
else {
$row[] = drupal_render($form[$id][$child_id]);
}
}
$rows[] = $row;
}
}
$output = theme('table', array(
'header' => $header,
'rows' => $rows,
));
$output .= drupal_render_children($form);
return $output;
}
/**
* Implements hook_theme().
*/
function ding_kultunaut_import_theme($existing, $type, $theme, $path) {
return array(
'ding_kultunaut_import_mapping_table' => array(
'render element' => 'form',
),
);
}
/**
* Clean imported events which don't have "eventid" in database.
* @return string
*/
function ding_kultunaut_import_cleanup_callback() {
$nids = db_select('imported_events', 'ie')
->fields('ie', array('nid'))
->condition('eid', '', '=')
->execute()
->fetchAllAssoc('nid');
$nids = array_reverse($nids, TRUE);
$i = 0;
foreach ($nids as $nid) {
node_delete($nid->nid);
db_delete('imported_events')
->condition('nid', $nid->nid)
->execute();
$i++;
}
$return = "Removed $i nodes";
return $return;
}
/**
* Delete all imported nodes.
*/
function ding_kultunaut_import_event_delete_callback() {
$nids = db_select('imported_events', 'ie')
->fields('ie', array('nid'))
->execute()
->fetchAllAssoc('nid');
$nids = array_keys($nids);
$i = 0;
foreach ($nids as $nid) {
node_delete($nid);
db_delete('imported_events')
->condition('nid', $nid)
->execute();
$i++;
}
$return = "Deleted $i nodes.";
return $return;
}