Fix an issue where utility skos and dc functions would fail due to a signature change.
[project/ldt.git] / ldt.api.php
1 <?php
2 /**
3 * @file
4 * Principal API for the Linked Data Tools module.
5 *
6 * @copyright Copyright(c) 2012 Christopher Skene
7 * @license GPL v2 http://www.fsf.org/licensing/licenses/gpl.html
8 * @author Chris Skene chris at xtfer dot com
9 *
10 * Functions in this file should be considered the main API, whereas functions
11 * in the module file are those required for these to function effectively.
12 */
13
14 /**
15 * Invoke a new linked data tool from a plugin.
16 *
17 * @param string $name
18 * Name of the wrapper.
19 *
20 * @return \Drupal\ldt\Library\LibraryWrapperInterface
21 * A library wrapper.
22 */
23 function ldt_tool($name) {
24 $wrappers = ldt_get_library_wrappers();
25 if (array_key_exists($name, $wrappers)) {
26 if (class_exists($wrappers[$name]['class'])) {
27 return new $wrappers[$name]['class']();
28 }
29 }
30 }
31
32 /**
33 * Load a linked data tool and load RDF data into it.
34 *
35 * @param string $tool
36 * Machine name of the RDF tool to use (e.g. 'arc2' or 'easyrdf')
37 * @param string $data
38 * Data to load into the graph
39 * @param string $uri
40 * A URI to attach to the graph.
41 * @param string $format
42 * The data format.
43 *
44 * @return \Drupal\ldt\Library\LibraryWrapperInterface
45 * The graph object, or false.
46 */
47 function ldt_graph_data($tool, $data, $uri = NULL, $format = 'rdf+xml') {
48 try {
49 $tool = ldt_tool($tool);
50
51 $tool->setGraphData($data, $format);
52
53 if (!empty($uri)) {
54 $tool->setUri($uri);
55 }
56
57 return $tool;
58 }
59 catch (\Exception $e) {
60 drupal_set_message('Failed to load graph (' . $e->getMessage() . ')', 'error');
61 }
62
63 return FALSE;
64 }
65
66 /**
67 * Load a linked data tool and load RDF data into it from a URI.
68 *
69 * This will load cached data, if available.
70 *
71 * @param string $uri
72 * A URI.
73 * @param string $format
74 * (optional) An optional ldt data format. Defaults to rdfxml.
75 * @param string $tool
76 * (optional) Machine name of the RDF tool to use (defaults to 'easyrdf')
77 *
78 * @return \Drupal\ldt\Library\LibraryWrapperInterface|bool
79 * The graph object, or false.
80 */
81 function ldt_graph_uri($uri, $format = LDT_DEFAULT_FORMAT, $tool = LDT_DEFAULT_LIBRARY) {
82 try {
83 $tool = ldt_tool($tool);
84
85 $data = ldt_fetch_rdf($uri);
86
87 // Data may already by loaded as an array...
88 if (is_array($data)) {
89 $format = 'php';
90 }
91
92 if (!empty($data)) {
93 $tool->setGraphData($data, $format);
94 $tool->setUri($uri);
95
96 $tool->parseGraphData();
97
98 return $tool;
99 }
100 }
101 catch (\Exception $e) {
102 drupal_set_message('Failed to load graph. More information can be found in the log.', 'error');
103 watchdog_exception('ldt', $e, '"%message", in %file:%line', array(
104 '%message' => $e->getMessage(),
105 '%file' => $e->getFile(),
106 '%line' => $e->getLine(),
107 ));
108 }
109
110 return FALSE;
111 }
112
113 /**
114 * Helper to make a request for RDF data.
115 *
116 * This first checks the local cache, then it will request the data using
117 * Guzzle. If Guzzle is not available, it will fallback on
118 * drupal_http_request(). Guzzle itself is expected to be autoloaded, so it can
119 * be provided via http://drupal.org/project/guzzle or any other mechanism
120 * which supports autoloading.
121 *
122 * @param string $uri
123 * The URI to request data from
124 * @param string $format
125 * (optional) The data format, as defined by hook_ldt_data_formats(). Defaults
126 * to 'rdf+xml' (RDF XML).
127 * @param string $tool_type
128 * (optional) The tool to use. Defaults to EasyRdf
129 * @param bool $flush
130 * (optional) If TRUE, the resource will be
131 *
132 * @return string
133 * The data returned from the request..
134 */
135 function ldt_fetch_rdf($uri, $format = LDT_DEFAULT_FORMAT, $tool_type = LDT_DEFAULT_LIBRARY, $flush = FALSE) {
136 $data = FALSE;
137
138 // Check if the resource is cached first.
139 if ($flush == FALSE) {
140 $tool = ldt_tool($tool_type);
141 $cached_resource = $tool->loadResource($uri);
142 if (!empty($cached_resource) && is_array($cached_resource)) {
143 return $cached_resource;
144 }
145 }
146
147 // Check formats.
148 $format = ldt_data_format($format);
149 if (empty($format)) {
150 watchdog('ldt', 'Invalid data format');
151
152 return FALSE;
153 }
154
155 // Use Guzzle if it exists.
156 if (class_exists('Guzzle\Http\Client')) {
157 try {
158 $client = new \Guzzle\Http\Client();
159 $request = $client->get($uri);
160 if (array_key_exists('accept', $format) && is_array($format['accept']) && !empty($format['accept'])) {
161 foreach ($format['accept'] as $accept) {
162 $request->addHeader('Accept', $accept);
163 }
164 }
165 $response = $request->send();
166 if ($response->isSuccessful()) {
167 $data = $response->getBody(TRUE);
168 }
169 else {
170 // Probably an invalid request.
171 ldt_log_http_error($response->getStatusCode(), 'Request failed');
172 }
173 }
174 catch(\Guzzle\Http\Exception\BadResponseException $e) {
175 $response = $e->getResponse();
176 if (isset($response) && is_object($response) && $response instanceof \Guzzle\Http\Message\Response) {
177 $status = $response->getStatusCode();
178 $message = $response->getReasonPhrase();
179 }
180 else {
181 $status = 0;
182 $message = 'Unknown error (this may mean the endpoint is missing or not responding) ';
183 }
184 ldt_log_http_error($status, $message);
185 }
186 }
187 else {
188 // Use drupal_http_request as a fallback.
189 $vars = array(
190 'headers' => array(),
191 );
192 if (array_key_exists('accept', $format) && is_array($format['accept']) && !empty($format['accept'])) {
193 $accept_headers = array();
194 foreach ($format['accept'] as $accept) {
195 $accept_headers[] = $accept;
196 }
197 $vars['headers']['Accept'] = $accept_headers;
198 }
199 $result = drupal_http_request($uri, $vars);
200 if (isset($result->data)) {
201
202 $data = $result->data;
203 }
204 }
205
206 return $data;
207 }
208
209 /**
210 * Extract resources specified as SKOS 'narrower'.
211 *
212 * @param \Drupal\ldt\Library\LibraryWrapperInterface $tool
213 * An EasyRdf Graph object.
214 *
215 * @return array
216 * An array of resource objects.
217 */
218 function ldt_extract_skos_narrower($tool) {
219
220 $namespaces = $tool->getNamespaces();
221 if (!array_key_exists('skos', $namespaces)) {
222 $tool->addNamespace('skos', 'http://www.w3.org/2004/02/skos/core#');
223 }
224
225 $resources = $tool->extractResources('skos:narrower');
226 $results = $tool->fetchResources($resources);
227
228 return $results;
229 }
230
231 /**
232 * Extract resources specified as SKOS 'broader'.
233 *
234 * @param string $uri
235 * The URI to import from.
236 * @param string $tool_plugin
237 * Name of the plugin to use.
238 * @param string $format
239 * The data format.
240 *
241 * @return array
242 * An array of resource objects.
243 */
244 function ldt_extract_skos_broader($uri, $tool_plugin = LDT_DEFAULT_LIBRARY, $format = LDT_DEFAULT_FORMAT) {
245
246 $tool = ldt_graph_uri($uri, LDT_DEFAULT_FORMAT, $tool_plugin);
247 $namespaces = $tool->getNamespaces();
248 if (!array_key_exists('skos', $namespaces)) {
249 $tool->addNamespace('skos', 'http://www.w3.org/2004/02/skos/core#');
250 }
251
252 $resources = $tool->extractResources('skos:broader');
253
254 $tool = ldt_tool($tool_plugin);
255 $namespaces = $tool->getNamespaces();
256 if (!array_key_exists('skos', $namespaces)) {
257 $tool->addNamespace('skos', 'http://www.w3.org/2004/02/skos/core#');
258 }
259
260 $results = $tool->fetchResources($resources);
261
262 return $results;
263 }
264
265 /**
266 * Extract resources specified as Dublin Core Terms 'subject'.
267 *
268 * @param string $uri
269 * The URI to import from.
270 * @param string $tool_plugin
271 * Name of the plugin to use.
272 * @param string $format
273 * The data format.
274 *
275 * @return array
276 * An array of resource objects.
277 */
278 function ldt_extract_dc_subjects($uri, $tool_plugin = LDT_DEFAULT_LIBRARY, $format = LDT_DEFAULT_FORMAT) {
279
280 $tool = ldt_graph_uri($uri, $format, $tool_plugin);
281 $namespaces = $tool->getNamespaces();
282 if (!array_key_exists('dcterms', $namespaces)) {
283 $tool->addNamespace('dcterms', 'http://purl.org/dc/terms/');
284 }
285
286 $resources = $tool->extractResources('dcterms:subject');
287
288 $tool = ldt_tool($tool_plugin);
289 $namespaces = $tool->getNamespaces();
290 if (!array_key_exists('dcterms', $namespaces)) {
291 $tool->addNamespace('dcterms', 'http://purl.org/dc/terms/');
292 }
293
294 $results = $tool->fetchResources($resources);
295
296 return $results;
297 }