audiofix_ror.module 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. const PARAGRAPH = 'audio';
  3. const LINKFIELD = 'field_audio_link';
  4. function isArchive(string $url): bool {
  5. $pos = strpos($url, "archive.org/");
  6. if($pos === FALSE) {
  7. return FALSE;
  8. }
  9. return TRUE;
  10. }
  11. function normalizeArchive(string $url) {
  12. //assume il link sia di archive
  13. if(strpos($url, "https://archive.org/download") !== FALSE) {
  14. return $url;
  15. }
  16. if(strpos($url, "https://archive.org/details") !== FALSE) {
  17. // aagh qui in teoria non c'e' nulla da fare a meno che non guardiamo sul sito
  18. return $url;
  19. }
  20. // https://ia123456.us.archive.org/30/items/Bucket/filename.ogg
  21. $parts = explode("/", $url);
  22. $bucket = $parts[count($parts)-2];
  23. $fname = $parts[count($parts)-1];
  24. return "https://archive.org/download/" . $bucket . "/" . $fname;
  25. }
  26. /*
  27. * Implements hook_ENTITY_TYPE_presave
  28. */
  29. function audiofix_ror_paragraph_presave(Drupal\Core\Entity\EntityInterface $entity) {
  30. // per i paragraph, getType() === bundle().
  31. if($entity->bundle() !== PARAGRAPH) { // audio e' il nome del nostro paragraph type
  32. return;
  33. }
  34. // campi utili: field_audio_link e field_durata
  35. $link = $entity->get(LINKFIELD)->getValue();
  36. if(count($link) == 0) { return; }
  37. $link = $link[0]['uri'];
  38. if(is_string($link) && isArchive($link)) {
  39. $norm = normalizeArchive($link);
  40. if($norm !== $link) {
  41. \Drupal::logger('audiofix_ror')->notice('Aggiornato da :old a :new', array(":old" => $link, ":new" => $norm));
  42. $entity->set(LINKFIELD, $norm);
  43. }
  44. }
  45. }