summaryrefslogtreecommitdiffstats
path: root/ldt.api.php
blob: 0b63ad9e92531931278e648f3be469addf61eb07 (plain)
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
<?php
/**
 * @file
 * Principal API for the Linked Data Tools module.
 *
 * @copyright Copyright(c) 2012 Christopher Skene
 * @license GPL v2 http://www.fsf.org/licensing/licenses/gpl.html
 * @author Chris Skene chris at xtfer dot com
 *
 * Functions in this file should be considered the main API, whereas functions
 * in the module file are those required for these to function effectively.
 */

/**
 * Invoke a new linked data tool from a plugin.
 *
 * @param string $name
 *   Name of the wrapper.
 *
 * @return \Drupal\ldt\Library\LibraryWrapperInterface
 *   A library wrapper.
 */
function ldt_tool($name) {
  $wrappers = ldt_get_library_wrappers();
  if (array_key_exists($name, $wrappers)) {
    if (class_exists($wrappers[$name]['class'])) {
      return new $wrappers[$name]['class']();
    }
  }
}

/**
 * Load a linked data tool and load RDF data into it.
 *
 * @param string $tool
 *   Machine name of the RDF tool to use (e.g. 'arc2' or 'easyrdf')
 * @param string $data
 *   Data to load into the graph
 * @param string $uri
 *   A URI to attach to the graph.
 * @param string $format
 *   The data format.
 *
 * @return \Drupal\ldt\Library\LibraryWrapperInterface
 *   The graph object, or false.
 */
function ldt_graph_data($tool, $data, $uri = NULL, $format = 'rdf+xml') {
  try {
    $tool = ldt_tool($tool);

    $tool->setGraphData($data, $format);

    if (!empty($uri)) {
      $tool->setUri($uri);
    }

    return $tool;
  }
  catch (\Exception $e) {
    drupal_set_message('Failed to load graph (' . $e->getMessage() . ')', 'error');
  }

  return FALSE;
}

/**
 * Load a linked data tool and load RDF data into it from a URI.
 *
 * This will load cached data, if available.
 *
 * @param string $uri
 *   A URI.
 * @param string $format
 *   (optional) An optional ldt data format. Defaults to rdfxml.
 * @param string $tool
 *   (optional) Machine name of the RDF tool to use (defaults to 'easyrdf')
 *
 * @return \Drupal\ldt\Library\LibraryWrapperInterface|bool
 *   The graph object, or false.
 */
function ldt_graph_uri($uri, $format = LDT_DEFAULT_FORMAT, $tool = LDT_DEFAULT_LIBRARY) {
  try {
    $tool = ldt_tool($tool);

    $data = ldt_fetch_rdf($uri);

    // Data may already by loaded as an array...
    if (is_array($data)) {
      $format = 'php';
    }

    if (!empty($data)) {
      $tool->setGraphData($data, $format);
      $tool->setUri($uri);

      $tool->parseGraphData();

      return $tool;
    }
  }
  catch (\Exception $e) {
    drupal_set_message('Failed to load graph. More information can be found in the log.', 'error');
    watchdog_exception('ldt', $e, '"%message", in %file:%line', array(
      '%message' => $e->getMessage(),
      '%file' => $e->getFile(),
      '%line' => $e->getLine(),
    ));
  }

  return FALSE;
}

/**
 * Helper to make a request for RDF data.
 *
 * This first checks the local cache, then it will request the data using
 * Guzzle. If Guzzle is not available, it will fallback on
 * drupal_http_request(). Guzzle itself is expected to be autoloaded, so it can
 * be provided via http://drupal.org/project/guzzle or any other mechanism
 * which supports autoloading.
 *
 * @param string $uri
 *   The URI to request data from
 * @param string $format
 *   (optional) The data format, as defined by hook_ldt_data_formats(). Defaults
 *   to 'rdf+xml' (RDF XML).
 * @param string $tool_type
 *   (optional) The tool to use. Defaults to EasyRdf
 * @param bool $flush
 *   (optional) If TRUE, the resource will be
 *
 * @return string
 *   The data returned from the request..
 */
