media.xml.inc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * @file
  4. * XML data retrieval and storage API for Media.
  5. */
  6. /**
  7. * A wrapper around simplexml to retrieve a given XML file.
  8. *
  9. * @param $url
  10. * The URL to the XML to retrieve.
  11. * @param $display_errors
  12. * Optional; if TRUE, then we'll display errors to the end user. They'll be
  13. * logged to the watchdog in any case.
  14. * @param $refresh
  15. * Optional; if TRUE, then we'll force a new load of the XML. Otherwise,
  16. * a cached version will be retrieved if possible.
  17. * @return
  18. * A fully populated object, or FALSE on an error.
  19. */
  20. function _media_retrieve_xml($url, $display_errors = FALSE, $refresh = FALSE) {
  21. $xmls = &drupal_static(__FUNCTION__, array());
  22. // Return our cached XML if allowed, and it exists.
  23. if (!$refresh && isset($xmls[$url])) {
  24. return $xmls[$url];
  25. }
  26. elseif (!$refresh && $cache = cache_get('media:xml:' . $url, 'cache_media_xml')) {
  27. $xmls[$url] = $cache->data;
  28. return $xmls[$url];
  29. }
  30. // Enable user error handling.
  31. libxml_use_internal_errors(TRUE);
  32. // Load the document
  33. $xml = simplexml_load_file($url);
  34. if (!$xml) {
  35. foreach (libxml_get_errors() as $error) {
  36. $params = array('%url' => $url, '%error' => $error->message);
  37. // Handle errors here.
  38. if ($display_errors) {
  39. drupal_set_message(t('Error retrieving XML from %url: %error', $params), 'error');
  40. }
  41. watchdog('media', 'Error retrieving XML from %url: %error', $params, WATCHDOG_WARNING);
  42. }
  43. // Clear our error cache.
  44. libxml_clear_errors();
  45. // Set the static cache, but not Drupal's cache, so we can attempt to
  46. // retrieve the file another time if possible.
  47. $xmls[$url] = FALSE;
  48. }
  49. else {
  50. $xmls[$url] = _media_unserialize_xml($xml);
  51. cache_set('media:xml:' . $url, $xmls[$url], 'cache_media_xml', media_variable_get('xml_cache_expire', 3600));
  52. }
  53. return $xmls[$url];
  54. }
  55. /**
  56. * Recursively converts a SimpleXMLElement object into an array.
  57. * @param $xml
  58. * The original XML object.
  59. */
  60. function _media_unserialize_xml($xml) {
  61. if ($xml instanceof SimpleXMLElement) {
  62. $xml = (array) $xml;
  63. }
  64. if (is_array($xml)) {
  65. foreach ($xml as $key => $item) {
  66. $xml[$key] = _media_unserialize_xml($item);
  67. }
  68. }
  69. return $xml;
  70. }