You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.3 KiB

  1. <?php
  2. $wikidataCache = array();
  3. function wikidataLoad ($id) {
  4. global $wikidataCache;
  5. if (!array_key_exists($id, $wikidataCache)) {
  6. $body = file_get_contents("https://www.wikidata.org/wiki/Special:EntityData/{$id}.json");
  7. $body = $body ? json_decode($body, true) : false;
  8. if (!array_key_exists('entities', $body) || !array_key_exists($id, $body['entities'])) {
  9. return false;
  10. }
  11. $wikidataCache[$id] = $body['entities'][$id];
  12. }
  13. return $wikidataCache[$id];
  14. }
  15. function wikidataGetLabel ($id, $lang) {
  16. $data = wikidataLoad($id);
  17. if (array_key_exists($lang, $data['labels'])) {
  18. return $data['labels'][$lang]['value'];
  19. }
  20. elseif (array_key_exists('en', $data['labels'])) {
  21. return $data['labels']['en']['value'];
  22. }
  23. elseif (!sizeof($data['labels'])) {
  24. return $id;
  25. }
  26. else {
  27. return array_values($data['labels'])[0]['value'];
  28. }
  29. }
  30. function wikidataGetValues ($id, $property) {
  31. $data = wikidataLoad($id);
  32. if (!array_key_exists($property, $data['claims'])) {
  33. return [];
  34. }
  35. return array_map(
  36. function ($el) {
  37. return $el['mainsnak']['datavalue']['value'];
  38. },
  39. $data['claims'][$property]
  40. );
  41. }
  42. function wikidataFormatDate($value, $maxPrecision = 13) {
  43. $v = new DateTime($value['time']);
  44. $p = min($maxPrecision, $value['precision']);
  45. if ($p < 9) {
  46. } else {
  47. $formats = [
  48. 9 => 'Y',
  49. 10 => 'M Y',
  50. 11 => 'j. M Y',
  51. 12 => 'j. M Y - G:00',
  52. 13 => 'j. M Y - G:i',
  53. 14 => 'j. M Y - G:i:s',
  54. ];
  55. return $v->format($formats[$p]);
  56. }
  57. }
  58. function wikidataFormat ($id, $lang) {
  59. $ret = '<b>' . wikidataGetLabel($id, $lang) . '</b>';
  60. $birthDate = wikidataGetValues($id, 'P569');
  61. $deathDate = wikidataGetValues($id, 'P570');
  62. if (sizeof($birthDate) && sizeof($deathDate)) {
  63. $ret .= ' (' . wikidataFormatDate($birthDate[0], 11) . ' — ' . wikidataFormatDate($deathDate[0], 11) . ')';
  64. }
  65. elseif (sizeof($birthDate)) {
  66. $ret .= ' (* ' . wikidataFormatDate($birthDate[0], 11) . ')';
  67. }
  68. elseif (sizeof($deathDate)) {
  69. $ret .= ' († ' . wikidataFormatDate($birthDate[0], 11) . ')';
  70. }
  71. $occupation = wikidataGetValues($id, 'P106');
  72. if (sizeof($occupation)) {
  73. $ret .= ', ' . implode(', ', array_map(
  74. function ($value) use ($lang) {
  75. return wikidataGetLabel($value['id'], $lang);
  76. },
  77. $occupation
  78. ));
  79. }
  80. return $ret;
  81. }