/
ItemReferencesPlugin.php
1017 lines (856 loc) · 37.1 KB
/
ItemReferencesPlugin.php
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
DEFINE("ITEM_REFERENCES_MAP_HEIGHT_DEFAULT", 300);
/**
* ItemReferences plugin.
*
* @package Omeka\Plugins\ItemReferences
*/
class ItemReferencesPlugin extends Omeka_Plugin_AbstractPlugin
{
// Define Hooks
protected $_hooks = array(
'initialize',
'install',
'uninstall',
'after_save_item',
'config_form',
'config',
'admin_head',
'public_head',
'admin_items_show',
'public_items_show',
);
//Define Filters
// protected $_filters = array('admin_navigation_main');
protected $_options = array(
'item_references_select' => "[]",
'item_references_second_level' => true,
'item_references_map_height' => ITEM_REFERENCES_MAP_HEIGHT_DEFAULT,
'item_references_show_maps' => true, // obsolete
'item_references_show_lines' => false, // obsolete
'item_references_configuration' => "[]",
);
private static $_withGeoLoc; // flag -- is the GeoLocation plugin installed and active
private static $_withSecondLevel; // flag -- do or do not follow second level references
private static $_geoLocations = array(); // collecting geolocations of referenced items
private static $_secondLevelGeoLocations = array(); // collecting geolocations of 2nd level referenced items
private static $_enhancedGeoLog; // enhanced version of GeoLocations plugin supporting map overlays
/**
* Initialize the plugin
*/
public function hookInitialize() {
add_translation_source(dirname(__FILE__) . '/languages');
$db = get_db();
// Add filters
$filter_names = array(
'Display',
'ElementInput',
);
$referenceElements = SELF::_retrieveReferenceElements();
foreach($referenceElements as $element_id ) {
$element = $db->getTable('Element')->find($element_id);
$elementSet = $db->getTable('ElementSet')->find($element->element_set_id);
foreach ($filter_names as $filter_name) {
add_filter(
array($filter_name, 'Item', $elementSet->name, $element->name),
array($this, "filter$filter_name")
);
}
}
SELF::$_withGeoLoc = SELF::_withGeoLoc();
SELF::$_withSecondLevel = !!intval(get_option('item_references_second_level'));
SELF::$_enhancedGeoLog = ( (SELF::$_withGeoLoc) AND
$db->fetchOne("SHOW COLUMNS FROM $db->Locations LIKE 'overlay'")
);
}
/**
* Retrieve the element IDs that are supposed to store references from JSON configuration variable
*/
protected function _retrieveReferenceElements() {
$referenceElementsJson=get_option('item_references_select');
if (!$referenceElementsJson) { $referenceElementsJson="[]"; }
$referenceElements = json_decode($referenceElementsJson,true);
return $referenceElements;
}
/**
* Retrieve the element configurations (map style / color) from JSON configuration vafiable
*/
protected function _retrieveReferenceElementConfiguration() {
$itemReferencesConfiguration = get_option('item_references_configuration');
if (!$itemReferencesConfiguration) { $itemReferencesConfiguration="null"; }
$itemReferencesConfiguration = json_decode($itemReferencesConfiguration,true);
return $itemReferencesConfiguration;
}
/**
* Determine whether or not the Geolocations plugin is installed
*/
private function _withGeoLoc() {
$db = get_db();
return $db->fetchOne("SELECT active FROM $db->Plugins WHERE name='GeoLocation' LIMIT 1");
}
/**
* Install the plugin.
*/
public function hookInstall() {
SELF::_installOptions();
}
/**
* Uninstall the plugin.
*/
public function hookUninstall() {
SELF::_uninstallOptions();
}
protected function myAddSearchText($item, $enrichedSearchTexts) {
// http://omeka.org/forums/topic/adding-item-search-text-from-a-plugin
//look up the existing search text
$searchText = $this->_db->getTable('SearchText')->findByRecord('Item', $item->id);
// searchText should already exist, but if something goes wrong, create it
if (!$searchText) {
$searchText = new SearchText;
$searchText->record_type = 'Item';
$searchText->record_id = $item->id;
$searchText->public = $item->public;
$searchText->title = metadata($item, array('Dublin Core', 'Title'));
}
$searchText->text .= ' ' . $enrichedSearchTexts;
$searchText->save();
}
/**
* Retrieve referenced items' titles and add them to item's search text
*
* @param array $args
*/
// saving relation comments into the search index
public function hookAfterSaveItem($args) {
$itemId = intval(@$args["record"]["id"]);
if ($itemId) {
$item = get_record_by_id('Item', $itemId);
$itemReferencesSelect = SELF::_retrieveReferenceElements();
if ($itemReferencesSelect) {
$elementIds = implode(",", $itemReferencesSelect);
$db = get_db();
$sql = "SELECT text FROM $db->ElementTexts".
" WHERE record_id = $itemId".
" AND element_id in ($elementIds)";
$refItemIds = $db->fetchAll($sql);
if ($refItemIds) {
$refItemTitles = array();
$firstLevelIds = array();
foreach($refItemIds as $refItemId) {
$firstLevelIds[] = $refItemId["text"];
$refItemTitles[] = SELF::getTitleForId($refItemId["text"]);
}
if ( ($firstLevelIds) and (SELF::$_withSecondLevel) ) {
$firstLevelIdsVerb = implode(",", $firstLevelIds);
$sql = "SELECT text FROM $db->ElementTexts".
" WHERE record_id in ($firstLevelIdsVerb)".
" AND element_id in ($elementIds)";
$refTwoItemIds = $db->fetchAll($sql);
foreach($refTwoItemIds as $refTwoItemId) {
$refItemTitles[] = SELF::getTitleForId($refTwoItemId["text"]);
}
}
if ($refItemTitles) {
$enrichedSearchTexts = implode(" ", $refItemTitles);
SELF::myAddSearchText($item, $enrichedSearchTexts);
}
} // if ($refItemIds)
} // if ($itemReferencesSelect)
} // if ($itemId)
}
/**
* Display the plugin configuration form.
*/
public static function hookConfigForm() {
$sqlDb = get_db();
$page = intval(@$_GET["page"]);
$itemReferencesSelect = SELF::_retrieveReferenceElements();
$itemReferencesSecondLevel = SELF::$_withSecondLevel;
switch ($page) {
case 2:
// $itemReferencesShowMaps = !!get_option('item_references_show_maps');
// $itemReferencesShowLines = !!get_option('item_references_show_lines');
$itemReferencesMapHeight = intval(get_option('item_references_map_height'));
$ids = implode(",", $itemReferencesSelect);
$sql = "SELECT id, name FROM $sqlDb->Elements WHERE id in ($ids)";
$itemReferencesArr = $sqlDb->fetchALl($sql);
$itemReferencesConfiguration = SELF::_retrieveReferenceElementConfiguration();
require dirname(__FILE__) . '/config_form2.php';
break;
default:
$select = "
SELECT es.name AS element_set_name, e.id AS element_id,
e.name AS element_name, it.name AS item_type_name
FROM {$sqlDb->ElementSet} es
JOIN {$sqlDb->Element} e ON es.id = e.element_set_id
LEFT JOIN {$sqlDb->ItemTypesElements} ite ON e.id = ite.element_id
LEFT JOIN {$sqlDb->ItemType} it ON ite.item_type_id = it.id
WHERE es.id = 3
ORDER BY it.name, e.name
";
$records = $sqlDb->fetchAll($select);
$elements = array();
foreach ($records as $record) {
$optGroup = $record['item_type_name']
? __('Item Type') . ': ' . __($record['item_type_name'])
: __($record['element_set_name']);
$value = __($record['element_name']);
$elements[$optGroup][$record['element_id']] = $value;
}
$configPage2Url = url("plugins/config?name=ItemReferences&page=2");
require dirname(__FILE__) . '/config_form.php';
break;
}
}
/**
* Tiny min/max function to ensure a variable to be within a certain range
*/
protected function minMax($x, $min, $max) {
$x = ($x < $min ? $min : $x);
$x = ($x > $max ? $max : $x);
return $x;
}
/**
* Handle the plugin configuration form.
*/
public static function hookConfig() {
$page = intval(@$_POST["configPage"]);
switch ($page) {
case 2:
// $itemReferencesShowMaps = !!$_POST["item_references_show_maps"];
// set_option('item_references_show_maps', intval($itemReferencesShowMaps) );
// $itemReferencesShowLines = !!$_POST["item_references_show_lines"];
// set_option('item_references_show_lines', intval($itemReferencesShowLines) );
$itemReferencesMapHeight = 0;
if (isset($_POST["item_references_map_height"])) {
$itemReferencesMapHeight = intval($_POST["item_references_map_height"]);
}
set_option('item_references_map_height', $itemReferencesMapHeight );
$itemReferencesElements = SELF::_retrieveReferenceElements();
$elementConfigurations = array();
foreach($itemReferencesElements as $itemReferencesElement) {
$elementConfigurationType = intval(@$_POST["item_reference_type_$itemReferencesElement"]);
$elementConfigurationType = SELF::minMax($elementConfigurationType, 0, 2);
$elementConfigurationColor = intval(@$_POST["item_reference_color_$itemReferencesElement"]);
$elementConfigurationColor = SELF::minMax($elementConfigurationColor, 0, 7);
$elementConfigurations[$itemReferencesElement] = array(
$elementConfigurationType,
$elementConfigurationColor,
);
}
$itemReferencesConfiguration = json_encode($elementConfigurations);
set_option('item_references_configuration', $itemReferencesConfiguration);
break;
default:
$itemReferencesSelect = array();
$postIds=false;
if (isset($_POST["item_references_select"])) { $postIds = $_POST["item_references_select"]; }
if (is_array($postIds)) {
foreach($postIds as $postId) {
$postId = intval($postId);
if ($postId) { $itemReferencesSelect[] = $postId; }
}
}
$itemReferencesSelect = array_unique($itemReferencesSelect);
$itemReferencesSelect = json_encode($itemReferencesSelect);
set_option('item_references_select', $itemReferencesSelect);
$itemReferencesSecondLevel = !!intval(@$_POST["item_references_second_level"]);
set_option('item_references_second_level', $itemReferencesSecondLevel);
break;
}
}
/**
* Add item references select JavaScript code to editor / reference map code to item show
*/
public function hookAdminHead() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$module = $request->getModuleName();
if (is_null($module)) { $module = 'default'; }
$controller = $request->getControllerName();
$action = $request->getActionName();
if ($module === 'default' && $controller === 'items' && in_array($action, array('add', 'edit'))) {
$itemTypesList = array(
'-1' => '- ' . __('All') . ' -',
);
$itemTypesList += SELF::_getUsedItemTypes();
require dirname(__FILE__) . '/item-references-form.php';
}
if ($module === 'default' && $controller === 'items' && $action === 'show') {
queue_js_file('referencemap');
}
}
/**
* Get the list of used item types for select form.
*
* @return array
*/
protected function _getUsedItemTypes()
{
$db = get_db();
$itemTypesTable = $db->getTable('ItemType');
$itemTypesAlias = $itemTypesTable->getTableAlias();
$select = $itemTypesTable->getSelect()
->reset(Zend_Db_Select::COLUMNS)
->from(array(), array($itemTypesAlias . '.id', $itemTypesAlias . '.name'))
->joinInner(array('items' => $db->Item), "items.item_type_id = $itemTypesAlias.id", array())
->group($itemTypesAlias . '.id')
->order($itemTypesAlias . '.name ASC');
$permissions = new Omeka_Db_Select_PublicPermissions('Items');
$permissions->apply($select, 'items');
$itemTypes = $db->fetchPairs($select);
return $itemTypes;
}
/**
* Same as hookAdminHead -- but for public item show (edit code obsolete in this scenario)
*/
public function hookPublicHead() { SELF::hookAdminHead(); }
public function getTitleForId($itemId) {
$data = SELF::getDataForId($itemId);
return ($data ? $data["title"] : false);
}
/**
* Determine title for an item ID, numerical value if not present, or false if not accessible (public context)
*/
public function getDataForId($itemId) {
$itemId = intval($itemId);
$result = false;
if ($itemId) {
$item = get_record_by_id('Item', $itemId);
if ($item) {
$title = metadata($item, array('Dublin Core', 'Title'), array('no_filter' => true));
$title = ($title ? $title : "#$itemId" );
$details = metadata($item, array('Dublin Core', 'Description'), array('no_filter' => true));
$result = array( "title" => $title, "details" => $details );
}
}
return $result;
}
/**
* Filter to modify reference fields in item editor -- to show the item select popup, etc.
*/
public function filterElementInput($components, $args) {
$view = get_view();
$itemId = intval($args['value']);
$itemDetails = SELF::getDataForId($itemId);
$itemTitle = "";
if ($itemDetails !== false) { $itemTitle = $itemDetails["title"]; }
$components['input'] = "";
$components['input'] .= $view->formText(
$args['input_name_stem'] . '[text]'.'-title',
$itemTitle,
array('readonly' => 'true', 'style' => 'width: auto;', 'class' => 'itemReferencesField'),
null
);
$components['input'] .= $view->formHidden(
$args['input_name_stem'].'[text]',
$itemId,
array('readonly' => 'true', 'style' => 'width: auto;'),
null
);
$components['input'] .= " <button class='itemReferencesBtn'>".__("Select")."</button>";
$components['input'] .= "<button class='itemReferencesClearBtn'>".__("Clear")."</button>";
$components['html_checkbox'] = false;
return $components;
}
/**
* Check is wanton array is still undefined -- and, if not, prepare an empty one
*/
protected function _prepareArray(&$potentialArray) {
if (!isset($potentialArray)) { $potentialArray = array(); }
}
/**
* Filter to modify reference fields during rendering -- to display references item titles instead of IDs.
* PLUS: Collect geolocation data for combined reference maps / 2nd level refrence maps.
*/
public function filterDisplay($text, $args) {
$result = $text;
$itemId = intval($text); // this is our referenced item -- as stored in the element text
if ($itemId) {
$itemData = SELF::getDataForId($text);
if ($itemData === false) { return; } // if we can't access its title, it's probably not public
$itemTitle = $itemData["title"];
$itemDetails = $itemData["details"];
$referenceUrl = url('items/show/' . $text);
$result = __("Reference").": ".
"<a href='$referenceUrl'>$itemTitle</a>".
( !$itemDetails ? "" :
" <span class='itemRefDetailsLink'>(".__("Details").")</span>".
"<div class='itemRefDetailsText'>$itemDetails</div>"
);
$element_id = $args["element_text"]->element_id;
$db = get_db();
// collect the referenced item's geolocation only if the GeoLocation plugin is active
if (SELF::$_withGeoLoc) {
$sql = "SELECT * FROM $db->Locations WHERE item_id = $itemId";
$geoLoc = $db->fetchAll($sql); // just one result, i.e. one geoloc -- but fetchAll for "SELECT *"
if ($geoLoc) {
$geoLoc[0]["url"] = $referenceUrl;
$geoLoc[0]["geo_title"] = $itemTitle;
$geoLoc[0]["geo_title"] .= ( $geoLoc[0]["address"] ? " - " . $geoLoc[0]["address"] : "" );
if (!isset($geoLoc[0]["overlay"])) { $geoLoc[0]["overlay"] = -1; }
SELF::_prepareArray(SELF::$_geoLocations[$element_id]);
SELF::$_geoLocations[$element_id][$itemId] = $geoLoc[0];
/* * /
$lat = $geoLoc[0]["latitude"];
$lng = $geoLoc[0]["longitude"];
$zoom = $geoLoc[0]["zoom_level"];
$title = $geoLoc[0]["geo_title"];
$result .= "<br>(".__("Geolocation").": ";
$result .= "<a href='https://www.google.de/maps".
"/place/$lat+$lng".
"/@$lat,$lng,$zoom"."z' target='_blank'>";
$result .= $title;
$result .= "</a>";
$result .= ")";
/* */
}
}
if (SELF::$_withSecondLevel) {
// Let's find 2nd order references
$sql = "SELECT text FROM $db->element_texts".
" WHERE element_id = $element_id AND record_id = $itemId";
$secondaryItems = $db->fetchAll($sql);
$secondaryList = "";
foreach($secondaryItems as $secondaryItem) {
$secondaryItemId = intval($secondaryItem["text"]);
if ($secondaryItemId) {
$secondaryItemData = SELF::getDataForId($secondaryItemId);
if ($secondaryItemData !== false) {
$secondaryItemTitle = $secondaryItemData["title"];
$secondaryItemDetails = $secondaryItemData["details"];
$secondaryReferenceUrl = url('items/show/' . $secondaryItemId);
// $gMapsLink = "";
if (SELF::$_withGeoLoc) {
$sql = "SELECT * FROM $db->Locations WHERE item_id = $secondaryItemId";
$geoLoc = $db->fetchAll($sql); // just one result, i.e. one geoloc -- but fetchAll for "SELECT *"
if ($geoLoc) {
$geoLoc[0]["url"] = $secondaryReferenceUrl;
$geoLoc[0]["geo_title"] = $secondaryItemTitle;
$geoLoc[0]["geo_title"] .= ( $geoLoc[0]["address"] ? " - " . $geoLoc[0]["address"] : "" );
if (!isset($geoLoc[0]["overlay"])) { $geoLoc[0]["overlay"] = -1; }
SELF::_prepareArray(SELF::$_secondLevelGeoLocations[$element_id]);
SELF::_prepareArray(SELF::$_secondLevelGeoLocations[$element_id][$itemId]);
SELF::$_secondLevelGeoLocations[$element_id][$itemId][$secondaryItemId] = $geoLoc[0];
/* * /
$lat = $geoLoc[0]["latitude"];
$lng = $geoLoc[0]["longitude"];
$zoom = $geoLoc[0]["zoom_level"];
$title = $geoLoc[0]["geo_title"];
$gMapsLink .= "<br>(".__("Geolocation").": ";
$gMapsLink .= "<a href='https://www.google.de/maps".
"/place/$lat+$lng".
"/@$lat,$lng,$zoom"."z' target='_blank'>";
$gMapsLink .= $title;
$gMapsLink .= "</a>";
$gMapsLink .= ")";
/* */
}
}
$secondaryList .= "<li>".
__("Reference").": ".
"<a href='$secondaryReferenceUrl'>$secondaryItemTitle</a>".
( !$secondaryItemDetails ? "" :
" <span class='itemRefDetailsLink'>(".__("Details").")</span>".
"<div class='itemRefDetailsText'>$secondaryItemDetails</div>"
).
// $gMapsLink.
"</li>";
}
}
}
if ($secondaryList) { $result .= "<ul>$secondaryList</ul>\n"; }
}
}
return $result;
}
/**
* Additional item display: display reverse references and reference maps / 2nd level reference maps
*/
public function hookAdminItemsShow($args) {
echo '<link href="' . css_src('item-references-maps') . '" rel="stylesheet">';
if (SELF::$_enhancedGeoLog) {
$overlays = GeolocationPlugin::GeolocationConvertOverlayJsonForUse();
}
else { $overlays = null; }
SELF::_displaySelfReferences($args);
$js = "";
$js .= SELF::_displayReferenceMaps($args, $overlays);
$js .= SELF::_displaySecondLevelReferenceMaps($args, $overlays);
if ($js) {
if ($overlays) {
$js .= "var mapOverlays = ".$overlays["jsData"].";";
}
echo "<script type='text/javascript'>\n" . $js . "\n</script>";
}
}
/**
* Same as hookAdminItemsShow, but in public context
*/
public function hookPublicItemsShow($args) { SELF::hookAdminItemsShow($args); }
/**
* Display list of reverse references (1st level only)
*/
protected function _displaySelfReferences($args) {
$referenceElements = SELF::_retrieveReferenceElements();
if (!$referenceElements) { return; }
$referenceElementsStr = implode(",", $referenceElements);
$item = $args['item'];
$itemId = $item->id;
$db = get_db();
$sql = "
SELECT DISTINCT et.record_id, el.item_type_id, it.name
FROM `$db->ElementTexts` et
LEFT JOIN `$db->Items` el ON et.record_id = el.id
LEFT JOIN `$db->ItemTypes` it ON el.item_type_id = it.id
WHERE et.element_id in ($referenceElementsStr)
AND et.text = '$itemId'
ORDER BY it.name ASC, el.modified DESC
";
$referencers = $db->fetchAll($sql);
// echo "<pre>$sql - ".count($referencers)."\n" . print_r($referencers,true) . "</pre>";
$itemTypes = array();
foreach($referencers as $referencer) {
$typeName = ( @$referencer["name"] ? $referencer["name"] : __("[n/a]") );
$itemTypes[$referencer["item_type_id"]] = $typeName;
}
if ($referencers) {
echo "<h2>".__("Items Referencing this Item")."</h2>\n";
$refItemTypeShowHide = __("Show / Hide");
$refItemTypeShowHideAll = __("Show / Hide All");
?>
<script type='text/javascript'>
var refItemTypeShowHide = <?php echo json_encode($refItemTypeShowHide); ?>;
var refItemTypeShowHideAll = <?php echo json_encode($refItemTypeShowHideAll); ?>;
</script>
<?php
echo js_tag('item-references-item-type-toggle');
echo "<table id='refItemTypeTable'>\n";
$lastType = -1;
foreach($referencers as $referencer) {
if ($referencer["item_type_id"] != $lastType) {
$lastType = $referencer["item_type_id"];
echo "<tr class='refItemTypeHead' data-item-type='$lastType'>".
"<th colspan='3'>" . $itemTypes[$lastType] . "</th></tr>\n";
}
$referencerId = $referencer["record_id"];
$referencerUrl = url('items/show/' . $referencerId);
$title = $details = "";
if ($data = SELF::getDataForId($referencerId)) {
$title = $data["title"];
$details = $data["details"];
// echo "<pre>" . print_r($data,true) . "</pre>";
}
echo "<tr class='refItemTypeRow refItemType_".$lastType."'>";
echo "<td><a href='" . $referencerUrl . "'>#$referencerId</a></td>";
echo "<td><a href='" . $referencerUrl . "'>$title</a></td>";
echo "<td>".
( !$details ? "" :
"<span class='itemRefDetailsLink'>".__("Details")."</span>".
"<div class='itemRefDetailsText'>$details</div>"
).
"</td>";
echo "</tr>\n";
}
echo "</table>\n";
}
}
/**
* Determine whether this item contains reference element and thus potentially draws reference maps
*/
protected function _needsMaps($itemReferencesConfiguration) {
$result = false;
foreach($itemReferencesConfiguration as $itemReference) {
$result = ($itemReference[0] != 0);
if ($result) { break; }
}
return $result;
}
/**
* Display 1st level reference maps -- i.e. create HTML tags, push data into JavaScript to create Google Maps dynamically
*/
protected function _displayReferenceMaps($args, $overlays) {
$js = "";
$itemReferencesConfiguration = SELF::_retrieveReferenceElementConfiguration();
if (!SELF::_needsMaps($itemReferencesConfiguration)) { return; }
if ( (SELF::$_withGeoLoc) AND (SELF::$_geoLocations) ) {
$output = "<h2>".__("Geolocations of References Items")."</h2>\n";
$itemReferencesMapHeight = intval(get_option('item_references_map_height'));
if (!$itemReferencesMapHeight) { $itemReferencesMapHeight = ITEM_REFERENCES_MAP_HEIGHT_DEFAULT; }
$mapsData = array();
$db = get_db();
foreach(SELF::$_geoLocations as $elementId => $referenceMap) {
if ( ($referenceMap) and ($itemReferencesConfiguration[$elementId][0]>0) ) {
$sql = "SELECT name FROM $db->Elements WHERE id = $elementId";
$elementName = $db->fetchOne($sql);
$output .= "<h4>$elementName</h4>\n";
$isLineReference = intval($itemReferencesConfiguration[$elementId][0]==2);
$moreThanOnePin = (count($referenceMap) > 1);
$data = array(
"mapId" => "map".$elementId,
"coords" => array(),
"line" => $isLineReference,
"color" => intval($itemReferencesConfiguration[$elementId][1]),
);
$reqOverlays = array();
$lineDistances = array();
$lastPin = null;
$distanceArrays = array();
foreach($referenceMap as $pinIndex => $pin) {
if ($pin) {
$data["coords"][] = array( // see below (*)
"title" => $pin["geo_title"],
"lat" => $pin["latitude"],
"lng" => $pin["longitude"],
"url" => $pin["url"],
"ovl" => $pin["overlay"],
"zl" => $pin["zoom_level"],
);
if ($moreThanOnePin) {
if ($isLineReference) { // Line references: calculate distances from stop to stop
if ($lastPin) { // Have we already seen the stop before this one?
$lineDistances[] = array(
"fromTitle" =>
"<a href='".$lastPin["url"]."'>" . $lastPin["geo_title"] . "</a>",
"toTitle" =>
"<a href='".$pin["url"]."'>" . $pin["geo_title"] . "</a>",
"linDistance" => SELF::_km_format(
SELF::_getDistanceFromLatLonInKm(
$pin["latitude"], $pin["longitude"],
$lastPin["latitude"], $lastPin["longitude"]
)
)
);
}
$lastPin = $pin;
}
else { // Not line reference -- but location reference
// in this case calculate distances from here to everywhere else
$distanceArray = array();
foreach($referenceMap as $otherPinIndex => $otherPin) {
if ($pinIndex != $otherPinIndex) {
$distanceArray[$otherPin["geo_title"]] = array(
"fromTitle" =>
"<a href='".$pin["url"]."'>" . $pin["geo_title"] . "</a>",
"toTitle" =>
"<a href='".$otherPin["url"]."'>" . $otherPin["geo_title"] . "</a>",
"linDistance" => SELF::_km_format(
SELF::_getDistanceFromLatLonInKm(
$pin["latitude"], $pin["longitude"],
$otherPin["latitude"], $otherPin["longitude"]
)
)
);
}
}
ksort($distanceArray);
$distanceArrays[ $pin["geo_title"] ] = $distanceArray;
}
}
if (isset($reqOverlays[$pin["overlay"]])) {
$reqOverlays[$pin["overlay"]]++;
}
else {
$reqOverlays[$pin["overlay"]] = 1;
}
}
}
ksort($distanceArrays);
$ovlDefault = -1;
if (count($reqOverlays) == 1) { $ovlDefault = array_keys($reqOverlays)[0]; }
$distHtml = "";
if ($moreThanOnePin) {
$distHtml .= "<h5>" . __("Linear Distances") . "</h5>\n";
$classInfix = ( $lineDistances ? ""
: "class='refDistanceTable refDistanceElement_".$elementId."' data-element='".$elementId."'"
);
$distHtml .= "<table $classInfix>";
$distHtml .= "<thead><tr>";
$distHtml .= "<th>" . __("Start Point") . "</th>";
$distHtml .= "<th>" . __("End Point") . "</th>";
$distHtml .= "<th style='text-align:right;'>" . __("Linear Distance") . "</th>";
$distHtml .= "</tr></thead>\n";
$distHtml .= "<tbody>\n";
if ($lineDistances) {
foreach($lineDistances as $lineDistance) {
$distHtml .= "<tr>";
$distHtml .= "<td>" . $lineDistance["fromTitle"] . "</td>";
$distHtml .= "<td>" . $lineDistance["toTitle"] . "</td>";
$distHtml .= "<td style='text-align:right;'>" . $lineDistance["linDistance"] . "</td>";
$distHtml .= "</tr>\n";
}
}
else {
$cnt = 0;
foreach($distanceArrays as $fromTitle => $distanceArray) {
$cnt++;
$distHtml .= "<tr class='refDistanceHead' data-block='".$elementId."_".$cnt."'>".
"<th colspan='3'>$fromTitle</th>".
"</tr>\n";
$first = true;
$rowSpan = count($distanceArray);
foreach($distanceArray as $distance) {
$distHtml .= "<tr class='refDistanceRow refDistanceBlock_".$elementId."_".$cnt."'>";
if ($first) {
$distHtml .= "<td rowspan='$rowSpan'>" . $distance["fromTitle"] . "</td>";
$first = false;
}
$distHtml .= "<td>" . $distance["toTitle"] . "</td>";
$distHtml .= "<td style='text-align:right;'>" . $distance["linDistance"] . "</td>";
$distHtml .= "</tr>\n";
}
}
}
$distHtml .= "</tbody>\n";
$distHtml .= "</table>\n";
}
$output .= "<div id='".$data["mapId"]."' style='height:".$itemReferencesMapHeight."px; width:100%;'></div>\n";
$curCount = count($mapsData);
if ($overlays) {
$output .= '<div class="reference_ovl_options"><strong>' . __("Select Map Overlay:") . '</strong> '.
get_view()->formSelect(
$data["mapId"]."_ovl",
$ovlDefault,
array(
"class" => "refMapOvlSel",
"data-map-arr" => $curCount, // latest added IDX - see above (*)
),
$overlays["jsSelect"]
).
"<span class='refMapOvlSlider' id='".$data["mapId"]."_slider' data-map-arr='".$curCount."'></span>".
$distHtml.
"</div>";
}
$mapsData[] = $data;
}
}
if ($mapsData) {
echo $output;
$js .= "var mapsData=".json_encode($mapsData).";\n";
$refItemTypeShowHide = __("Show / Hide");
$refItemTypeShowHideAll = __("Show / Hide All");
$js .= "var refDistancesShowHide = ".json_encode($refItemTypeShowHide).";\n";
$js .= "var refDistancesShowHideAll = ".json_encode($refItemTypeShowHideAll).";\n";
echo js_tag('item-references-distances-toggle');
}
}
return $js;
}
/**
* Helper function to encapsulate the number format for km measurements which
* fall back to one decimal digit below 5 km and to meters below 1 km etc.
*/
protected function _km_format($km) {
$result = round($km);
if ($km>5) { $result = number_format($km, 0, ",", ".") . " km"; }
else if ($km>1) { $result = number_format($km, 1, ",", ".") . " km"; }
else {
$m = round($km * 1000);
if ($m>500) { $m = round($m / 100) * 100; }
else if ($m>100) { $m = round($m / 50) * 50; }
else if ($m>50) { $m = round($m / 10) * 10; }
else if ($m>20) { $m = round($m / 5) * 5; }
$result = number_format($m, 0, ",", ".") . " m";
}
return $result;
}
/**
* Helper function to caculate linear distances (i.e. air distances) between two lat/lng tuples
* ... adapted from http://stackoverflow.com/a/27943
*/
protected function _getDistanceFromLatLonInKm($lat1, $lon1, $lat2,$lon2) {
$R = 6371; // Radius of the earth in km
$dLat = deg2rad($lat2-$lat1); // deg2rad below
$dLon = deg2rad($lon2-$lon1);
$a =
sin($dLat/2) * sin($dLat/2) +
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
sin($dLon/2) * sin($dLon/2)
;
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$d = $R * $c; // Distance in km
return $d;
}
/**
* Display 2nd level reference maps -- i.e. create HTML tags, push data into JavaScript to create Google Maps dynamically
*/
protected function _displaySecondLevelReferenceMaps($args, $overlays) {
$js = "";
$itemReferencesConfiguration = SELF::_retrieveReferenceElementConfiguration();
if (!SELF::_needsMaps($itemReferencesConfiguration)) { return; }
if ( (SELF::$_withGeoLoc) AND (SELF::$_secondLevelGeoLocations) ) {
$output = "<h2>".__("Geolocations of Second Level References Items")."</h2>\n";
$itemReferencesMapHeight = intval(get_option('item_references_map_height'));
if (!$itemReferencesMapHeight) { $itemReferencesMapHeight = ITEM_REFERENCES_MAP_HEIGHT_DEFAULT; }
$secondLevelMapsData = array();
$db = get_db();
foreach(SELF::$_secondLevelGeoLocations as $elementId => $firstLevelRef) {
if ( ($firstLevelRef) and ($itemReferencesConfiguration[$elementId][0]>0) ) {
$sql = "SELECT name FROM $db->Elements WHERE id = $elementId";
$elementName = $db->fetchOne($sql);
$output .= "<h4>$elementName</h4>\n";
$data = array(
"mapId" => "mapTwo".$elementId,
"line" => intval($itemReferencesConfiguration[$elementId][0]==2),
"refMaps" => array(),
);
$reqOverlays = array();
foreach($firstLevelRef as $firstLevelRefId => $referenceMap) {
$firstLevelRefData = SELF::getDataForId($firstLevelRefId);
if ($firstLevelRefData !== false) {
$firstLevelRefTitle = $firstLevelRefData["title"];
$firstLevelRefUrl = url('items/show/' . $firstLevelRefId);
$data["refMaps"][$firstLevelRefId] = array(
"title" => $firstLevelRefTitle,
"url" => $firstLevelRefUrl,
"coords" => array(),
);
foreach($referenceMap as $secondLevelRefId => $pin) {
if ($pin) {
$data["refMaps"][$firstLevelRefId]["coords"][] = array( // see below (*)
"title" => $pin["geo_title"],
"lat" => $pin["latitude"],
"lng" => $pin["longitude"],
"url" => $pin["url"],
"ovl" => $pin["overlay"],
"zl" => $pin["zoom_level"],
);
if (isset($reqOverlays[$pin["overlay"]])) {
$reqOverlays[$pin["overlay"]]++;
}
else {
$reqOverlays[$pin["overlay"]] = 1;
}
} # if ($pin)
} # foreach($referenceMap
} # if ($firstLevelRefTitle
} # foreach($firstLevelRef
$ovlDefault = -1;
if (count($reqOverlays) == 1) { $ovlDefault = array_keys($reqOverlays)[0]; }
$output .= "<div id='".$data["mapId"]."' style='height:".$itemReferencesMapHeight."px; width:100%;'></div>\n";
$curSecondCount = count($secondLevelMapsData);
if ($overlays) {
$output .= '<div class="reference_ovl_options"><strong>'.__("Select Map Overlay:").'</strong> '.
get_view()->formSelect(
$data["mapId"]."_ovl",
$ovlDefault,
array(
"class" => "refMapOvlSel",
"data-map-two-arr" => $curSecondCount, // latest added IDX - see above (*)
),
$overlays["jsSelect"]
).
"<span class='refMapOvlSlider' id='".$data["mapId"]."_slider' data-map-two-arr='".$curSecondCount."'></span>".
"</div>";
}
$output .= "<div id='".$data["mapId"]."_legend' class='itemRefTwoMapLegend'></div>";