function ldt_fetch_rdf($uri, $format = LDT_DEFAULT_FORMAT, $tool_type = LDT_DEFAULT_LIBRARY, $flush = FALSE) {
  $data = FALSE;

  // Check if the resource is cached first.
  if ($flush == FALSE) {
    $tool = ldt_tool($tool_type);
    $cached_resource = $tool->loadResource($uri);
    if (!empty($cached_resource) && is_array($cached_resource)) {
      return $cached_resource;
    }
  }

  // Check formats.
  $format = ldt_data_format($format);
  if (empty($format)) {
    watchdog('ldt', 'Invalid data format');

    return FALSE;
  }

  // Use Guzzle if it exists.
  if (class_exists('Guzzle\Http\Client')) {
    try {
      $client = new \Guzzle\Http\Client();
      $request = $client->get($uri);
      if (array_key_exists('accept', $format) && is_array($format['accept']) && !empty($format['accept'])) {
        foreach ($format['accept'] as $accept) {
          $request->addHeader('Accept', $accept);
        }
      }
      $response = $request->send();
      if ($response->isSuccessful()) {
        $data = $response->getBody(TRUE);
      }
      else {
        // Probably an invalid request.
        ldt_log_http_error($response->getStatusCode(), 'Request failed');
      }
    }
    catch(\Guzzle\Http\Exception\BadResponseException $e) {
      $response = $e->getResponse();
      if (isset($response) && is_object($response) && $response instanceof \Guzzle\Http\Message\Response) {
        $status = $response->getStatusCode();
        $message = $response->getReasonPhrase();
      }
      else {
        $status = 0;
        $message = 'Unknown error (this may mean the endpoint is missing or not responding)  ';
      }
      ldt_log_http_error($status, $message);
    }
  }
  else {
    // Use drupal_http_request as a fallback.
    $vars = array(
      'headers' => array(),
    );
    if (array_key_exists('accept', $format) && is_array($format['accept']) && !empty($format['accept'])) {
      $accept_headers = array();
      foreach ($format['accept'] as $accept) {
        $accept_headers[] = $accept;
      }
      $vars['headers']['Accept'] = $accept_headers;
    }
    $result = drupal_http_request($uri, $vars);
    if (isset($result->data)) {

      $data = $result->data;
    }
  }

  return $data;
}

/**
 * Extract resources specified as SKOS 'narrower'.
 *
 * @param \Drupal\ldt\Library\LibraryWrapperInterface $tool
 *   An EasyRdf Graph object.
 *
 * @return array
 *   An array of resource objects.
 */
function ldt_extract_skos_narrower($tool) {

  $namespaces = $tool->getNamespaces();
  if (!array_key_exists('skos', $namespaces)) {
    $tool->addNamespace('skos', 'http://www.w3.org/2004/02/skos/core#');
  }

  $resources = $tool->extractResources('skos:narrower');
  $results = $tool->fetchResources($resources);

  return $results;
}

/**
 * Extract resources specified as SKOS 'broader'.
 *
 * @param string $uri
 *   The URI to import from.
 * @param string $tool_plugin
 *   Name of the plugin to use.
 * @param string $format
 *   The data format.
 *
 * @return array
 *   An array of resource objects.
 */
function ldt_extract_skos_broader($uri, $tool_plugin = LDT_DEFAULT_LIBRARY, $format = LDT_DEFAULT_FORMAT) {

  $tool = ldt_graph_uri($uri, LDT_DEFAULT_FORMAT, $tool_plugin);
  $namespaces = $tool->getNamespaces();
  if (!array_key_exists('skos', $namespaces)) {
    $tool->addNamespace('skos', 'http://www.w3.org/2004/02/skos/core#');
  }

  $resources = $tool->extractResources('skos:broader');

  $tool = ldt_tool($tool_plugin);
  $namespaces = $tool->getNamespaces();
  if (!array_key_exists('skos', $namespaces)) {
    $tool->addNamespace('skos', 'http://www.w3.org/2004/02/skos/core#');
  }

  $results = $tool->fetchResources($resources);

  return $results;
}

/**
 * Extract resources specified as Dublin Core Terms 'subject'.
 *
 * @param string $uri
 *   The URI to import from.
 * @param string $tool_plugin
 *   Name of the plugin to use.
 * @param string $format
 *   The data format.
 *
 * @return array
 *   An array of resource objects.
 */
function ldt_extract_dc_subjects($uri, $tool_plugin = LDT_DEFAULT_LIBRARY, $format = LDT_DEFAULT_FORMAT) {

  $tool = ldt_graph_uri($uri, $format, $tool_plugin);
  $namespaces = $tool->getNamespaces();
  if (!array_key_exists('dcterms', $namespaces)) {
    $tool->addNamespace('dcterms', 'http://purl.org/dc/terms/');
  }

  $resources = $tool->extractResources('dcterms:subject');

  $tool = ldt_tool($tool_plugin);
  $namespaces = $tool->getNamespaces();
  if (!array_key_exists('dcterms', $namespaces)) {
    $tool->addNamespace('dcterms', 'http://purl.org/dc/terms/');
  }

  $results = $tool->fetchResources($resources);

  return $results;
}