-
Notifications
You must be signed in to change notification settings - Fork 6
/
os2web_borger_dk_articles.module
1765 lines (1588 loc) · 74 KB
/
os2web_borger_dk_articles.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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Drupal needs this blank file.
*/
include_once('os2web_borger_dk_articles.features.inc');
/**
* Text formats
*/
define('BORGERDK_TEXT_FORMAT_PLAIN', variable_get('os2web_borger_dk_articles_text_format_plain', 'plain_text'));
define('BORGERDK_TEXT_FORMAT_HTML', variable_get('os2web_borger_dk_articles_text_format_html', 'full_html'));
/**
* Implements hook_menu().
*/
function os2web_borger_dk_articles_menu() {
$items = array();
$items['admin/config/borgerdk'] = array(
'title' => 'Os2web borger.dk article settings',
'description' => 'General settings for Borger.dk articles, fx, modify fields display, editable and syncronization time',
'position' => 'right',
'weight' => -10,
'page callback' => 'system_admin_menu_block_page',
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),
'access arguments' => array('administer os2web borgerdk article settings'),
);
$items['admin/config/borgerdk/settings'] = array(
'title' => 'OS2web Borger.dk Settings',
'description' => 'General settings for the OS2Web borger.dk articles',
'page callback' => 'drupal_get_form',
'page arguments' => array('os2web_borger_dk_articles_settings_form'),
'access arguments' => array('administer os2web borgerdk article settings'),
'file' => 'os2web_borger_dk_articles.admin.inc',
);
$items['import/borger-dk-article/autocomplete'] = array(
'page callback' => '_os2web_borger_dk_articles_autocomplete_callback',
'access arguments' => array('create borger_dk_article content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_permission().
*/
function os2web_borger_dk_articles_permission() {
return array(
'administer os2web borgerdk article settings' => array(
'title' => t('Administer OS2Web Borger.dk article settings'),
'description' => t('Administer settings for the OS2Web Borger.dk article import module.'),
),
);
}
/**
* Implements hook_action_info().
*/
function os2web_borger_dk_articles_action_info() {
return array(
'os2web_borger_dk_articles_update_action' => array(
'type' => 'node',
'label' => t('Update article from borger.dk'),
'configurable' => FALSE,
),
);
}
/**
* _os2web_borger_dk_articles_autocomplete_callback().
*/
function _os2web_borger_dk_articles_autocomplete_callback($string = '') {
$matches = array();
if ($string) {
$query = db_select('os2web_borger_dk_titles', 'o')
->fields('o', array('ArticleID', 'ArticleStatus', 'ArticleTitle'))
->condition('o.ArticleStatus', 0, '>=')
->condition('o.ArticleTitle', db_like($string) . '%', 'LIKE')
->range(0, 10);
$result = $query->execute();
// Add matches to $matches.
foreach ($result as $row) {
if ($row->ArticleStatus > 0) {
$row_name = $row->ArticleTitle . ' [*](ID:' . $row->ArticleID . ')';
}
else {
$row_name = $row->ArticleTitle . ' (ID:' . $row->ArticleID . ')';
}
$matches[$row_name] = check_plain($row_name);
}
}
// return for JS
drupal_json_output($matches);
}
/**
* Implements hook_form_alter().
*/
function os2web_borger_dk_articles_form_alter(&$form, &$form_state, $form_id) {
static $os2web_borger_dk_articles_falter_form;
if (isset($form['type']) && isset($form['#node'])) {
if ($form_id == 'borger_dk_article_node_form') {
if (isset($os2web_borger_dk_articles_falter_form) && !empty($os2web_borger_dk_articles_falter_form)) {
// If the static form-cache has already been build then
// we simply return the form-cache value instead of
// building the whole form twice per request
$form = $os2web_borger_dk_articles_falter_form;
}
else {
$node = $form_state['node'];
$titles_autocomplete = variable_get('borger_dk_article_titles_sync', FALSE);
if (!isset($node->nid) || isset($node->is_new)) {
os2web_borger_dk_articles_autocomplete_form($form, $form_state);
}
$locked_os2web_types = array('field_os2web_borger_dk_url' => 1);
$admin_display_fields = variable_get('os2web_borger_dk_articles_display');
$data = field_info_instances('node', 'borger_dk_article');
// First we create a list of all field-names and labels.
$checkbox_opts = array();
$initial_values = array();
$data['title'] = array('label' => 'Title');
$visible_items = (isset($form['#node']->borger_dk_article['field_settings'])) ? $form['#node']->borger_dk_article['field_settings'] : NULL;
$admin_last_settings = variable_get('os2web_borger_dk_aritcles_admin_last_settings');
foreach ($data as $type => $item) {
// Then we insert field label to our checkboxes options.
$checkbox_opts[$type] = t($item['label']);
// admin-config says we should show this item as an option
if ($admin_display_fields[$type]) {
if (empty($visible_items) || (!empty($visible_items) && !empty($visible_items[$type]))) {
//if ($visible_items != '0') {
//If visible_items is empty that means we should use admin-config
//or if the type of visible_items is set, and set to be displayed
//then we add this type to the default_values
$initial_values[] = $type;
}
else {
if ($admin_last_settings[$type] != $admin_display_fields[$type] && $visible_items[$type] == $admin_last_settings[$type]) {
$initial_values[] = $type;
}
}
}
}
variable_set('os2web_borger_dk_aritcles_admin_last_settings', $admin_display_fields);
// This is the field fieldset.
$form['fields_visible_formset'] = array(
'#type' => 'fieldset',
'#title' => t('Toggle display'),
'#collapsible' => TRUE,
'#description' => t('Set the visibility of article fields.'),
'#group' => 'additional_settings',
);
$form['fields_visible_formset']['field_settings'] = array(
'#type' => 'checkboxes',
'#options' => $checkbox_opts,
'#description' => t("Check or uncheck the respective fields"),
'#default_value' => $initial_values,
'#after_build' => array('os2web_borger_dk_process_checkboxes'),
'#group' => 'additional_settings',
);
if (isset($form['#node']->nid)) {
$form['actions']['syncronize'] = array(
'#type' => 'submit',
'#value' => t("Update article now"),
'#weight' => 100,
'#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
'#submit' => array('os2web_borger_dk_articles_sync_submit'),
);
}
$form['#after_build'][] = 'os2web_borger_dk_articles_after_build';
// Before we exit this function we set the static form-cache value
// so that later calls to this function handling the same request
// can return much faster (instead of building the same form twice)
$os2web_borger_dk_articles_falter_form = $form;
}
}
}
}
/**
* Function os2web_borger_dk_articles_autocomplete_form().
*/
function os2web_borger_dk_articles_autocomplete_form(&$form, $form_state) {
$titles_autocomplete = variable_get('borger_dk_article_titles_sync', FALSE);
$title_search_state = (isset($form_state['values']['new_borger_dk_article_search_method'])) ? TRUE : FALSE;
$url_search = !$title_search_state;
$form['new_borger_dk_article_import'] = array(
'#type' => 'fieldset',
'#title' => t('Import Borger.dk Article'),
'#collapsible' => FALSE,
);
$form['new_borger_dk_article_import']['os2web_borger_dk_article_url_text'] = array(
'#type' => 'textfield',
'#title' => t('Borger.dk Article URL'),
'#default_value' => (isset($form_state['values']['os2web_borger_dk_article_url_text'])) ? $form_state['values']['os2web_borger_dk_article_url_text'] : '',
'#size' => 60,
'#maxlength' => 255,
);
if ($titles_autocomplete) {
$form['new_borger_dk_article_import']['os2web_borger_dk_article_title_text'] = array(
'#type' => 'textfield',
'#title' => t('Borger.dk Article title'),
'#default_value' => (isset($form_state['values']['os2web_borger_dk_article_title_text'])) ? $form_state['values']['os2web_borger_dk_article_title_text'] : '',
'#autocomplete_path' => 'import/borger-dk-article/autocomplete',
'#size' => 60,
'#maxlength' => 255,
'#attributes' => array('class' => array('auto_submit')),
);
$form['new_borger_dk_article_import']['os2web_borger_dk_article_title_search'] = array(
'#type' => 'checkbox',
'#title' => t('Search for Borger.dk Article by Title-search'),
'#description' => t('If checked Borger.dk articles are found by title (by URL if un-checked).'),
'#default_value' => ($url_search) ? 1 : 0,
'#after_build' => array('_os2web_borger_dk_articles_autocomplete_form_load_js'),
);
}
}
/**
* Function _os2web_borger_dk_articles_autocomplete_form_load_js().
*/
function _os2web_borger_dk_articles_autocomplete_form_load_js($element) {
$autosubmit_js = '
$(document).ready(function(){
Drupal.jsAC.prototype.select = function (node) {
this.input.value = $(node).data("autocompleteValue");
if(jQuery(this.input).hasClass("auto_submit")){
this.input.form.submit();
}
};
});';
$must_auto_submit = variable_get('borger_dk_article_titles_search_auto_submit', FALSE);
if (!$must_auto_submit) {
$autosubmit_js = '';
}
$js = '(function ($) {
Drupal.behaviors.switchfield = {
attach: function(context, settings) {
var checked1 = $("#edit-os2web-borger-dk-article-title-search").attr("checked");
if (checked1) {
$(".form-item-os2web-borger-dk-article-url-text").hide();
$(".form-item-os2web-borger-dk-article-title-text").show();
}
else {
$(".form-item-os2web-borger-dk-article-url-text").show();
$(".form-item-os2web-borger-dk-article-title-text").hide();
}
$("#edit-os2web-borger-dk-article-title-search").click(function() {
var checked = $(this).attr("checked");
if (checked) {
$(".form-item-os2web-borger-dk-article-url-text").hide(500);
$(".form-item-os2web-borger-dk-article-title-text").show(500);
}
else {
$(".form-item-os2web-borger-dk-article-url-text").show(500);
$(".form-item-os2web-borger-dk-article-title-text").hide(500);
}
});' . $autosubmit_js . '
}
}
})(jQuery);';
drupal_add_js($js, 'inline');
return $element;
}
/**
* Function os2web_borger_dk_articles_after_build().
*/
function os2web_borger_dk_articles_after_build($form, &$form_state) {
// Some of the fields are handled exclusively by OS2web.
// These fields are required on node-add, and can NOT be
// changed later on (ie. locked).
$locked_os2web_types = array('field_os2web_borger_dk_url' => 1);
$nid = $form_state['values']['nid'];
$admin_display_fields = variable_get('os2web_borger_dk_articles_display', array(NULL));
// First we check if this is a node/add-type by checking the node->nid.
if (!empty($nid)) {
// This is an old node that is being edited.
// We must unset all form-elements that has been
// marked as hidden in the admin-display-settings.
foreach ($admin_display_fields as $type => $item) {
if (empty($item) && empty($locked_os2web_types[$type])) {
os2web_borger_dk_articles_fix_disabled($form[$type]);
}
}
// Then we must disable all fields that has been marked as
// non-editable in the admin-editable-settings.
$value_editable = variable_get('os2web_borger_dk_articles_editable', array(NULL));
foreach ($value_editable as $type => $editable) {
if ((empty($editable) || !empty($locked_os2web_types[$type])) && !empty($form[$type])) {
os2web_borger_dk_articles_fix_disabled($form[$type]);
}
if ($type == 'field_os2web_byline' && !empty($form[$type])) {
$form[$type]['#format'] = BORGERDK_TEXT_FORMAT_PLAIN;
}
}
// Finally we lock the special types.
foreach ($locked_os2web_types as $type => $locked) {
if (isset($form[$type])) {
$form[$type]['#required'] = FALSE;
$form[$type]['und']['#required'] = FALSE;
$form[$type]['und'][0]['#required'] = FALSE;
$form[$type]['und'][0]['value']['#required'] = FALSE;
os2web_borger_dk_articles_fix_disabled($form[$type]);
}
}
}
else {
// This is a brand new node-add form, and we must hide every
// form-field except the locked types.
$data = field_info_instances('node', 'borger_dk_article');
foreach ($data as $type => $item) {
$form[$type]['#access'] = FALSE;
}
$form['field_os2web_borger_dk_url']['#required'] = FALSE;
$form['field_os2web_borger_dk_url']['und']['#required'] = FALSE;
$form['field_os2web_borger_dk_url']['und'][0]['#required'] = FALSE;
$form['field_os2web_borger_dk_url']['und'][0]['value']['#required'] = FALSE;
$form['title']['#required'] = FALSE;
$form['title']['#access'] = FALSE;
// TODO: Move this to the module-feature, and delete from this location.
if (isset($form['path']['pathauto']['#default_value'])) {
$form['path']['pathauto']['#checked'] = FALSE;
}
$form['status'] = 0;
$form['promote'] = 0;
}
return $form;
}
/**
* Function os2web_borger_dk_process_checkboxes().
*/
function os2web_borger_dk_process_checkboxes($element) {
$admin_display_fields = variable_get('os2web_borger_dk_articles_display');
foreach (element_children($element) as $key) {
if (!$admin_display_fields[$key]) {
$element[$key]['#attributes'] = array('disabled' => 'disabled');
$element[$key]['#description'] = t('Please go to OS2web Borger.dk settings to change the visibility for this field');
}
}
return $element;
}
/**
* Function os2web_borger_dk_articles_fix_disabled().
*/
function os2web_borger_dk_articles_fix_disabled(&$elements) {
foreach (element_children($elements) as $key) {
if (isset($elements[$key]) && $elements[$key]) {
// Recurse through all child elements
os2web_borger_dk_articles_fix_disabled($elements[$key]);
}
}
if (!isset($elements['#attributes'])) {
$elements['#attributes'] = array();
}
$elements['#attributes']['disabled'] = 'disabled';
}
/**
* Implements hook_node_load().
*/
function os2web_borger_dk_articles_node_load($nodes, $types) {
// Decide whether any of $types are relevant to our purpose
// We only work on the "borger_dk_article" node-types
if (in_array('borger_dk_article', $types)) {
// Gather our extra data for each of these nodes
$result = db_query('SELECT nid, external_id, external_status, external_url, field_settings, published_date, last_updated FROM {os2web_borger_dk_articles} WHERE nid IN (:nids)', array(':nids' => array_keys($nodes)));
// Add our extra data to the node objects.
foreach ($result as $record) {
$field_settings = unserialize($record->field_settings);
$nodes[$record->nid]->borger_dk_article = array(
'external_id' => $record->external_id,
'external_status' => $record->external_status,
'external_url' => $record->external_url,
'field_settings' => $field_settings,
'published_date' => $record->published_date,
'last_updated' => $record->last_updated,
);
}
}
}
/**
* Implements hook_node_view().
*/
function os2web_borger_dk_articles_node_view($node, $view_mode, $langcode) {
if ($node->type == 'borger_dk_article') {
$fields = $node->borger_dk_article['field_settings'];
// First get admin display settings.
$admin_display_fields = variable_get('os2web_borger_dk_articles_display');
$locked_os2web_types = array('field_os2web_borger_dk_url' => 1);
foreach ($admin_display_fields as $type => $value) {
// If ADMIN set this field to display
if ($admin_display_fields[$type]) {
// If EDITOR set this field to be hidden.
if ($fields[$type] == '0') {
$content_field = (isset($node->content[$type]['#field_name'])) ? $node->content[$type]['#field_name'] : '';
if ($content_field == $type) {
$node->content[$type]['0']['#markup'] = '';
}
}
}
// If ADMIN set this field to be hidden
else {
$content_field = (isset($node->content[$type]['#field_name'])) ? $node->content[$type]['#field_name'] : '';
if ($content_field == $type) {
$node->content[$type]['0']['#markup'] = '';
}
}
}
drupal_add_js(drupal_get_path('module', 'os2web_borger_dk_articles') .'/js/os2web_borger_dk_articles.js', 'file');
drupal_add_css(drupal_get_path('module', 'os2web_borger_dk_articles') .'/css/os2web_borger_dk_articles.css', 'file');
}
}
/**
* Implements hook_node_insert().
*/
function os2web_borger_dk_articles_node_insert($node) {
if ($node->type == 'borger_dk_article') {
$borgerdk_data = $node->borger_dk_article;
$serialized_data = serialize($borgerdk_data['field_settings']);
db_insert('os2web_borger_dk_articles')
->fields(array(
'nid' => $node->nid,
'external_id' => $borgerdk_data['external_id'],
'external_status' => $borgerdk_data['external_status'],
'external_url' => $borgerdk_data['external_url'],
'field_settings' => $serialized_data,
'last_updated' => $borgerdk_data['last_updated'],
'published_date' => $borgerdk_data['published_date'],
))
->execute();
}
}
/**
* Implements hook_node_delete().
*/
function os2web_borger_dk_articles_node_delete($node) {
if ($node->type == 'borger_dk_article') {
// First we delete the article-data from the node-additions table
db_delete('os2web_borger_dk_articles')
->condition('nid', $node->nid)
->execute();
// Then we set the status to "not imported" in the "Titles list"-table
db_update('os2web_borger_dk_titles')
->fields(array('ArticleStatus' => 0))
->condition('ArticleID', $node->borger_dk_article['external_id'], '=')
->execute();
}
}
/**
* Implements hook_node_validate().
*/
function os2web_borger_dk_articles_node_validate($node, $form, &$form_state) {
if ($node->type == 'borger_dk_article') {
// Enforce a minimum word length of 3 on punch lines.
$admin_title_search = variable_get('borger_dk_article_titles_sync', FALSE);
$titles_search = isset($form_state['values']['os2web_borger_dk_article_title_search'])? $form_state['values']['os2web_borger_dk_article_title_search'] : FALSE;
$url_text = isset($form_state['values']['os2web_borger_dk_article_url_text']) ? $form_state['values']['os2web_borger_dk_article_url_text'] : FALSE;
// If admin config set up : import Borger.dk article by URL
// TODO: Check if this if-statement works as expected, and
// if we can drop the "!isset($node->nid)" part
if ((!$admin_title_search) || ($titles_search == '0' && !isset($node->nid))) {
if (!$titles_search && !isset($node->nid)) {
if (!empty($url_text)) {
$url = $url_text;
$pos = strpos($url, 'borger.dk/Sider');
if ($pos === FALSE) {
form_set_error('os2web_borger_dk_article_url_text', t('The Borger.dk-URL is not valid, please write a valid Borger.dk-URL.'));
}
}
else {
form_set_error('os2web_borger_dk_article_url_text', t('The Borger.dk-URL is empty, please write a valid Borger.dk-URL.'));
}
}
}
// If admin config set up : import Borger.dk article by article title.
else {
// If search article checkbox by Title-search is CHECKED.
// TODO: Check if we can drop this if-statement. The else-statement above
// should be sufficient if the matched if-statement really works.
if ($titles_search == '1') {
$borger_dk_title = !empty($form_state['values']['os2web_borger_dk_article_title_text']) ? $form_state['values']['os2web_borger_dk_article_title_text'] : FALSE;
if (!$borger_dk_title) {
form_set_error('os2web_borger_dk_article_title_text', t('The Borger.dk Article title is empty, please write a Borger.dk Article title'));
}
$matches = array();
$aid = 0;
// This preg_match() looks for the last pattern like [33334] and if found extracts the numeric portion.
$result = preg_match('/\(ID:([0-9]+)\)$/', $borger_dk_title, $matches);
if ($result > 0) {
// If $result is nonzero, we found a match and can use it as the index into $matches.
$aid = $matches[$result];
$status = db_query('SELECT ArticleStatus FROM {os2web_borger_dk_titles} WHERE ArticleID = :aid', array(':aid' => $aid))->fetchField();
if ($status < 0) {
// This article is no longer availlable and we tell the user so
drupal_set_message(t('The Borger.dk article with title "!title" is no longer availlable', array('!title' => $borger_dk_url)), 'warning');
form_set_error('os2web_borger_dk_article_title_text', t('The Borger.dk Article-title has been deleted, please write a valid Borger.dk-URL.'));
}
}
}
}
}
}
/**
* Function os2web_borger_dk_articles_sync_submit().
*/
function os2web_borger_dk_articles_sync_submit($form, &$form_state) {
// Get the node->nid from the form['#node']
$nid = $form['#node']->nid;
// Update the article
os2web_borger_dk_articles_update_article($nid);
drupal_set_message(t('The article has been updated with content from Borger.dk'), 'status');
drupal_goto('node/' . $nid . '/edit');
}
/**
* Update a single article with latest content from borger.dk
*
* @param int $nid
* The node we are updating.
*/
function os2web_borger_dk_articles_update_article($nid) {
// First we find the external_id, and last_update time for this article
$data = db_query('SELECT external_id, last_updated FROM {os2web_borger_dk_articles} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();
// Then we fetch the article item from the Borger.dk webservice
$wsdl = variable_get('os2web_borger_dk_webservice', 'https://www.borger.dk/_vti_bin/borger/ArticleExport.svc?wsdl');
$article = _os2web_borger_dk_articles_GetArticleByID($data->external_id, $wsdl);
// Now we update the node content with the fetched article content
_os2web_borger_dk_articles_update_node_content($nid, $article);
}
/**
* Implements hook_node_submit().
*/
function os2web_borger_dk_articles_node_submit(&$node, $form, &$form_state) {
if ($node->type == 'borger_dk_article') {
// We must check if this is a "brand new" article or if it exists in the
// database already (NB: That's how we find out if it is brand new or not)
// Get the node->nid from the form['#node']
$nid = (!empty($form_state['values']['nid'])) ? $form_state['values']['nid'] : NULL;
if (!empty($nid)) {
// We have a node and should fetch field-values from form_state
// nid, external_id, external_url, field_settings, published_date, last_update
// EXCEPT: ONLY field_settings CAN BE UPDATED!!
$field_settings = $form_state['values']['field_settings'];
// Check admin field settings : are there fields set as hidden by admin.
$admin_display_fields = variable_get('os2web_borger_dk_articles_display');
foreach ($admin_display_fields as $type => $items) {
if (!$admin_display_fields[$type]) {
$field_settings[$type] = $type;
}
}
$serialized_data = serialize($field_settings);
db_update('os2web_borger_dk_articles')
->fields(array('field_settings' => $serialized_data))
->condition('nid', $nid, '=')
->execute();
// All other fields are handled by the normal Drupal field-handling
}
else {
// We do not(!) have a node->nid and this is a brand new node
// We must get the Borger.dk-URL, fetch the article, and store
// the borger.dk-article content (i.e. the new node)
$wsdl = variable_get('os2web_borger_dk_webservice', 'https://www.borger.dk/_vti_bin/borger/ArticleExport.svc?wsdl');
$titles_autocomplete = variable_get('borger_dk_article_titles_sync', FALSE);
$borger_dk_url = $form_state['values']['os2web_borger_dk_article_url_text'];
$borger_dk_title = $form_state['values']['os2web_borger_dk_article_title_text'];
$search_method = $form_state['values']['os2web_borger_dk_article_title_search'];
if ($search_method) {
// The title has been autocompleted, and we must find the ArticleID
$matches = array();
$aid = -1;
// This preg_match() looks for the last pattern like [33334] and if found extracts the numeric portion.
$result = preg_match('/\(ID:([0-9]+)\)$/', $borger_dk_title, $matches);
if ($result > 0) {
// If $result is nonzero, we found a match and can use it as the index into $matches.
$aid = $matches[$result];
$sql = "SELECT `ArticleID`, `ArticleStatus` FROM {os2web_borger_dk_titles} WHERE `ArticleID` = " . $aid . " LIMIT 1";
$data = db_query($sql)->fetchObject();
if ($data->ArticleStatus < 0) {
// This article is no longer availlable and we tell the user so
drupal_set_message(t('The Borger.dk article with title "!title" is no longer availlable', array('!title' => $borger_dk_title)), 'warning');
drupal_goto('node/add/borger-dk-article');
return;
}
elseif ($data->ArticleStatus > 0) {
// We have already imported this article and node->nid = ArticleStatus
drupal_set_message(t('The Borger.dk article with title "!title" has already been imported.', array('!title' => $borger_dk_title)), 'status');
drupal_set_message(t('You can re-import the article by clicking on the "Update now"-button below.'), 'status');
drupal_goto('node/' . $data->ArticleStatus . '/edit');
return;
}
elseif ($data->ArticleStatus == 0) {
$aid = $data->ArticleID;
}
}
else {
// Lets look for the text directly in our Title list
drupal_set_message(t('No Borger.dk article with title "!title" exists.', array('!title' => $borger_dk_title)), 'warning');
drupal_goto('node/add/borger-dk-article');
}
if (isset($aid) && $aid >= 0) {
// We have not imported this article before, and we do so now
$article = _os2web_borger_dk_articles_GetArticleByID($aid, $wsdl);
}
else {
$borger_dk_title = preg_replace('/ \(ID:([0-9]+)\)$/', '', $borger_dk_title);
drupal_set_message(t('Could not find any Borger.dk article with title "!title"', array('!title' => $borger_dk_title)), 'warning');
drupal_goto('node/add/borger-dk-article');
return;
}
}
else {
// Now we fetch the article item from the Borger.dk webservice
$article = _os2web_borger_dk_articles_GetArticleByUrl($borger_dk_url, $wsdl);
if (!empty($article['Exceptions']) || !empty($article['error'])) {
drupal_set_message(t('An error occured or an exception was thrown by the Borger.dk webservice for the specified URL.'), 'error');
drupal_set_message(t('You can fetch this article when the webservice is responsive again.'), 'error');
drupal_goto('node/add/borger-dk-article');
return;
}
}
// TODO: Expand system_settings_form with visibility for microArticle's
// TODO: Expand node->field_settings with visibility for microArticle's
$body = '';
foreach ($article['kernetekst'] as $div => $content) {
// TODO: Insert check for microArticle visibility. Use div values
$body .= $content . "\n";
}
// A user might assign the node author by entering a user name in the node
// form, which we then need to translate to a user ID.
if (isset($node->name)) {
if ($account = user_load_by_name($node->name)) {
$node->uid = $account->uid;
}
else {
$node->uid = 0;
}
}
// And we update all the node-fields with the article-values
$node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
$node->validated = TRUE;
// Insert default value of a new node.
$node->type = 'borger_dk_article';
$node->title = (!empty($article['title'])) ? $article['title'] : '';
$node->body['und'][0]['value'] = (!empty($body)) ? $body : '';
$node->field_os2web_borger_dk_url['und'][0]['value'] = (!empty($article['external_url'])) ? $article['external_url'] : '';
$node->field_os2web_header['und'][0]['value'] = (!empty($article['header'])) ? $article['header'] : '';
$node->field_os2web_selfservice['und'][0]['value'] = (!empty($article['selvbetjeningslinks'])) ? $article['selvbetjeningslinks'] : '';
$node->field_os2web_byline['und'][0]['value'] = (!empty($article['byline'])) ? $article['byline'] : '';
$node->field_os2web_legislation['und'][0]['value'] = (!empty($article['lovgivning'])) ? $article['lovgivning'] : '';
$node->field_os2web_shortlist['und'][0]['value'] = (!empty($article['huskeliste'])) ? $article['huskeliste'] : '';
$node->field_os2web_recommended['und'][0]['value'] = (!empty($article['anbefaler'])) ? $article['anbefaler'] : '';
$node->body['und'][0]['safe_value'] = (!empty($body)) ? $body : '';
$node->field_os2web_borger_dk_url['und'][0]['safe_value'] = (!empty($article['external_url'])) ? $article['external_url'] : '';
$node->field_os2web_header['und'][0]['safe_value'] = (!empty($article['header'])) ? $article['header'] : '';
$node->field_os2web_selfservice['und'][0]['safe_value'] = (!empty($article['selvbetjeningslinks'])) ? $article['selvbetjeningslinks'] : '';
$node->field_os2web_byline['und'][0]['safe_value'] = (!empty($article['byline'])) ? $article['byline'] : '';
$node->field_os2web_legislation['und'][0]['safe_value'] = (!empty($article['lovgivning'])) ? $article['lovgivning'] : '';
$node->field_os2web_shortlist['und'][0]['safe_value'] = (!empty($article['huskeliste'])) ? $article['huskeliste'] : '';
$node->field_os2web_recommended['und'][0]['safe_value'] = (!empty($article['anbefaler'])) ? $article['anbefaler'] : '';
$node->body['und'][0]['format'] = BORGERDK_TEXT_FORMAT_HTML;
$node->field_os2web_header['und'][0]['format'] = BORGERDK_TEXT_FORMAT_HTML;
$node->field_os2web_selfservice['und'][0]['format'] = BORGERDK_TEXT_FORMAT_HTML;
$node->field_os2web_byline['und'][0]['format'] = BORGERDK_TEXT_FORMAT_PLAIN;
$node->field_os2web_legislation['und'][0]['format'] = BORGERDK_TEXT_FORMAT_HTML;
$node->field_os2web_shortlist['und'][0]['format'] = BORGERDK_TEXT_FORMAT_HTML;
$node->field_os2web_recommended['und'][0]['format'] = BORGERDK_TEXT_FORMAT_HTML;
$field_settings = $form_state['values']['field_settings'];
// Check admin field settings : are there fields set as hidden by admin.
$admin_display_fields = variable_get('os2web_borger_dk_articles_display');
foreach ($admin_display_fields as $type => $items) {
if (!$admin_display_fields[$type]) {
$field_settings[$type] = $type;
}
}
// TODO: Perform a logical-test (on paper) to see if the external_status is correct.
$external_status = (empty($article['Exceptions']) && empty($article['error'])) ? 1 : 0;
$external_status = (!empty($article['error']) && $article['error_type'] == 'not_found') ? -1 : $external_status;
$node->borger_dk_article = array(
'external_id' => $article['external_id'],
'external_url' => $article['external_url'],
'external_status' => $external_status,
'field_settings' => $field_settings,
'published_date' => strtotime($article['published_date']),
'last_updated' => strtotime($article['last_updated']),
);
if (!empty($article['Exceptions']) || !empty($article['error'])) {
drupal_set_message(t('An exception was thrown by the Borger.dk webservice for the specified URL.'), 'error');
drupal_set_message(t('You can fetch this article when the webservice is responsive again.'), 'error');
drupal_goto('node/add/borger-dk-article');
}
else {
// We need to store the field values and article-settings
node_save($node);
// Then we need to update the ArticleStatus in the Title-list
if ($node->nid) {
db_update('os2web_borger_dk_titles')
->fields(array('ArticleStatus' => $node->nid))
->condition('ArticleID', $article['external_id'], '=')
->execute();
drupal_goto('node/' . $node->nid . '/edit');
}
}
}
}
}
/**
* Implements hook_cron().
*/
function os2web_borger_dk_articles_cron() {
$cron_settings_time_articles = variable_get('borger_dk_nightly_article_sync', FALSE);
$titles_autocomplete = variable_get('borger_dk_article_titles_sync', FALSE);
$borger_dk_menus_import = variable_get('borger_dk_articles_borger_dk_menus_import', FALSE);
$cron_settings_time_menus = variable_get('borger_dk_articles_nightly_menu_sync');
// Then we can find out if it is time for our cron-job to run
if (!empty($cron_settings_time_articles) || !empty($cron_settings_time_menus)) {
$current_time = time();
$current_hour = date('G', $current_time);
if ($current_hour == '0') {
$current_hour = '24';
}
// Is it time for auto-updating imported Borger.dk-articles.
if ($cron_settings_time_articles == $current_hour) {
// Run the auto-update for articles already imported.
_os2web_borger_dk_articles_cronbatch();
// If Borger.dk-menus should not be fetched then we must
// still fetch availlable Borger.dk-titles if autocomplete
// has been activated.
if ($titles_autocomplete && !$borger_dk_menus_import) {
// We must fetch a list of all availlable articles from Borger.dk.
_os2web_borger_dk_articles_titles_cronbatch();
}
}
// Is it time for fetching Borger.dk-menus or should we fetch a new
// list of availlable Borger.dk-titles. In order for this function
// to run only once we must have extensive checks on what kind of
// functionality has been enabled.
if (($titles_autocomplete && !$borger_dk_menus_import) || ($borger_dk_menus_import && ($cron_settings_time_menus == $current_hour))) {
// Run the auto-update for menus, and article-titles / autocomplete.
// We must fetch a list of all availlable articles from Borger.dk.
_os2web_borger_dk_articles_titles_cronbatch();
}
}
// We check for deleted-items in the queue at every cron-run
_os2web_borger_dk_articles_cron_queue();
}
/**
* Function _os2web_borger_dk_articles_cron_queue().
*/
function _os2web_borger_dk_articles_cron_queue() {
$queue = DrupalQueue::get('os2web_borger_dk_articles_delete_queue');
$result = db_query('SELECT nid, external_id FROM {os2web_borger_dk_articles} WHERE external_status = -2');
foreach ($result as $item) {
$qitem = array('nid' => $item->nid, 'external_id' => $item->external_id);
$queue->createItem($qitem);
}
}
/**
* Function _os2web_borger_dk_articles_cronbatch()
*/
function _os2web_borger_dk_articles_cronbatch() {
// First we determine the time for our last check for new updates
$this_run = time();
$last_run = variable_get('os2web_borger_dk_articles_last_update', time());
$updated_after = date('Y-m-d\TH\:i\:s', $last_run);
$titles_autocomplete = variable_get('borger_dk_article_titles_sync', FALSE);
// Next we get a list of all imported articles
$article_id_list = array();
$article_id_to_nid = array();
$result = db_query('SELECT nid, external_id FROM {os2web_borger_dk_articles} WHERE external_status > 0');
foreach ($result as $item) {
// We also build an index of "external_id" => "nid"
$article_id2nid[$item->external_id] = $item->nid;
$article_id_list[] = $item->external_id;
}
// Then we get all the updated articles. We can not(!) use the LastUpdated-
// field in the 'os2web_borger_dk_titles'-table since it only works when
// titles-autocomplete has been activated.
$articles = array();
$wsdl = variable_get('os2web_borger_dk_webservice', 'https://www.borger.dk/_vti_bin/borger/ArticleExport.svc?wsdl');
$articles = _os2web_borger_dk_articles_GetArticlesByIDs($article_id_list, $updated_after, $wsdl);
// We must check if the webservice throws ANY errors
$any_webservice_errors = FALSE;
//$deleted_items = array();
$deleted_ids = array();
$error_items = array();
// And for each of the found articles we update the node content
foreach ($articles as $article) {
$external_id = $article['external_id'];
// We only update articles we already know the nid for (just in case)
if (!empty($article_id2nid[$external_id])) {
$nid = $article_id2nid[$external_id];
// First we check if the article is an error-array
if (empty($article['no_updates'])) {
// We only update articles that does not contain an error
if (empty($article['Exceptions']) && empty($article['error'])) {
_os2web_borger_dk_articles_update_node_content($nid, $article);
}
if (!empty($article['Exceptions'])) {
$any_webservice_errors = TRUE;
}
}
else {
// Articles with errors might have been deleted, and we must handle it.
// But if "Titles autocomplete" is active, then it will be handled by
// the titles-auto-update in the cron-function:
// _os2web_borger_dk_articles_titles_cronbatch()
if (!$titles_autocomplete) {
// Try to get this one article, to see if it still exists
$item = _os2web_borger_dk_articles_GetArticleByID($external_id, $wsdl);
if (!empty($item['error']) && $item['error'] == 1) {
if (!empty($item['error_type']) && ($item['error_type'] == 'not_found')) {
//$deleted_items[$nid] = $item;
$deleted_ids[] = $nid;
}
else {
$error_items[$nid] = $item;
}
}
}
}
}
}
// Next we update/queue the articles that should be deleted
// deleted_ids will only contain elements if "Titles autocomplete" is inactive
if (!empty($deleted_ids)) {
$sql = "UPDATE {os2web_borger_dk_articles} SET external_status = -2 WHERE nid IN (:nids)";
$nid_list = implode(',', $deleted_ids);
db_query($sql, array(':updated' => $this_run, ':nids' => $nid_list));
}
// Then we log the errors that occured but we could not handle
if (!empty($error_items)) {
foreach ($error_items as $nid => $error) {
$msg = 'Borger.dk webservice returned an error for nid=%nid, external_id=%eid. Error code: %ecode. Error string: %estring';
watchdog(
'Borger.dk-articles',
$msg,
$variables = array(
'%nid' => $nid,
'%eid' => $error['external_id'],
'%ecode' => $error['error_code'],
'%estring' => $error['error_string'])
);
}
}
// Now we must update the "last_updated" variable.
// But only if no errors were encountered
if (!$any_webservice_errors) {
variable_set('os2web_borger_dk_articles_last_update', $this_run);
$updated_at = date('Y-m-d\TH\:i\:s', $this_run);
$msg = 'All Borger.dk webservice articles have been updated succesfully at: %success';
watchdog('Borger.dk-articles', $msg, $variables = array('%success' => $updated_at));
}
else {
$should_have_been = date('Y-m-d\TH\:i\:s', $this_run);
$msg = 'Borger.dk webservice threw errors while updating articles at: %runtime. Not all articles have been updated. Last succesful automated update was at: %success';
watchdog('Borger.dk-articles', $msg, $variables = array('%runtime' => $should_have_been, '%success' => $updated_after));
}
}
/**
* Function _os2web_borger_dk_articles_titles_cronbatch()
*/
function _os2web_borger_dk_articles_titles_cronbatch($first_run = FALSE) {
$borger_dk_menus_import = variable_get('borger_dk_articles_borger_dk_menus_import', FALSE);
$titles_availlable = array();
$wsdl = variable_get('os2web_borger_dk_webservice', 'https://www.borger.dk/_vti_bin/borger/ArticleExport.svc?wsdl');
$titles_availlable = _os2web_borger_dk_articles_GetAllArticles($wsdl);
// We must update the table of Borger.dk Article titles
// And to do that we must know what is already there, so that we can mark
// un-listed titles for deletion
$titles_result = db_query('SELECT `ArticleID`, `ArticleStatus`, `LastUpdated` FROM {os2web_borger_dk_titles} WHERE `ArticleStatus` >= 0');
$known_ids = array();
foreach ($titles_result as $item) {
$aid = $item->ArticleID;
$known_ids[$aid] = array('ArticleStatus' => $item->ArticleStatus, 'LastUpdated' => $item->LastUpdated);
}
foreach ($titles_availlable as $id => $item) {
$aid = $item['ArticleID'];
// Check the known status (if any)
if (isset($known_ids[$aid])) {
// Before we update we check if it has been changed
$updated = strtotime($item['LastUpdated']);
if ($updated > $known_ids[$aid]['LastUpdated']) {
// We know about this article and we update the DB-entry
// because the content has changed since we updated it last
db_update('os2web_borger_dk_titles')
->fields(array(
'ArticleTitle' => $item['ArticleTitle'],
'ArticleUrl' => $item['ArticleUrl'],
'LastUpdated' => $updated,
'FORMFields' => $item['FORMFields'],
))
->condition('ArticleID', $aid, '=')
->execute();
}
// We remove this item from the list of known ID's so that we can
// find out if all the known ID's were found in the list
unset($known_ids[$aid]);
}
else {
// This is a new article-title and we must insert it into DB
db_insert('os2web_borger_dk_titles')
->fields(array(
'ArticleID' => $aid,
'ArticleTitle' => $item['ArticleTitle'],
'ArticleUrl' => $item['ArticleUrl'],
'LastUpdated' => strtotime($item['LastUpdated']),
'PublishingDate' => strtotime($item['PublishingDate']),
'FORMFields' => $item['FORMFields'],
))
->execute();
}
}
// Should we also import the menu-structure from Borger.dk.
if (!empty($borger_dk_menus_import)) {
// We must step through the FORM-Fields in the availlable titles
// in order to recreate the Borger.dk-menu structure.
//$menu = _os2web_borger_dk_articles_build_borger_dk_menus($titles_availlable);
}
// NB: If this is run for the first time we should do an early exit
// No need to look for data to delete when no data exists
if ($first_run) {
// Calling functions should never set this. Only called from hook_install
return;
}