You are here

function piwik_stats_get_xml_data in Piwik Statistic Integration 7.2

Get statistical XML data (either by fresh request or cached).

Parameters

array $field: Array of the field config.

Return value

object A SimpleXMLElement on success, FALSE otherwise.

1 call to piwik_stats_get_xml_data()
piwik_stats_process_queue_item in ./piwik_stats.module
Processes a dataset for filling a field.

File

./piwik_stats.module, line 607
Integrates piwik statistics as entity fields.

Code

function piwik_stats_get_xml_data($field) {

  // Static caching for SimpleXMLElement data.
  // We cache by period as it is currently the only thing that
  // differs between each field configuration. If this gets more
  // complex later we should use the field name as cache key.
  static $xml;
  if (empty($xml)) {
    $xml = array();
  }

  // Check whether we already got this XML object in cache.
  if (!isset($xml[$field['settings']['period']])) {

    // Check for cached request result data (SimpleXMLElement cannot be cached).
    $cache = cache_get('piwik_stats:xml:' . $field['settings']['period'], 'cache_piwik_stats');
    if (!empty($cache) && $cache->created > REQUEST_TIME - 24 * 60 * 60) {
      $result = $cache;
    }
    else {
      $url = variable_get('piwik_url_http');
      $token = variable_get('piwik_stats_token_auth');
      $site_id = variable_get('piwik_site_id');

      // Check if connection credentials are provided.
      if (!isset($url, $token, $site_id)) {
        return FALSE;
      }

      // Request piwik XML data.
      $result = piwik_stats_api_request($url, $token, 'Actions.getPageUrls', $site_id, $field['settings']['period']);

      // Check HTTP status code of response.
      if ($result->code != 200) {
        $error = isset($result->error) ? "{$result->code}: {$result->error}" : $result->code;
        watchdog('piwik_stats', 'Requesting Piwik Statistics failed: HTTP returned: @error.', array(
          '@error' => $error,
        ), WATCHDOG_ERROR);
        return FALSE;
      }
      if ($result->headers['content-type'] != 'text/xml; charset=utf-8') {
        watchdog('piwik_stats', 'Requesting Piwik Statistics does not return expected data format.', array(), WATCHDOG_ERROR);
        return FALSE;
      }
      cache_set('piwik_stats:xml:' . $field['settings']['period'], $result->data, 'cache_piwik_stats');
    }

    // Parse XML data.
    $xml[$field['settings']['period']] = new SimpleXMLElement($result->data);

    // Be shure that there is really some data to work with.
    if (isset($xml[$field['settings']['period']]->error)) {
      watchdog('piwik_stats', 'Requesting Piwik Statistics failed: Could not parse XML.', array(), WATCHDOG_ERROR);
      return FAlSE;
    }
  }
  return $xml[$field['settings']['period']];
}